diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py new file mode 100644 index 0000000000000000000000000000000000000000..17bedf44748fbcf9e65e9b2aee1a94621d1b709e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_from_model.py @@ -0,0 +1,704 @@ +import re +import warnings +from unittest.mock import Mock + +import numpy as np +import pytest + +from sklearn import datasets +from sklearn.base import BaseEstimator +from sklearn.cross_decomposition import CCA, PLSCanonical, PLSRegression +from sklearn.datasets import make_friedman1, make_regression +from sklearn.decomposition import PCA +from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier +from sklearn.exceptions import NotFittedError +from sklearn.feature_selection import SelectFromModel +from sklearn.linear_model import ( + ElasticNet, + ElasticNetCV, + Lasso, + LassoCV, + LinearRegression, + LogisticRegression, + PassiveAggressiveClassifier, + SGDClassifier, +) +from sklearn.pipeline import make_pipeline +from sklearn.svm import LinearSVC +from sklearn.utils._testing import ( + MinimalClassifier, + assert_allclose, + assert_array_almost_equal, + assert_array_equal, + skip_if_32bit, +) + + +class NaNTag(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = True + return tags + + +class NoNaNTag(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = False + return tags + + +class NaNTagRandomForest(RandomForestClassifier): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = True + return tags + + +iris = datasets.load_iris() +data, y = iris.data, iris.target + + +def test_invalid_input(): + clf = SGDClassifier( + alpha=0.1, max_iter=10, shuffle=True, random_state=None, tol=None + ) + for threshold in ["gobbledigook", ".5 * gobbledigook"]: + model = SelectFromModel(clf, threshold=threshold) + model.fit(data, y) + with pytest.raises(ValueError): + model.transform(data) + + +def test_input_estimator_unchanged(): + # Test that SelectFromModel fits on a clone of the estimator. + est = RandomForestClassifier() + transformer = SelectFromModel(estimator=est) + transformer.fit(data, y) + assert transformer.estimator is est + + +@pytest.mark.parametrize( + "max_features, err_type, err_msg", + [ + ( + data.shape[1] + 1, + ValueError, + "max_features ==", + ), + ( + lambda X: 1.5, + TypeError, + "max_features must be an instance of int, not float.", + ), + ( + lambda X: data.shape[1] + 1, + ValueError, + "max_features ==", + ), + ( + lambda X: -1, + ValueError, + "max_features ==", + ), + ], +) +def test_max_features_error(max_features, err_type, err_msg): + err_msg = re.escape(err_msg) + clf = RandomForestClassifier(n_estimators=5, random_state=0) + + transformer = SelectFromModel( + estimator=clf, max_features=max_features, threshold=-np.inf + ) + with pytest.raises(err_type, match=err_msg): + transformer.fit(data, y) + + +@pytest.mark.parametrize("max_features", [0, 2, data.shape[1], None]) +def test_inferred_max_features_integer(max_features): + """Check max_features_ and output shape for integer max_features.""" + clf = RandomForestClassifier(n_estimators=5, random_state=0) + transformer = SelectFromModel( + estimator=clf, max_features=max_features, threshold=-np.inf + ) + X_trans = transformer.fit_transform(data, y) + if max_features is not None: + assert transformer.max_features_ == max_features + assert X_trans.shape[1] == transformer.max_features_ + else: + assert not hasattr(transformer, "max_features_") + assert X_trans.shape[1] == data.shape[1] + + +@pytest.mark.parametrize( + "max_features", + [lambda X: 1, lambda X: X.shape[1], lambda X: min(X.shape[1], 10000)], +) +def test_inferred_max_features_callable(max_features): + """Check max_features_ and output shape for callable max_features.""" + clf = RandomForestClassifier(n_estimators=5, random_state=0) + transformer = SelectFromModel( + estimator=clf, max_features=max_features, threshold=-np.inf + ) + X_trans = transformer.fit_transform(data, y) + assert transformer.max_features_ == max_features(data) + assert X_trans.shape[1] == transformer.max_features_ + + +@pytest.mark.parametrize("max_features", [lambda X: round(len(X[0]) / 2), 2]) +def test_max_features_array_like(max_features): + X = [ + [0.87, -1.34, 0.31], + [-2.79, -0.02, -0.85], + [-1.34, -0.48, -2.55], + [1.92, 1.48, 0.65], + ] + y = [0, 1, 0, 1] + + clf = RandomForestClassifier(n_estimators=5, random_state=0) + transformer = SelectFromModel( + estimator=clf, max_features=max_features, threshold=-np.inf + ) + X_trans = transformer.fit_transform(X, y) + assert X_trans.shape[1] == transformer.max_features_ + + +@pytest.mark.parametrize( + "max_features", + [lambda X: min(X.shape[1], 10000), lambda X: X.shape[1], lambda X: 1], +) +def test_max_features_callable_data(max_features): + """Tests that the callable passed to `fit` is called on X.""" + clf = RandomForestClassifier(n_estimators=50, random_state=0) + m = Mock(side_effect=max_features) + transformer = SelectFromModel(estimator=clf, max_features=m, threshold=-np.inf) + transformer.fit_transform(data, y) + m.assert_called_with(data) + + +class FixedImportanceEstimator(BaseEstimator): + def __init__(self, importances): + self.importances = importances + + def fit(self, X, y=None): + self.feature_importances_ = np.array(self.importances) + + +def test_max_features(): + # Test max_features parameter using various values + X, y = datasets.make_classification( + n_samples=1000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + max_features = X.shape[1] + est = RandomForestClassifier(n_estimators=50, random_state=0) + + transformer1 = SelectFromModel(estimator=est, threshold=-np.inf) + transformer2 = SelectFromModel( + estimator=est, max_features=max_features, threshold=-np.inf + ) + X_new1 = transformer1.fit_transform(X, y) + X_new2 = transformer2.fit_transform(X, y) + assert_allclose(X_new1, X_new2) + + # Test max_features against actual model. + transformer1 = SelectFromModel(estimator=Lasso(alpha=0.025, random_state=42)) + X_new1 = transformer1.fit_transform(X, y) + scores1 = np.abs(transformer1.estimator_.coef_) + candidate_indices1 = np.argsort(-scores1, kind="mergesort") + + for n_features in range(1, X_new1.shape[1] + 1): + transformer2 = SelectFromModel( + estimator=Lasso(alpha=0.025, random_state=42), + max_features=n_features, + threshold=-np.inf, + ) + X_new2 = transformer2.fit_transform(X, y) + scores2 = np.abs(transformer2.estimator_.coef_) + candidate_indices2 = np.argsort(-scores2, kind="mergesort") + assert_allclose( + X[:, candidate_indices1[:n_features]], X[:, candidate_indices2[:n_features]] + ) + assert_allclose(transformer1.estimator_.coef_, transformer2.estimator_.coef_) + + +def test_max_features_tiebreak(): + # Test if max_features can break tie among feature importance + X, y = datasets.make_classification( + n_samples=1000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + max_features = X.shape[1] + + feature_importances = np.array([4, 4, 4, 4, 3, 3, 3, 2, 2, 1]) + for n_features in range(1, max_features + 1): + transformer = SelectFromModel( + FixedImportanceEstimator(feature_importances), + max_features=n_features, + threshold=-np.inf, + ) + X_new = transformer.fit_transform(X, y) + selected_feature_indices = np.where(transformer._get_support_mask())[0] + assert_array_equal(selected_feature_indices, np.arange(n_features)) + assert X_new.shape[1] == n_features + + +def test_threshold_and_max_features(): + X, y = datasets.make_classification( + n_samples=1000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + est = RandomForestClassifier(n_estimators=50, random_state=0) + + transformer1 = SelectFromModel(estimator=est, max_features=3, threshold=-np.inf) + X_new1 = transformer1.fit_transform(X, y) + + transformer2 = SelectFromModel(estimator=est, threshold=0.04) + X_new2 = transformer2.fit_transform(X, y) + + transformer3 = SelectFromModel(estimator=est, max_features=3, threshold=0.04) + X_new3 = transformer3.fit_transform(X, y) + assert X_new3.shape[1] == min(X_new1.shape[1], X_new2.shape[1]) + selected_indices = transformer3.transform(np.arange(X.shape[1])[np.newaxis, :]) + assert_allclose(X_new3, X[:, selected_indices[0]]) + + +@skip_if_32bit +def test_feature_importances(): + X, y = datasets.make_classification( + n_samples=1000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + est = RandomForestClassifier(n_estimators=50, random_state=0) + for threshold, func in zip(["mean", "median"], [np.mean, np.median]): + transformer = SelectFromModel(estimator=est, threshold=threshold) + transformer.fit(X, y) + assert hasattr(transformer.estimator_, "feature_importances_") + + X_new = transformer.transform(X) + assert X_new.shape[1] < X.shape[1] + importances = transformer.estimator_.feature_importances_ + + feature_mask = np.abs(importances) > func(importances) + assert_array_almost_equal(X_new, X[:, feature_mask]) + + +def test_sample_weight(): + # Ensure sample weights are passed to underlying estimator + X, y = datasets.make_classification( + n_samples=100, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + # Check with sample weights + sample_weight = np.ones(y.shape) + sample_weight[y == 1] *= 100 + + est = LogisticRegression(random_state=0, fit_intercept=False) + transformer = SelectFromModel(estimator=est) + transformer.fit(X, y, sample_weight=None) + mask = transformer._get_support_mask() + transformer.fit(X, y, sample_weight=sample_weight) + weighted_mask = transformer._get_support_mask() + assert not np.all(weighted_mask == mask) + transformer.fit(X, y, sample_weight=3 * sample_weight) + reweighted_mask = transformer._get_support_mask() + assert np.all(weighted_mask == reweighted_mask) + + +@pytest.mark.parametrize( + "estimator", + [ + Lasso(alpha=0.1, random_state=42), + LassoCV(random_state=42), + ElasticNet(l1_ratio=1, random_state=42), + ElasticNetCV(l1_ratio=[1], random_state=42), + ], +) +def test_coef_default_threshold(estimator): + X, y = datasets.make_classification( + n_samples=100, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + ) + + # For the Lasso and related models, the threshold defaults to 1e-5 + transformer = SelectFromModel(estimator=estimator) + transformer.fit(X, y) + X_new = transformer.transform(X) + mask = np.abs(transformer.estimator_.coef_) > 1e-5 + assert_array_almost_equal(X_new, X[:, mask]) + + +@skip_if_32bit +def test_2d_coef(): + X, y = datasets.make_classification( + n_samples=1000, + n_features=10, + n_informative=3, + n_redundant=0, + n_repeated=0, + shuffle=False, + random_state=0, + n_classes=4, + ) + + est = LogisticRegression() + for threshold, func in zip(["mean", "median"], [np.mean, np.median]): + for order in [1, 2, np.inf]: + # Fit SelectFromModel a multi-class problem + transformer = SelectFromModel( + estimator=LogisticRegression(), threshold=threshold, norm_order=order + ) + transformer.fit(X, y) + assert hasattr(transformer.estimator_, "coef_") + X_new = transformer.transform(X) + assert X_new.shape[1] < X.shape[1] + + # Manually check that the norm is correctly performed + est.fit(X, y) + importances = np.linalg.norm(est.coef_, axis=0, ord=order) + feature_mask = importances > func(importances) + assert_array_almost_equal(X_new, X[:, feature_mask]) + + +def test_partial_fit(): + est = PassiveAggressiveClassifier( + random_state=0, shuffle=False, max_iter=5, tol=None + ) + transformer = SelectFromModel(estimator=est) + transformer.partial_fit(data, y, classes=np.unique(y)) + old_model = transformer.estimator_ + transformer.partial_fit(data, y, classes=np.unique(y)) + new_model = transformer.estimator_ + assert old_model is new_model + + X_transform = transformer.transform(data) + transformer.fit(np.vstack((data, data)), np.concatenate((y, y))) + assert_array_almost_equal(X_transform, transformer.transform(data)) + + # check that if est doesn't have partial_fit, neither does SelectFromModel + transformer = SelectFromModel(estimator=RandomForestClassifier()) + assert not hasattr(transformer, "partial_fit") + + +def test_calling_fit_reinitializes(): + est = LinearSVC(random_state=0) + transformer = SelectFromModel(estimator=est) + transformer.fit(data, y) + transformer.set_params(estimator__C=100) + transformer.fit(data, y) + assert transformer.estimator_.C == 100 + + +def test_prefit(): + # Test all possible combinations of the prefit parameter. + + # Passing a prefit parameter with the selected model + # and fitting a unfit model with prefit=False should give same results. + clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None) + model = SelectFromModel(clf) + model.fit(data, y) + X_transform = model.transform(data) + clf.fit(data, y) + model = SelectFromModel(clf, prefit=True) + assert_array_almost_equal(model.transform(data), X_transform) + model.fit(data, y) + assert model.estimator_ is not clf + + # Check that the model is rewritten if prefit=False and a fitted model is + # passed + model = SelectFromModel(clf, prefit=False) + model.fit(data, y) + assert_array_almost_equal(model.transform(data), X_transform) + + # Check that passing an unfitted estimator with `prefit=True` raises a + # `ValueError` + clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None) + model = SelectFromModel(clf, prefit=True) + err_msg = "When `prefit=True`, `estimator` is expected to be a fitted estimator." + with pytest.raises(NotFittedError, match=err_msg): + model.fit(data, y) + with pytest.raises(NotFittedError, match=err_msg): + model.partial_fit(data, y) + with pytest.raises(NotFittedError, match=err_msg): + model.transform(data) + + # Check that the internal parameters of prefitted model are not changed + # when calling `fit` or `partial_fit` with `prefit=True` + clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, tol=None).fit(data, y) + model = SelectFromModel(clf, prefit=True) + model.fit(data, y) + assert_allclose(model.estimator_.coef_, clf.coef_) + model.partial_fit(data, y) + assert_allclose(model.estimator_.coef_, clf.coef_) + + +def test_prefit_max_features(): + """Check the interaction between `prefit` and `max_features`.""" + # case 1: an error should be raised at `transform` if `fit` was not called to + # validate the attributes + estimator = RandomForestClassifier(n_estimators=5, random_state=0) + estimator.fit(data, y) + model = SelectFromModel(estimator, prefit=True, max_features=lambda X: X.shape[1]) + + err_msg = ( + "When `prefit=True` and `max_features` is a callable, call `fit` " + "before calling `transform`." + ) + with pytest.raises(NotFittedError, match=err_msg): + model.transform(data) + + # case 2: `max_features` is not validated and different from an integer + # FIXME: we cannot validate the upper bound of the attribute at transform + # and we should force calling `fit` if we intend to force the attribute + # to have such an upper bound. + max_features = 2.5 + model.set_params(max_features=max_features) + with pytest.raises(ValueError, match="`max_features` must be an integer"): + model.transform(data) + + +def test_get_feature_names_out_elasticnetcv(): + """Check if ElasticNetCV works with a list of floats. + + Non-regression test for #30936.""" + X, y = make_regression(n_features=5, n_informative=3, random_state=0) + estimator = ElasticNetCV(l1_ratio=[0.25, 0.5, 0.75], random_state=0) + selector = SelectFromModel(estimator=estimator) + selector.fit(X, y) + + names_out = selector.get_feature_names_out() + mask = selector.get_support() + expected = np.array([f"x{i}" for i in range(X.shape[1])])[mask] + assert_array_equal(names_out, expected) + + +def test_prefit_get_feature_names_out(): + """Check the interaction between prefit and the feature names.""" + clf = RandomForestClassifier(n_estimators=2, random_state=0) + clf.fit(data, y) + model = SelectFromModel(clf, prefit=True, max_features=1) + + name = type(model).__name__ + err_msg = ( + f"This {name} instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using this estimator." + ) + with pytest.raises(NotFittedError, match=err_msg): + model.get_feature_names_out() + + model.fit(data, y) + feature_names = model.get_feature_names_out() + assert feature_names == ["x3"] + + +def test_threshold_string(): + est = RandomForestClassifier(n_estimators=50, random_state=0) + model = SelectFromModel(est, threshold="0.5*mean") + model.fit(data, y) + X_transform = model.transform(data) + + # Calculate the threshold from the estimator directly. + est.fit(data, y) + threshold = 0.5 * np.mean(est.feature_importances_) + mask = est.feature_importances_ > threshold + assert_array_almost_equal(X_transform, data[:, mask]) + + +def test_threshold_without_refitting(): + # Test that the threshold can be set without refitting the model. + clf = SGDClassifier(alpha=0.1, max_iter=10, shuffle=True, random_state=0, tol=None) + model = SelectFromModel(clf, threshold="0.1 * mean") + model.fit(data, y) + X_transform = model.transform(data) + + # Set a higher threshold to filter out more features. + model.threshold = "1.0 * mean" + assert X_transform.shape[1] > model.transform(data).shape[1] + + +def test_fit_accepts_nan_inf(): + # Test that fit doesn't check for np.inf and np.nan values. + clf = HistGradientBoostingClassifier(random_state=0) + + model = SelectFromModel(estimator=clf) + + nan_data = data.copy() + nan_data[0] = np.nan + nan_data[1] = np.inf + + model.fit(data, y) + + +def test_transform_accepts_nan_inf(): + # Test that transform doesn't check for np.inf and np.nan values. + clf = NaNTagRandomForest(n_estimators=100, random_state=0) + nan_data = data.copy() + + model = SelectFromModel(estimator=clf) + model.fit(nan_data, y) + + nan_data[0] = np.nan + nan_data[1] = np.inf + + model.transform(nan_data) + + +def test_allow_nan_tag_comes_from_estimator(): + allow_nan_est = NaNTag() + model = SelectFromModel(estimator=allow_nan_est) + assert model.__sklearn_tags__().input_tags.allow_nan is True + + no_nan_est = NoNaNTag() + model = SelectFromModel(estimator=no_nan_est) + assert model.__sklearn_tags__().input_tags.allow_nan is False + + +def _pca_importances(pca_estimator): + return np.abs(pca_estimator.explained_variance_) + + +@pytest.mark.parametrize( + "estimator, importance_getter", + [ + ( + make_pipeline(PCA(random_state=0), LogisticRegression()), + "named_steps.logisticregression.coef_", + ), + (PCA(random_state=0), _pca_importances), + ], +) +def test_importance_getter(estimator, importance_getter): + selector = SelectFromModel( + estimator, threshold="mean", importance_getter=importance_getter + ) + selector.fit(data, y) + assert selector.transform(data).shape[1] == 1 + + +@pytest.mark.parametrize("PLSEstimator", [CCA, PLSCanonical, PLSRegression]) +def test_select_from_model_pls(PLSEstimator): + """Check the behaviour of SelectFromModel with PLS estimators. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/12410 + """ + X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) + estimator = PLSEstimator(n_components=1) + model = make_pipeline(SelectFromModel(estimator), estimator).fit(X, y) + assert model.score(X, y) > 0.5 + + +def test_estimator_does_not_support_feature_names(): + """SelectFromModel works with estimators that do not support feature_names_in_. + + Non-regression test for #21949. + """ + pytest.importorskip("pandas") + X, y = datasets.load_iris(as_frame=True, return_X_y=True) + all_feature_names = set(X.columns) + + def importance_getter(estimator): + return np.arange(X.shape[1]) + + selector = SelectFromModel( + MinimalClassifier(), importance_getter=importance_getter + ).fit(X, y) + + # selector learns the feature names itself + assert_array_equal(selector.feature_names_in_, X.columns) + + feature_names_out = set(selector.get_feature_names_out()) + assert feature_names_out < all_feature_names + + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + + selector.transform(X.iloc[1:3]) + + +@pytest.mark.parametrize( + "error, err_msg, max_features", + ( + [ValueError, "max_features == 10, must be <= 4", 10], + [ValueError, "max_features == 5, must be <= 4", lambda x: x.shape[1] + 1], + ), +) +def test_partial_fit_validate_max_features(error, err_msg, max_features): + """Test that partial_fit from SelectFromModel validates `max_features`.""" + X, y = datasets.make_classification( + n_samples=100, + n_features=4, + random_state=0, + ) + + with pytest.raises(error, match=err_msg): + SelectFromModel( + estimator=SGDClassifier(), max_features=max_features + ).partial_fit(X, y, classes=[0, 1]) + + +@pytest.mark.parametrize("as_frame", [True, False]) +def test_partial_fit_validate_feature_names(as_frame): + """Test that partial_fit from SelectFromModel validates `feature_names_in_`.""" + pytest.importorskip("pandas") + X, y = datasets.load_iris(as_frame=as_frame, return_X_y=True) + + selector = SelectFromModel(estimator=SGDClassifier(), max_features=4).partial_fit( + X, y, classes=[0, 1, 2] + ) + if as_frame: + assert_array_equal(selector.feature_names_in_, X.columns) + else: + assert not hasattr(selector, "feature_names_in_") + + +def test_from_model_estimator_attribute_error(): + """Check that we raise the proper AttributeError when the estimator + does not implement the `partial_fit` method, which is decorated with + `available_if`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/28108 + """ + # `LinearRegression` does not implement 'partial_fit' and should raise an + # AttributeError + from_model = SelectFromModel(estimator=LinearRegression()) + + outer_msg = "This 'SelectFromModel' has no attribute 'partial_fit'" + inner_msg = "'LinearRegression' object has no attribute 'partial_fit'" + with pytest.raises(AttributeError, match=outer_msg) as exec_info: + from_model.fit(data, y).partial_fit(data) + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg in str(exec_info.value.__cause__) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py new file mode 100644 index 0000000000000000000000000000000000000000..4922b7e4e57b352456e8295d7dba44feb4eef535 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_mutual_info.py @@ -0,0 +1,270 @@ +import numpy as np +import pytest + +from sklearn.datasets import make_classification, make_regression +from sklearn.feature_selection import mutual_info_classif, mutual_info_regression +from sklearn.feature_selection._mutual_info import _compute_mi +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + assert_allclose, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +def test_compute_mi_dd(): + # In discrete case computations are straightforward and can be done + # by hand on given vectors. + x = np.array([0, 1, 1, 0, 0]) + y = np.array([1, 0, 0, 0, 1]) + + H_x = H_y = -(3 / 5) * np.log(3 / 5) - (2 / 5) * np.log(2 / 5) + H_xy = -1 / 5 * np.log(1 / 5) - 2 / 5 * np.log(2 / 5) - 2 / 5 * np.log(2 / 5) + I_xy = H_x + H_y - H_xy + + assert_allclose(_compute_mi(x, y, x_discrete=True, y_discrete=True), I_xy) + + +def test_compute_mi_cc(global_dtype): + # For two continuous variables a good approach is to test on bivariate + # normal distribution, where mutual information is known. + + # Mean of the distribution, irrelevant for mutual information. + mean = np.zeros(2) + + # Setup covariance matrix with correlation coeff. equal 0.5. + sigma_1 = 1 + sigma_2 = 10 + corr = 0.5 + cov = np.array( + [ + [sigma_1**2, corr * sigma_1 * sigma_2], + [corr * sigma_1 * sigma_2, sigma_2**2], + ] + ) + + # True theoretical mutual information. + I_theory = np.log(sigma_1) + np.log(sigma_2) - 0.5 * np.log(np.linalg.det(cov)) + + rng = check_random_state(0) + Z = rng.multivariate_normal(mean, cov, size=1000).astype(global_dtype, copy=False) + + x, y = Z[:, 0], Z[:, 1] + + # Theory and computed values won't be very close + # We here check with a large relative tolerance + for n_neighbors in [3, 5, 7]: + I_computed = _compute_mi( + x, y, x_discrete=False, y_discrete=False, n_neighbors=n_neighbors + ) + assert_allclose(I_computed, I_theory, rtol=1e-1) + + +def test_compute_mi_cd(global_dtype): + # To test define a joint distribution as follows: + # p(x, y) = p(x) p(y | x) + # X ~ Bernoulli(p) + # (Y | x = 0) ~ Uniform(-1, 1) + # (Y | x = 1) ~ Uniform(0, 2) + + # Use the following formula for mutual information: + # I(X; Y) = H(Y) - H(Y | X) + # Two entropies can be computed by hand: + # H(Y) = -(1-p)/2 * ln((1-p)/2) - p/2*log(p/2) - 1/2*log(1/2) + # H(Y | X) = ln(2) + + # Now we need to implement sampling from out distribution, which is + # done easily using conditional distribution logic. + + n_samples = 1000 + rng = check_random_state(0) + + for p in [0.3, 0.5, 0.7]: + x = rng.uniform(size=n_samples) > p + + y = np.empty(n_samples, global_dtype) + mask = x == 0 + y[mask] = rng.uniform(-1, 1, size=np.sum(mask)) + y[~mask] = rng.uniform(0, 2, size=np.sum(~mask)) + + I_theory = -0.5 * ( + (1 - p) * np.log(0.5 * (1 - p)) + p * np.log(0.5 * p) + np.log(0.5) + ) - np.log(2) + + # Assert the same tolerance. + for n_neighbors in [3, 5, 7]: + I_computed = _compute_mi( + x, y, x_discrete=True, y_discrete=False, n_neighbors=n_neighbors + ) + assert_allclose(I_computed, I_theory, rtol=1e-1) + + +def test_compute_mi_cd_unique_label(global_dtype): + # Test that adding unique label doesn't change MI. + n_samples = 100 + x = np.random.uniform(size=n_samples) > 0.5 + + y = np.empty(n_samples, global_dtype) + mask = x == 0 + y[mask] = np.random.uniform(-1, 1, size=np.sum(mask)) + y[~mask] = np.random.uniform(0, 2, size=np.sum(~mask)) + + mi_1 = _compute_mi(x, y, x_discrete=True, y_discrete=False) + + x = np.hstack((x, 2)) + y = np.hstack((y, 10)) + mi_2 = _compute_mi(x, y, x_discrete=True, y_discrete=False) + + assert_allclose(mi_1, mi_2) + + +# We are going test that feature ordering by MI matches our expectations. +def test_mutual_info_classif_discrete(global_dtype): + X = np.array( + [[0, 0, 0], [1, 1, 0], [2, 0, 1], [2, 0, 1], [2, 0, 1]], dtype=global_dtype + ) + y = np.array([0, 1, 2, 2, 1]) + + # Here X[:, 0] is the most informative feature, and X[:, 1] is weakly + # informative. + mi = mutual_info_classif(X, y, discrete_features=True) + assert_array_equal(np.argsort(-mi), np.array([0, 2, 1])) + + +def test_mutual_info_regression(global_dtype): + # We generate sample from multivariate normal distribution, using + # transformation from initially uncorrelated variables. The zero + # variables after transformation is selected as the target vector, + # it has the strongest correlation with the variable 2, and + # the weakest correlation with the variable 1. + T = np.array([[1, 0.5, 2, 1], [0, 1, 0.1, 0.0], [0, 0.1, 1, 0.1], [0, 0.1, 0.1, 1]]) + cov = T.dot(T.T) + mean = np.zeros(4) + + rng = check_random_state(0) + Z = rng.multivariate_normal(mean, cov, size=1000).astype(global_dtype, copy=False) + X = Z[:, 1:] + y = Z[:, 0] + + mi = mutual_info_regression(X, y, random_state=0) + assert_array_equal(np.argsort(-mi), np.array([1, 2, 0])) + # XXX: should mutual_info_regression be fixed to avoid + # up-casting float32 inputs to float64? + assert mi.dtype == np.float64 + + +def test_mutual_info_classif_mixed(global_dtype): + # Here the target is discrete and there are two continuous and one + # discrete feature. The idea of this test is clear from the code. + rng = check_random_state(0) + X = rng.rand(1000, 3).astype(global_dtype, copy=False) + X[:, 1] += X[:, 0] + y = ((0.5 * X[:, 0] + X[:, 2]) > 0.5).astype(int) + X[:, 2] = X[:, 2] > 0.5 + + mi = mutual_info_classif(X, y, discrete_features=[2], n_neighbors=3, random_state=0) + assert_array_equal(np.argsort(-mi), [2, 0, 1]) + for n_neighbors in [5, 7, 9]: + mi_nn = mutual_info_classif( + X, y, discrete_features=[2], n_neighbors=n_neighbors, random_state=0 + ) + # Check that the continuous values have an higher MI with greater + # n_neighbors + assert mi_nn[0] > mi[0] + assert mi_nn[1] > mi[1] + # The n_neighbors should not have any effect on the discrete value + # The MI should be the same + assert mi_nn[2] == mi[2] + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_mutual_info_options(global_dtype, csr_container): + X = np.array( + [[0, 0, 0], [1, 1, 0], [2, 0, 1], [2, 0, 1], [2, 0, 1]], dtype=global_dtype + ) + y = np.array([0, 1, 2, 2, 1], dtype=global_dtype) + X_csr = csr_container(X) + + for mutual_info in (mutual_info_regression, mutual_info_classif): + with pytest.raises(ValueError): + mutual_info(X_csr, y, discrete_features=False) + with pytest.raises(ValueError): + mutual_info(X, y, discrete_features="manual") + with pytest.raises(ValueError): + mutual_info(X_csr, y, discrete_features=[True, False, True]) + with pytest.raises(IndexError): + mutual_info(X, y, discrete_features=[True, False, True, False]) + with pytest.raises(IndexError): + mutual_info(X, y, discrete_features=[1, 4]) + + mi_1 = mutual_info(X, y, discrete_features="auto", random_state=0) + mi_2 = mutual_info(X, y, discrete_features=False, random_state=0) + mi_3 = mutual_info(X_csr, y, discrete_features="auto", random_state=0) + mi_4 = mutual_info(X_csr, y, discrete_features=True, random_state=0) + mi_5 = mutual_info(X, y, discrete_features=[True, False, True], random_state=0) + mi_6 = mutual_info(X, y, discrete_features=[0, 2], random_state=0) + + assert_allclose(mi_1, mi_2) + assert_allclose(mi_3, mi_4) + assert_allclose(mi_5, mi_6) + + assert not np.allclose(mi_1, mi_3) + + +@pytest.mark.parametrize("correlated", [True, False]) +def test_mutual_information_symmetry_classif_regression(correlated, global_random_seed): + """Check that `mutual_info_classif` and `mutual_info_regression` are + symmetric by switching the target `y` as `feature` in `X` and vice + versa. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/23720 + """ + rng = np.random.RandomState(global_random_seed) + n = 100 + d = rng.randint(10, size=n) + + if correlated: + c = d.astype(np.float64) + else: + c = rng.normal(0, 1, size=n) + + mi_classif = mutual_info_classif( + c[:, None], d, discrete_features=[False], random_state=global_random_seed + ) + + mi_regression = mutual_info_regression( + d[:, None], c, discrete_features=[True], random_state=global_random_seed + ) + + assert mi_classif == pytest.approx(mi_regression) + + +def test_mutual_info_regression_X_int_dtype(global_random_seed): + """Check that results agree when X is integer dtype and float dtype. + + Non-regression test for Issue #26696. + """ + rng = np.random.RandomState(global_random_seed) + X = rng.randint(100, size=(100, 10)) + X_float = X.astype(np.float64, copy=True) + y = rng.randint(100, size=100) + + expected = mutual_info_regression(X_float, y, random_state=global_random_seed) + result = mutual_info_regression(X, y, random_state=global_random_seed) + assert_allclose(result, expected) + + +@pytest.mark.parametrize( + "mutual_info_func, data_generator", + [ + (mutual_info_regression, make_regression), + (mutual_info_classif, make_classification), + ], +) +def test_mutual_info_n_jobs(global_random_seed, mutual_info_func, data_generator): + """Check that results are consistent with different `n_jobs`.""" + X, y = data_generator(random_state=global_random_seed) + single_job = mutual_info_func(X, y, random_state=global_random_seed, n_jobs=1) + multi_job = mutual_info_func(X, y, random_state=global_random_seed, n_jobs=2) + assert_allclose(single_job, multi_job) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py new file mode 100644 index 0000000000000000000000000000000000000000..1f5672545874c057847a5d135f1c29a7211647e0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_rfe.py @@ -0,0 +1,755 @@ +""" +Testing Recursive feature elimination +""" + +import re +from operator import attrgetter + +import numpy as np +import pytest +from joblib import parallel_backend +from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal + +from sklearn.base import BaseEstimator, ClassifierMixin, is_classifier +from sklearn.compose import TransformedTargetRegressor +from sklearn.cross_decomposition import CCA, PLSCanonical, PLSRegression +from sklearn.datasets import load_iris, make_classification, make_friedman1 +from sklearn.ensemble import RandomForestClassifier +from sklearn.feature_selection import RFE, RFECV +from sklearn.impute import SimpleImputer +from sklearn.linear_model import LinearRegression, LogisticRegression +from sklearn.metrics import get_scorer, make_scorer, zero_one_loss +from sklearn.model_selection import GroupKFold, cross_val_score +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC, SVR, LinearSVR +from sklearn.utils import check_random_state +from sklearn.utils._testing import ignore_warnings +from sklearn.utils.fixes import CSR_CONTAINERS + + +class MockClassifier(ClassifierMixin, BaseEstimator): + """ + Dummy classifier to test recursive feature elimination + """ + + def __init__(self, foo_param=0): + self.foo_param = foo_param + + def fit(self, X, y): + assert len(X) == len(y) + self.coef_ = np.ones(X.shape[1], dtype=np.float64) + self.classes_ = sorted(set(y)) + return self + + def predict(self, T): + return np.ones(T.shape[0]) + + predict_proba = predict + decision_function = predict + transform = predict + + def score(self, X=None, y=None): + return 0.0 + + def get_params(self, deep=True): + return {"foo_param": self.foo_param} + + def set_params(self, **params): + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = True + return tags + + +def test_rfe_features_importance(): + generator = check_random_state(0) + iris = load_iris() + # Add some irrelevant features. Random seed is set to make sure that + # irrelevant features are always irrelevant. + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + + clf = RandomForestClassifier(n_estimators=20, random_state=generator, max_depth=2) + rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) + rfe.fit(X, y) + assert len(rfe.ranking_) == X.shape[1] + + clf_svc = SVC(kernel="linear") + rfe_svc = RFE(estimator=clf_svc, n_features_to_select=4, step=0.1) + rfe_svc.fit(X, y) + + # Check if the supports are equal + assert_array_equal(rfe.get_support(), rfe_svc.get_support()) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_rfe(csr_container): + generator = check_random_state(0) + iris = load_iris() + # Add some irrelevant features. Random seed is set to make sure that + # irrelevant features are always irrelevant. + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + X_sparse = csr_container(X) + y = iris.target + + # dense model + clf = SVC(kernel="linear") + rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) + rfe.fit(X, y) + X_r = rfe.transform(X) + clf.fit(X_r, y) + assert len(rfe.ranking_) == X.shape[1] + + # sparse model + clf_sparse = SVC(kernel="linear") + rfe_sparse = RFE(estimator=clf_sparse, n_features_to_select=4, step=0.1) + rfe_sparse.fit(X_sparse, y) + X_r_sparse = rfe_sparse.transform(X_sparse) + + assert X_r.shape == iris.data.shape + assert_array_almost_equal(X_r[:10], iris.data[:10]) + + assert_array_almost_equal(rfe.predict(X), clf.predict(iris.data)) + assert rfe.score(X, y) == clf.score(iris.data, iris.target) + 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") + + +def test_rfe_percent_n_features(): + # test that the results are the same + generator = check_random_state(0) + iris = load_iris() + # Add some irrelevant features. Random seed is set to make sure that + # irrelevant features are always irrelevant. + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + # there are 10 features in the data. We select 40%. + clf = SVC(kernel="linear") + rfe_num = RFE(estimator=clf, n_features_to_select=4, step=0.1) + rfe_num.fit(X, y) + + rfe_perc = RFE(estimator=clf, n_features_to_select=0.4, step=0.1) + rfe_perc.fit(X, y) + + assert_array_equal(rfe_perc.ranking_, rfe_num.ranking_) + assert_array_equal(rfe_perc.support_, rfe_num.support_) + + +def test_rfe_mockclassifier(): + generator = check_random_state(0) + iris = load_iris() + # Add some irrelevant features. Random seed is set to make sure that + # irrelevant features are always irrelevant. + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + + # dense model + clf = MockClassifier() + rfe = RFE(estimator=clf, n_features_to_select=4, step=0.1) + rfe.fit(X, y) + X_r = rfe.transform(X) + clf.fit(X_r, y) + assert len(rfe.ranking_) == X.shape[1] + assert X_r.shape == iris.data.shape + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_rfecv(csr_container): + generator = check_random_state(0) + iris = load_iris() + # Add some irrelevant features. Random seed is set to make sure that + # irrelevant features are always irrelevant. + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = list(iris.target) # regression test: list should be supported + + # Test using the score function + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1) + rfecv.fit(X, y) + # non-regression test for missing worst feature: + + for key in rfecv.cv_results_.keys(): + assert len(rfecv.cv_results_[key]) == X.shape[1] + + assert len(rfecv.ranking_) == X.shape[1] + X_r = rfecv.transform(X) + + # All the noisy variable were filtered out + assert_array_equal(X_r, iris.data) + + # same in sparse + rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=1) + X_sparse = csr_container(X) + rfecv_sparse.fit(X_sparse, y) + X_r_sparse = rfecv_sparse.transform(X_sparse) + assert_array_equal(X_r_sparse.toarray(), iris.data) + + # Test using a customized loss function + scoring = make_scorer(zero_one_loss, greater_is_better=False) + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=scoring) + ignore_warnings(rfecv.fit)(X, y) + X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) + + # Test using a scorer + scorer = get_scorer("accuracy") + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=scorer) + rfecv.fit(X, y) + X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) + + # Test fix on cv_results_ + def test_scorer(estimator, X, y): + return 1.0 + + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, scoring=test_scorer) + rfecv.fit(X, y) + + # In the event of cross validation score ties, the expected behavior of + # RFECV is to return the FEWEST features that maximize the CV score. + # Because test_scorer always returns 1.0 in this example, RFECV should + # reduce the dimensionality to a single feature (i.e. n_features_ = 1) + assert rfecv.n_features_ == 1 + + # Same as the first two tests, but with step=2 + rfecv = RFECV(estimator=SVC(kernel="linear"), step=2) + rfecv.fit(X, y) + + for key in rfecv.cv_results_.keys(): + assert len(rfecv.cv_results_[key]) == 6 + + assert len(rfecv.ranking_) == X.shape[1] + X_r = rfecv.transform(X) + assert_array_equal(X_r, iris.data) + + rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=2) + X_sparse = csr_container(X) + rfecv_sparse.fit(X_sparse, y) + X_r_sparse = rfecv_sparse.transform(X_sparse) + assert_array_equal(X_r_sparse.toarray(), iris.data) + + # Verifying that steps < 1 don't blow up. + rfecv_sparse = RFECV(estimator=SVC(kernel="linear"), step=0.2) + X_sparse = csr_container(X) + rfecv_sparse.fit(X_sparse, y) + X_r_sparse = rfecv_sparse.transform(X_sparse) + assert_array_equal(X_r_sparse.toarray(), iris.data) + + +def test_rfecv_mockclassifier(): + generator = check_random_state(0) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = list(iris.target) # regression test: list should be supported + + # Test using the score function + rfecv = RFECV(estimator=MockClassifier(), step=1) + rfecv.fit(X, y) + # non-regression test for missing worst feature: + + for key in rfecv.cv_results_.keys(): + assert len(rfecv.cv_results_[key]) == X.shape[1] + + assert len(rfecv.ranking_) == X.shape[1] + + +def test_rfecv_verbose_output(): + # Check verbose=1 is producing an output. + import sys + from io import StringIO + + sys.stdout = StringIO() + + generator = check_random_state(0) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = list(iris.target) + + rfecv = RFECV(estimator=SVC(kernel="linear"), step=1, verbose=1) + rfecv.fit(X, y) + + verbose_output = sys.stdout + verbose_output.seek(0) + assert len(verbose_output.readline()) > 0 + + +def test_rfecv_cv_results_size(global_random_seed): + generator = check_random_state(global_random_seed) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = list(iris.target) # regression test: list should be supported + + # Non-regression test for varying combinations of step and + # min_features_to_select. + for step, min_features_to_select in [[2, 1], [2, 2], [3, 3]]: + rfecv = RFECV( + estimator=MockClassifier(), + step=step, + min_features_to_select=min_features_to_select, + ) + rfecv.fit(X, y) + + score_len = np.ceil((X.shape[1] - min_features_to_select) / step) + 1 + + for key in rfecv.cv_results_.keys(): + assert len(rfecv.cv_results_[key]) == score_len + + assert len(rfecv.ranking_) == X.shape[1] + assert rfecv.n_features_ >= min_features_to_select + + +def test_rfe_estimator_tags(): + rfe = RFE(SVC(kernel="linear")) + assert is_classifier(rfe) + # make sure that cross-validation is stratified + iris = load_iris() + score = cross_val_score(rfe, iris.data, iris.target) + assert score.min() > 0.7 + + +def test_rfe_min_step(global_random_seed): + n_features = 10 + X, y = make_friedman1( + n_samples=50, n_features=n_features, random_state=global_random_seed + ) + n_samples, n_features = X.shape + estimator = SVR(kernel="linear") + + # Test when floor(step * n_features) <= 0 + selector = RFE(estimator, step=0.01) + sel = selector.fit(X, y) + assert sel.support_.sum() == n_features // 2 + + # Test when step is between (0,1) and floor(step * n_features) > 0 + selector = RFE(estimator, step=0.20) + sel = selector.fit(X, y) + assert sel.support_.sum() == n_features // 2 + + # Test when step is an integer + selector = RFE(estimator, step=5) + sel = selector.fit(X, y) + assert sel.support_.sum() == n_features // 2 + + +def test_number_of_subsets_of_features(global_random_seed): + # In RFE, 'number_of_subsets_of_features' + # = the number of iterations in '_fit' + # = max(ranking_) + # = 1 + (n_features + step - n_features_to_select - 1) // step + # After optimization #4534, this number + # = 1 + np.ceil((n_features - n_features_to_select) / float(step)) + # This test case is to test their equivalence, refer to #4534 and #3824 + + def formula1(n_features, n_features_to_select, step): + return 1 + ((n_features + step - n_features_to_select - 1) // step) + + def formula2(n_features, n_features_to_select, step): + return 1 + np.ceil((n_features - n_features_to_select) / float(step)) + + # RFE + # Case 1, n_features - n_features_to_select is divisible by step + # Case 2, n_features - n_features_to_select is not divisible by step + n_features_list = [11, 11] + n_features_to_select_list = [3, 3] + step_list = [2, 3] + for n_features, n_features_to_select, step in zip( + n_features_list, n_features_to_select_list, step_list + ): + generator = check_random_state(global_random_seed) + X = generator.normal(size=(100, n_features)) + y = generator.rand(100).round() + rfe = RFE( + estimator=SVC(kernel="linear"), + n_features_to_select=n_features_to_select, + step=step, + ) + rfe.fit(X, y) + # this number also equals to the maximum of ranking_ + assert np.max(rfe.ranking_) == formula1(n_features, n_features_to_select, step) + assert np.max(rfe.ranking_) == formula2(n_features, n_features_to_select, step) + + # In RFECV, 'fit' calls 'RFE._fit' + # 'number_of_subsets_of_features' of RFE + # = the size of each score in 'cv_results_' of RFECV + # = the number of iterations of the for loop before optimization #4534 + + # RFECV, n_features_to_select = 1 + # Case 1, n_features - 1 is divisible by step + # Case 2, n_features - 1 is not divisible by step + + n_features_to_select = 1 + n_features_list = [11, 10] + step_list = [2, 2] + for n_features, step in zip(n_features_list, step_list): + generator = check_random_state(global_random_seed) + X = generator.normal(size=(100, n_features)) + y = generator.rand(100).round() + rfecv = RFECV(estimator=SVC(kernel="linear"), step=step) + rfecv.fit(X, y) + + for key in rfecv.cv_results_.keys(): + assert len(rfecv.cv_results_[key]) == formula1( + n_features, n_features_to_select, step + ) + assert len(rfecv.cv_results_[key]) == formula2( + n_features, n_features_to_select, step + ) + + +def test_rfe_cv_n_jobs(global_random_seed): + generator = check_random_state(global_random_seed) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + + rfecv = RFECV(estimator=SVC(kernel="linear")) + rfecv.fit(X, y) + rfecv_ranking = rfecv.ranking_ + + rfecv_cv_results_ = rfecv.cv_results_ + + rfecv.set_params(n_jobs=2) + rfecv.fit(X, y) + assert_array_almost_equal(rfecv.ranking_, rfecv_ranking) + + assert rfecv_cv_results_.keys() == rfecv.cv_results_.keys() + for key in rfecv_cv_results_.keys(): + assert rfecv_cv_results_[key] == pytest.approx(rfecv.cv_results_[key]) + + +def test_rfe_cv_groups(): + generator = check_random_state(0) + iris = load_iris() + number_groups = 4 + groups = np.floor(np.linspace(0, number_groups, len(iris.target))) + X = iris.data + y = (iris.target > 0).astype(int) + + est_groups = RFECV( + estimator=RandomForestClassifier(random_state=generator), + step=1, + scoring="accuracy", + cv=GroupKFold(n_splits=2), + ) + est_groups.fit(X, y, groups=groups) + assert est_groups.n_features_ > 0 + + +@pytest.mark.parametrize( + "importance_getter", [attrgetter("regressor_.coef_"), "regressor_.coef_"] +) +@pytest.mark.parametrize("selector, expected_n_features", [(RFE, 5), (RFECV, 4)]) +def test_rfe_wrapped_estimator(importance_getter, selector, expected_n_features): + # Non-regression test for + # https://github.com/scikit-learn/scikit-learn/issues/15312 + X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) + estimator = LinearSVR(random_state=0) + + log_estimator = TransformedTargetRegressor( + regressor=estimator, func=np.log, inverse_func=np.exp + ) + + selector = selector(log_estimator, importance_getter=importance_getter) + sel = selector.fit(X, y) + assert sel.support_.sum() == expected_n_features + + +@pytest.mark.parametrize( + "importance_getter, err_type", + [ + ("auto", ValueError), + ("random", AttributeError), + (lambda x: x.importance, AttributeError), + ], +) +@pytest.mark.parametrize("Selector", [RFE, RFECV]) +def test_rfe_importance_getter_validation(importance_getter, err_type, Selector): + X, y = make_friedman1(n_samples=50, n_features=10, random_state=42) + estimator = LinearSVR() + log_estimator = TransformedTargetRegressor( + regressor=estimator, func=np.log, inverse_func=np.exp + ) + + with pytest.raises(err_type): + model = Selector(log_estimator, importance_getter=importance_getter) + model.fit(X, y) + + +@pytest.mark.parametrize("cv", [None, 5]) +def test_rfe_allow_nan_inf_in_x(cv): + iris = load_iris() + X = iris.data + y = iris.target + + # add nan and inf value to X + X[0][0] = np.nan + X[0][1] = np.inf + + clf = MockClassifier() + if cv is not None: + rfe = RFECV(estimator=clf, cv=cv) + else: + rfe = RFE(estimator=clf) + rfe.fit(X, y) + rfe.transform(X) + + +def test_w_pipeline_2d_coef_(): + pipeline = make_pipeline(StandardScaler(), LogisticRegression()) + + data, y = load_iris(return_X_y=True) + sfm = RFE( + pipeline, + n_features_to_select=2, + importance_getter="named_steps.logisticregression.coef_", + ) + + sfm.fit(data, y) + assert sfm.transform(data).shape[1] == 2 + + +def test_rfecv_std_and_mean(global_random_seed): + generator = check_random_state(global_random_seed) + iris = load_iris() + X = np.c_[iris.data, generator.normal(size=(len(iris.data), 6))] + y = iris.target + + rfecv = RFECV(estimator=SVC(kernel="linear")) + rfecv.fit(X, y) + split_keys = [ + key + for key in rfecv.cv_results_.keys() + if re.search(r"split\d+_test_score", key) + ] + cv_scores = np.asarray([rfecv.cv_results_[key] for key in split_keys]) + expected_mean = np.mean(cv_scores, axis=0) + expected_std = np.std(cv_scores, axis=0) + + assert_allclose(rfecv.cv_results_["mean_test_score"], expected_mean) + assert_allclose(rfecv.cv_results_["std_test_score"], expected_std) + + +@pytest.mark.parametrize( + ["min_features_to_select", "n_features", "step", "cv_results_n_features"], + [ + [1, 4, 1, np.array([1, 2, 3, 4])], + [1, 5, 1, np.array([1, 2, 3, 4, 5])], + [1, 4, 2, np.array([1, 2, 4])], + [1, 5, 2, np.array([1, 3, 5])], + [1, 4, 3, np.array([1, 4])], + [1, 5, 3, np.array([1, 2, 5])], + [1, 4, 4, np.array([1, 4])], + [1, 5, 4, np.array([1, 5])], + [4, 4, 2, np.array([4])], + [4, 5, 1, np.array([4, 5])], + [4, 5, 2, np.array([4, 5])], + ], +) +def test_rfecv_cv_results_n_features( + min_features_to_select, + n_features, + step, + cv_results_n_features, +): + X, y = make_classification( + n_samples=20, n_features=n_features, n_informative=n_features, n_redundant=0 + ) + rfecv = RFECV( + estimator=SVC(kernel="linear"), + step=step, + min_features_to_select=min_features_to_select, + ) + rfecv.fit(X, y) + assert_array_equal(rfecv.cv_results_["n_features"], cv_results_n_features) + assert all( + len(value) == len(rfecv.cv_results_["n_features"]) + for value in rfecv.cv_results_.values() + ) + + +@pytest.mark.parametrize("ClsRFE", [RFE, RFECV]) +def test_multioutput(ClsRFE): + X = np.random.normal(size=(10, 3)) + y = np.random.randint(2, size=(10, 2)) + clf = RandomForestClassifier(n_estimators=5) + rfe_test = ClsRFE(clf) + rfe_test.fit(X, y) + + +@pytest.mark.parametrize("ClsRFE", [RFE, RFECV]) +def test_pipeline_with_nans(ClsRFE): + """Check that RFE works with pipeline that accept nans. + + Non-regression test for gh-21743. + """ + X, y = load_iris(return_X_y=True) + X[0, 0] = np.nan + + pipe = make_pipeline( + SimpleImputer(), + StandardScaler(), + LogisticRegression(), + ) + + fs = ClsRFE( + estimator=pipe, + importance_getter="named_steps.logisticregression.coef_", + ) + fs.fit(X, y) + + +@pytest.mark.parametrize("ClsRFE", [RFE, RFECV]) +@pytest.mark.parametrize("PLSEstimator", [CCA, PLSCanonical, PLSRegression]) +def test_rfe_pls(ClsRFE, PLSEstimator): + """Check the behaviour of RFE with PLS estimators. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/12410 + """ + X, y = make_friedman1(n_samples=50, n_features=10, random_state=0) + estimator = PLSEstimator(n_components=1) + selector = ClsRFE(estimator, step=1).fit(X, y) + assert selector.score(X, y) > 0.5 + + +def test_rfe_estimator_attribute_error(): + """Check that we raise the proper AttributeError when the estimator + does not implement the `decision_function` method, which is decorated with + `available_if`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/28108 + """ + iris = load_iris() + + # `LinearRegression` does not implement 'decision_function' and should raise an + # AttributeError + rfe = RFE(estimator=LinearRegression()) + + outer_msg = "This 'RFE' has no attribute 'decision_function'" + inner_msg = "'LinearRegression' object has no attribute 'decision_function'" + with pytest.raises(AttributeError, match=outer_msg) as exec_info: + rfe.fit(iris.data, iris.target).decision_function(iris.data) + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg in str(exec_info.value.__cause__) + + +@pytest.mark.parametrize( + "ClsRFE, param", [(RFE, "n_features_to_select"), (RFECV, "min_features_to_select")] +) +def test_rfe_n_features_to_select_warning(ClsRFE, param): + """Check if the correct warning is raised when trying to initialize a RFE + object with a n_features_to_select attribute larger than the number of + features present in the X variable that is passed to the fit method + """ + X, y = make_classification(n_features=20, random_state=0) + + with pytest.warns(UserWarning, match=f"{param}=21 > n_features=20"): + # Create RFE/RFECV with n_features_to_select/min_features_to_select + # larger than the number of features present in the X variable + clsrfe = ClsRFE(estimator=LogisticRegression(), **{param: 21}) + clsrfe.fit(X, y) + + +def test_rfe_with_sample_weight(): + """Test that `RFE` works correctly with sample weights.""" + X, y = make_classification(random_state=0) + n_samples = X.shape[0] + + # Assign the first half of the samples with twice the weight + sample_weight = np.ones_like(y) + sample_weight[: n_samples // 2] = 2 + + # Duplicate the first half of the data samples to replicate the effect + # of sample weights for comparison + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + y2 = np.concatenate([y, y[: n_samples // 2]]) + + estimator = SVC(kernel="linear") + + rfe_sw = RFE(estimator=estimator, step=0.1) + rfe_sw.fit(X, y, sample_weight=sample_weight) + + rfe = RFE(estimator=estimator, step=0.1) + rfe.fit(X2, y2) + + assert_array_equal(rfe_sw.ranking_, rfe.ranking_) + + # Also verify that when sample weights are not doubled the results + # are different from the duplicated data + rfe_sw_2 = RFE(estimator=estimator, step=0.1) + sample_weight_2 = np.ones_like(y) + rfe_sw_2.fit(X, y, sample_weight=sample_weight_2) + + assert not np.array_equal(rfe_sw_2.ranking_, rfe.ranking_) + + +def test_rfe_with_joblib_threading_backend(global_random_seed): + X, y = make_classification(random_state=global_random_seed) + + clf = LogisticRegression() + rfe = RFECV( + estimator=clf, + n_jobs=2, + ) + + rfe.fit(X, y) + ranking_ref = rfe.ranking_ + + with parallel_backend("threading"): + rfe.fit(X, y) + + assert_array_equal(ranking_ref, rfe.ranking_) + + +def test_results_per_cv_in_rfecv(global_random_seed): + """ + Test that the results of RFECV are consistent across the different folds + in terms of length of the arrays. + """ + X, y = make_classification(random_state=global_random_seed) + + clf = LogisticRegression() + rfecv = RFECV( + estimator=clf, + n_jobs=2, + cv=5, + ) + + rfecv.fit(X, y) + + assert len(rfecv.cv_results_["split1_test_score"]) == len( + rfecv.cv_results_["split2_test_score"] + ) + assert len(rfecv.cv_results_["split1_support"]) == len( + rfecv.cv_results_["split2_support"] + ) + assert len(rfecv.cv_results_["split1_ranking"]) == len( + rfecv.cv_results_["split2_ranking"] + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py new file mode 100644 index 0000000000000000000000000000000000000000..b98d5b400b84eaa68440c0dbc3891b99372444a2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_sequential.py @@ -0,0 +1,332 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from sklearn.cluster import KMeans +from sklearn.datasets import make_blobs, make_classification, make_regression +from sklearn.ensemble import HistGradientBoostingRegressor +from sklearn.feature_selection import SequentialFeatureSelector +from sklearn.linear_model import LinearRegression +from sklearn.model_selection import LeaveOneGroupOut, cross_val_score +from sklearn.neighbors import KNeighborsClassifier +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils.fixes import CSR_CONTAINERS + + +def test_bad_n_features_to_select(): + n_features = 5 + X, y = make_regression(n_features=n_features) + sfs = SequentialFeatureSelector(LinearRegression(), n_features_to_select=n_features) + with pytest.raises(ValueError, match="n_features_to_select must be < n_features"): + sfs.fit(X, y) + + +@pytest.mark.parametrize("direction", ("forward", "backward")) +@pytest.mark.parametrize("n_features_to_select", (1, 5, 9, "auto")) +def test_n_features_to_select(direction, n_features_to_select): + # Make sure n_features_to_select is respected + + n_features = 10 + X, y = make_regression(n_features=n_features, random_state=0) + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select=n_features_to_select, + direction=direction, + cv=2, + ) + sfs.fit(X, y) + + if n_features_to_select == "auto": + n_features_to_select = n_features // 2 + + assert sfs.get_support(indices=True).shape[0] == n_features_to_select + assert sfs.n_features_to_select_ == n_features_to_select + assert sfs.transform(X).shape[1] == n_features_to_select + + +@pytest.mark.parametrize("direction", ("forward", "backward")) +def test_n_features_to_select_auto(direction): + """Check the behaviour of `n_features_to_select="auto"` with different + values for the parameter `tol`. + """ + + n_features = 10 + tol = 1e-3 + X, y = make_regression(n_features=n_features, random_state=0) + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select="auto", + tol=tol, + direction=direction, + cv=2, + ) + sfs.fit(X, y) + + max_features_to_select = n_features - 1 + + assert sfs.get_support(indices=True).shape[0] <= max_features_to_select + assert sfs.n_features_to_select_ <= max_features_to_select + assert sfs.transform(X).shape[1] <= max_features_to_select + assert sfs.get_support(indices=True).shape[0] == sfs.n_features_to_select_ + + +@pytest.mark.parametrize("direction", ("forward", "backward")) +def test_n_features_to_select_stopping_criterion(direction): + """Check the behaviour stopping criterion for feature selection + depending on the values of `n_features_to_select` and `tol`. + + When `direction` is `'forward'`, select a new features at random + among those not currently selected in selector.support_, + build a new version of the data that includes all the features + in selector.support_ + this newly selected feature. + And check that the cross-validation score of the model trained on + this new dataset variant is lower than the model with + the selected forward selected features or at least does not improve + by more than the tol margin. + + When `direction` is `'backward'`, instead of adding a new feature + to selector.support_, try to remove one of those selected features at random + And check that the cross-validation score is either decreasing or + not improving by more than the tol margin. + """ + + X, y = make_regression(n_features=50, n_informative=10, random_state=0) + + tol = 1e-3 + + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select="auto", + tol=tol, + direction=direction, + cv=2, + ) + sfs.fit(X, y) + selected_X = sfs.transform(X) + + rng = np.random.RandomState(0) + + added_candidates = list(set(range(X.shape[1])) - set(sfs.get_support(indices=True))) + added_X = np.hstack( + [ + selected_X, + (X[:, rng.choice(added_candidates)])[:, np.newaxis], + ] + ) + + removed_candidate = rng.choice(list(range(sfs.n_features_to_select_))) + removed_X = np.delete(selected_X, removed_candidate, axis=1) + + plain_cv_score = cross_val_score(LinearRegression(), X, y, cv=2).mean() + sfs_cv_score = cross_val_score(LinearRegression(), selected_X, y, cv=2).mean() + added_cv_score = cross_val_score(LinearRegression(), added_X, y, cv=2).mean() + removed_cv_score = cross_val_score(LinearRegression(), removed_X, y, cv=2).mean() + + assert sfs_cv_score >= plain_cv_score + + if direction == "forward": + assert (sfs_cv_score - added_cv_score) <= tol + assert (sfs_cv_score - removed_cv_score) >= tol + else: + assert (added_cv_score - sfs_cv_score) <= tol + assert (removed_cv_score - sfs_cv_score) <= tol + + +@pytest.mark.parametrize("direction", ("forward", "backward")) +@pytest.mark.parametrize( + "n_features_to_select, expected", + ( + (0.1, 1), + (1.0, 10), + (0.5, 5), + ), +) +def test_n_features_to_select_float(direction, n_features_to_select, expected): + # Test passing a float as n_features_to_select + X, y = make_regression(n_features=10) + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select=n_features_to_select, + direction=direction, + cv=2, + ) + sfs.fit(X, y) + assert sfs.n_features_to_select_ == expected + + +@pytest.mark.parametrize("seed", range(10)) +@pytest.mark.parametrize("direction", ("forward", "backward")) +@pytest.mark.parametrize( + "n_features_to_select, expected_selected_features", + [ + (2, [0, 2]), # f1 is dropped since it has no predictive power + (1, [2]), # f2 is more predictive than f0 so it's kept + ], +) +def test_sanity(seed, direction, n_features_to_select, expected_selected_features): + # Basic sanity check: 3 features, only f0 and f2 are correlated with the + # target, f2 having a stronger correlation than f0. We expect f1 to be + # dropped, and f2 to always be selected. + + rng = np.random.RandomState(seed) + n_samples = 100 + X = rng.randn(n_samples, 3) + y = 3 * X[:, 0] - 10 * X[:, 2] + + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select=n_features_to_select, + direction=direction, + cv=2, + ) + sfs.fit(X, y) + assert_array_equal(sfs.get_support(indices=True), expected_selected_features) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_support(csr_container): + # Make sure sparse data is supported + + X, y = make_regression(n_features=10) + X = csr_container(X) + sfs = SequentialFeatureSelector( + LinearRegression(), n_features_to_select="auto", cv=2 + ) + sfs.fit(X, y) + sfs.transform(X) + + +def test_nan_support(): + # Make sure nans are OK if the underlying estimator supports nans + + rng = np.random.RandomState(0) + n_samples, n_features = 40, 4 + X, y = make_regression(n_samples, n_features, random_state=0) + nan_mask = rng.randint(0, 2, size=(n_samples, n_features), dtype=bool) + X[nan_mask] = np.nan + sfs = SequentialFeatureSelector( + HistGradientBoostingRegressor(), n_features_to_select="auto", cv=2 + ) + sfs.fit(X, y) + sfs.transform(X) + + with pytest.raises(ValueError, match="Input X contains NaN"): + # LinearRegression does not support nans + SequentialFeatureSelector( + LinearRegression(), n_features_to_select="auto", cv=2 + ).fit(X, y) + + +def test_pipeline_support(): + # Make sure that pipelines can be passed into SFS and that SFS can be + # passed into a pipeline + + n_samples, n_features = 50, 3 + X, y = make_regression(n_samples, n_features, random_state=0) + + # pipeline in SFS + pipe = make_pipeline(StandardScaler(), LinearRegression()) + sfs = SequentialFeatureSelector(pipe, n_features_to_select="auto", cv=2) + sfs.fit(X, y) + sfs.transform(X) + + # SFS in pipeline + sfs = SequentialFeatureSelector( + LinearRegression(), n_features_to_select="auto", cv=2 + ) + pipe = make_pipeline(StandardScaler(), sfs) + pipe.fit(X, y) + pipe.transform(X) + + +@pytest.mark.parametrize("n_features_to_select", (2, 3)) +def test_unsupervised_model_fit(n_features_to_select): + # Make sure that models without classification labels are not being + # validated + + X, y = make_blobs(n_features=4) + sfs = SequentialFeatureSelector( + KMeans(n_init=1), + n_features_to_select=n_features_to_select, + ) + sfs.fit(X) + assert sfs.transform(X).shape[1] == n_features_to_select + + +@pytest.mark.parametrize("y", ("no_validation", 1j, 99.9, np.nan, 3)) +def test_no_y_validation_model_fit(y): + # Make sure that other non-conventional y labels are not accepted + + X, clusters = make_blobs(n_features=6) + sfs = SequentialFeatureSelector( + KMeans(), + n_features_to_select=3, + ) + + with pytest.raises((TypeError, ValueError)): + sfs.fit(X, y) + + +def test_forward_neg_tol_error(): + """Check that we raise an error when tol<0 and direction='forward'""" + X, y = make_regression(n_features=10, random_state=0) + sfs = SequentialFeatureSelector( + LinearRegression(), + n_features_to_select="auto", + direction="forward", + tol=-1e-3, + ) + + with pytest.raises(ValueError, match="tol must be strictly positive"): + sfs.fit(X, y) + + +def test_backward_neg_tol(): + """Check that SequentialFeatureSelector works negative tol + + non-regression test for #25525 + """ + X, y = make_regression(n_features=10, random_state=0) + lr = LinearRegression() + initial_score = lr.fit(X, y).score(X, y) + + sfs = SequentialFeatureSelector( + lr, + n_features_to_select="auto", + direction="backward", + tol=-1e-3, + ) + Xr = sfs.fit_transform(X, y) + new_score = lr.fit(Xr, y).score(Xr, y) + + assert 0 < sfs.get_support().sum() < X.shape[1] + assert new_score < initial_score + + +def test_cv_generator_support(): + """Check that no exception raised when cv is generator + + non-regression test for #25957 + """ + X, y = make_classification(random_state=0) + + groups = np.zeros_like(y, dtype=int) + groups[y.size // 2 :] = 1 + + cv = LeaveOneGroupOut() + splits = cv.split(X, y, groups=groups) + + knc = KNeighborsClassifier(n_neighbors=5) + + sfs = SequentialFeatureSelector(knc, n_features_to_select=5, cv=splits) + sfs.fit(X, y) + + +def test_fit_rejects_params_with_no_routing_enabled(): + X, y = make_classification(random_state=42) + est = LinearRegression() + sfs = SequentialFeatureSelector(estimator=est) + + with pytest.raises(ValueError, match="is only supported if"): + sfs.fit(X, y, sample_weight=np.ones_like(y)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..45e66cb338a4b7a5a410db669a13f6f9213451dc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/feature_selection/tests/test_variance_threshold.py @@ -0,0 +1,72 @@ +import numpy as np +import pytest + +from sklearn.feature_selection import VarianceThreshold +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import BSR_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS + +data = [[0, 1, 2, 3, 4], [0, 2, 2, 3, 5], [1, 1, 2, 4, 0]] + +data2 = [[-0.13725701]] * 10 + + +@pytest.mark.parametrize( + "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_zero_variance(sparse_container): + # Test VarianceThreshold with default setting, zero variance. + X = data if sparse_container is None else sparse_container(data) + sel = VarianceThreshold().fit(X) + assert_array_equal([0, 1, 3, 4], sel.get_support(indices=True)) + + +def test_zero_variance_value_error(): + # Test VarianceThreshold with default setting, zero variance, error cases. + with pytest.raises(ValueError): + VarianceThreshold().fit([[0, 1, 2, 3]]) + with pytest.raises(ValueError): + VarianceThreshold().fit([[0, 1], [0, 1]]) + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_variance_threshold(sparse_container): + # Test VarianceThreshold with custom variance. + X = data if sparse_container is None else sparse_container(data) + X = VarianceThreshold(threshold=0.4).fit_transform(X) + assert (len(data), 1) == X.shape + + +@pytest.mark.skipif( + np.var(data2) == 0, + reason=( + "This test is not valid for this platform, " + "as it relies on numerical instabilities." + ), +) +@pytest.mark.parametrize( + "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_zero_variance_floating_point_error(sparse_container): + # Test that VarianceThreshold(0.0).fit eliminates features that have + # the same value in every sample, even when floating point errors + # cause np.var not to be 0 for the feature. + # See #13691 + X = data2 if sparse_container is None else sparse_container(data2) + msg = "No feature in X meets the variance threshold 0.00000" + with pytest.raises(ValueError, match=msg): + VarianceThreshold().fit(X) + + +@pytest.mark.parametrize( + "sparse_container", [None] + BSR_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_variance_nan(sparse_container): + arr = np.array(data, dtype=np.float64) + # add single NaN and feature should still be included + arr[0, 0] = np.nan + # make all values in feature NaN and feature should be rejected + arr[:, 1] = np.nan + + X = arr if sparse_container is None else sparse_container(arr) + sel = VarianceThreshold().fit(X) + assert_array_equal([0, 3, 4], sel.get_support(indices=True)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ca540b79229c87447f40eed6717fe59202885f0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/__init__.py @@ -0,0 +1,6 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._frozen import FrozenEstimator + +__all__ = ["FrozenEstimator"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/_frozen.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..7585ea2597b5995a5e7ffcaf8f7f9b78fd676e6e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/_frozen.py @@ -0,0 +1,166 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from copy import deepcopy + +from ..base import BaseEstimator +from ..exceptions import NotFittedError +from ..utils import get_tags +from ..utils.metaestimators import available_if +from ..utils.validation import check_is_fitted + + +def _estimator_has(attr): + """Check that final_estimator has `attr`. + + Used together with `available_if`. + """ + + def check(self): + # raise original `AttributeError` if `attr` does not exist + getattr(self.estimator, attr) + return True + + return check + + +class FrozenEstimator(BaseEstimator): + """Estimator that wraps a fitted estimator to prevent re-fitting. + + This meta-estimator takes an estimator and freezes it, in the sense that calling + `fit` on it has no effect. `fit_predict` and `fit_transform` are also disabled. + All other methods are delegated to the original estimator and original estimator's + attributes are accessible as well. + + This is particularly useful when you have a fitted or a pre-trained model as a + transformer in a pipeline, and you'd like `pipeline.fit` to have no effect on this + step. + + Parameters + ---------- + estimator : estimator + The estimator which is to be kept frozen. + + See Also + -------- + None: No similar entry in the scikit-learn documentation. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.frozen import FrozenEstimator + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(random_state=0) + >>> clf = LogisticRegression(random_state=0).fit(X, y) + >>> frozen_clf = FrozenEstimator(clf) + >>> frozen_clf.fit(X, y) # No-op + FrozenEstimator(estimator=LogisticRegression(random_state=0)) + >>> frozen_clf.predict(X) # Predictions from `clf.predict` + array(...) + """ + + def __init__(self, estimator): + self.estimator = estimator + + @available_if(_estimator_has("__getitem__")) + def __getitem__(self, *args, **kwargs): + """__getitem__ is defined in :class:`~sklearn.pipeline.Pipeline` and \ + :class:`~sklearn.compose.ColumnTransformer`. + """ + return self.estimator.__getitem__(*args, **kwargs) + + def __getattr__(self, name): + # `estimator`'s attributes are now accessible except `fit_predict` and + # `fit_transform` + if name in ["fit_predict", "fit_transform"]: + raise AttributeError(f"{name} is not available for frozen estimators.") + return getattr(self.estimator, name) + + def __sklearn_clone__(self): + return self + + def __sklearn_is_fitted__(self): + try: + check_is_fitted(self.estimator) + return True + except NotFittedError: + return False + + def fit(self, X, y, *args, **kwargs): + """No-op. + + As a frozen estimator, calling `fit` has no effect. + + Parameters + ---------- + X : object + Ignored. + + y : object + Ignored. + + *args : tuple + Additional positional arguments. Ignored, but present for API compatibility + with `self.estimator`. + + **kwargs : dict + Additional keyword arguments. Ignored, but present for API compatibility + with `self.estimator`. + + Returns + ------- + self : object + Returns the instance itself. + """ + check_is_fitted(self.estimator) + return self + + def set_params(self, **kwargs): + """Set the parameters of this estimator. + + The only valid key here is `estimator`. You cannot set the parameters of the + inner estimator. + + Parameters + ---------- + **kwargs : dict + Estimator parameters. + + Returns + ------- + self : FrozenEstimator + This estimator. + """ + estimator = kwargs.pop("estimator", None) + if estimator is not None: + self.estimator = estimator + if kwargs: + raise ValueError( + "You cannot set parameters of the inner estimator in a frozen " + "estimator since calling `fit` has no effect. You can use " + "`frozenestimator.estimator.set_params` to set parameters of the inner " + "estimator." + ) + + def get_params(self, deep=True): + """Get parameters for this estimator. + + Returns a `{"estimator": estimator}` dict. The parameters of the inner + estimator are not included. + + Parameters + ---------- + deep : bool, default=True + Ignored. + + Returns + ------- + params : dict + Parameter names mapped to their values. + """ + return {"estimator": self.estimator} + + def __sklearn_tags__(self): + tags = deepcopy(get_tags(self.estimator)) + tags._skip_test = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/tests/test_frozen.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/tests/test_frozen.py new file mode 100644 index 0000000000000000000000000000000000000000..b304d3ac0aa2c32d6b494351ef0c0d0209866b71 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/frozen/tests/test_frozen.py @@ -0,0 +1,223 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import re + +import numpy as np +import pytest +from numpy.testing import assert_array_equal + +from sklearn import config_context +from sklearn.base import ( + BaseEstimator, + clone, + is_classifier, + is_clusterer, + is_outlier_detector, + is_regressor, +) +from sklearn.cluster import KMeans +from sklearn.compose import make_column_transformer +from sklearn.datasets import make_classification, make_regression +from sklearn.exceptions import NotFittedError, UnsetMetadataPassedError +from sklearn.frozen import FrozenEstimator +from sklearn.linear_model import LinearRegression, LogisticRegression +from sklearn.neighbors import LocalOutlierFactor +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import RobustScaler, StandardScaler +from sklearn.utils._testing import set_random_state +from sklearn.utils.validation import check_is_fitted + + +@pytest.fixture +def regression_dataset(): + return make_regression() + + +@pytest.fixture +def classification_dataset(): + return make_classification() + + +@pytest.mark.parametrize( + "estimator, dataset", + [ + (LinearRegression(), "regression_dataset"), + (LogisticRegression(), "classification_dataset"), + (make_pipeline(StandardScaler(), LinearRegression()), "regression_dataset"), + ( + make_pipeline(StandardScaler(), LogisticRegression()), + "classification_dataset", + ), + (StandardScaler(), "regression_dataset"), + (KMeans(), "regression_dataset"), + (LocalOutlierFactor(), "regression_dataset"), + ( + make_column_transformer( + (StandardScaler(), [0]), + (RobustScaler(), [1]), + ), + "regression_dataset", + ), + ], +) +@pytest.mark.parametrize( + "method", + ["predict", "predict_proba", "predict_log_proba", "decision_function", "transform"], +) +def test_frozen_methods(estimator, dataset, request, method): + """Test that frozen.fit doesn't do anything, and that all other methods are + exposed by the frozen estimator and return the same values as the estimator. + """ + X, y = request.getfixturevalue(dataset) + set_random_state(estimator) + estimator.fit(X, y) + frozen = FrozenEstimator(estimator) + # this should be no-op + frozen.fit([[1]], [1]) + + if hasattr(estimator, method): + assert_array_equal(getattr(estimator, method)(X), getattr(frozen, method)(X)) + + assert is_classifier(estimator) == is_classifier(frozen) + assert is_regressor(estimator) == is_regressor(frozen) + assert is_clusterer(estimator) == is_clusterer(frozen) + assert is_outlier_detector(estimator) == is_outlier_detector(frozen) + + +@config_context(enable_metadata_routing=True) +def test_frozen_metadata_routing(regression_dataset): + """Test that metadata routing works with frozen estimators.""" + + class ConsumesMetadata(BaseEstimator): + def __init__(self, on_fit=None, on_predict=None): + self.on_fit = on_fit + self.on_predict = on_predict + + def fit(self, X, y, metadata=None): + if self.on_fit: + assert metadata is not None + self.fitted_ = True + return self + + def predict(self, X, metadata=None): + if self.on_predict: + assert metadata is not None + return np.ones(len(X)) + + X, y = regression_dataset + pipeline = make_pipeline( + ConsumesMetadata(on_fit=True, on_predict=True) + .set_fit_request(metadata=True) + .set_predict_request(metadata=True) + ) + + pipeline.fit(X, y, metadata="test") + frozen = FrozenEstimator(pipeline) + pipeline.predict(X, metadata="test") + frozen.predict(X, metadata="test") + + frozen["consumesmetadata"].set_predict_request(metadata=False) + with pytest.raises( + TypeError, + match=re.escape( + "Pipeline.predict got unexpected argument(s) {'metadata'}, which are not " + "routed to any object." + ), + ): + frozen.predict(X, metadata="test") + + frozen["consumesmetadata"].set_predict_request(metadata=None) + with pytest.raises(UnsetMetadataPassedError): + frozen.predict(X, metadata="test") + + +def test_composite_fit(classification_dataset): + """Test that calling fit_transform and fit_predict doesn't call fit.""" + + class Estimator(BaseEstimator): + def fit(self, X, y): + try: + self._fit_counter += 1 + except AttributeError: + self._fit_counter = 1 + return self + + def fit_transform(self, X, y=None): + # only here to test that it doesn't get called + ... # pragma: no cover + + def fit_predict(self, X, y=None): + # only here to test that it doesn't get called + ... # pragma: no cover + + X, y = classification_dataset + est = Estimator().fit(X, y) + frozen = FrozenEstimator(est) + + with pytest.raises(AttributeError): + frozen.fit_predict(X, y) + with pytest.raises(AttributeError): + frozen.fit_transform(X, y) + + assert frozen._fit_counter == 1 + + +def test_clone_frozen(regression_dataset): + """Test that cloning a frozen estimator keeps the frozen state.""" + X, y = regression_dataset + estimator = LinearRegression().fit(X, y) + frozen = FrozenEstimator(estimator) + cloned = clone(frozen) + assert cloned.estimator is estimator + + +def test_check_is_fitted(regression_dataset): + """Test that check_is_fitted works on frozen estimators.""" + X, y = regression_dataset + + estimator = LinearRegression() + frozen = FrozenEstimator(estimator) + with pytest.raises(NotFittedError): + check_is_fitted(frozen) + + estimator = LinearRegression().fit(X, y) + frozen = FrozenEstimator(estimator) + check_is_fitted(frozen) + + +def test_frozen_tags(): + """Test that frozen estimators have the same tags as the original estimator + except for the skip_test tag.""" + + class Estimator(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.categorical = True + return tags + + estimator = Estimator() + frozen = FrozenEstimator(estimator) + frozen_tags = frozen.__sklearn_tags__() + estimator_tags = estimator.__sklearn_tags__() + + assert frozen_tags._skip_test is True + assert estimator_tags._skip_test is False + + assert estimator_tags.input_tags.categorical is True + assert frozen_tags.input_tags.categorical is True + + +def test_frozen_params(): + """Test that FrozenEstimator only exposes the estimator parameter.""" + est = LogisticRegression() + frozen = FrozenEstimator(est) + + with pytest.raises(ValueError, match="You cannot set parameters of the inner"): + frozen.set_params(estimator__C=1) + + assert frozen.get_params() == {"estimator": est} + + other_est = LocalOutlierFactor() + frozen.set_params(estimator=other_est) + assert frozen.get_params() == {"estimator": other_est} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9fafaf67e4ed042a95058e294f2395ea0dffb55d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/__init__.py @@ -0,0 +1,10 @@ +"""Gaussian process based regression and classification.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from . import kernels +from ._gpc import GaussianProcessClassifier +from ._gpr import GaussianProcessRegressor + +__all__ = ["GaussianProcessClassifier", "GaussianProcessRegressor", "kernels"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpc.py new file mode 100644 index 0000000000000000000000000000000000000000..0ecceb47de9058643daee84faaab1e9927919c26 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpc.py @@ -0,0 +1,973 @@ +"""Gaussian processes classification.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral +from operator import itemgetter + +import numpy as np +import scipy.optimize +from scipy.linalg import cho_solve, cholesky, solve +from scipy.special import erf, expit + +from ..base import BaseEstimator, ClassifierMixin, _fit_context, clone +from ..multiclass import OneVsOneClassifier, OneVsRestClassifier +from ..preprocessing import LabelEncoder +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.optimize import _check_optimize_result +from ..utils.validation import check_is_fitted, validate_data +from .kernels import RBF, CompoundKernel, Kernel +from .kernels import ConstantKernel as C + +# Values required for approximating the logistic sigmoid by +# error functions. coefs are obtained via: +# x = np.array([0, 0.6, 2, 3.5, 4.5, np.inf]) +# b = logistic(x) +# A = (erf(np.dot(x, self.lambdas)) + 1) / 2 +# coefs = lstsq(A, b)[0] +LAMBDAS = np.array([0.41, 0.4, 0.37, 0.44, 0.39])[:, np.newaxis] +COEFS = np.array( + [-1854.8214151, 3516.89893646, 221.29346712, 128.12323805, -2010.49422654] +)[:, np.newaxis] + + +class _BinaryGaussianProcessClassifierLaplace(BaseEstimator): + """Binary Gaussian process classification based on Laplace approximation. + + The implementation is based on Algorithm 3.1, 3.2, and 5.1 from [RW2006]_. + + Internally, the Laplace approximation is used for approximating the + non-Gaussian posterior by a Gaussian. + + Currently, the implementation is restricted to using the logistic link + function. + + .. versionadded:: 0.18 + + Parameters + ---------- + kernel : kernel instance, default=None + The kernel specifying the covariance function of the GP. If None is + passed, the kernel "1.0 * RBF(1.0)" is used as default. Note that + the kernel's hyperparameters are optimized during fitting. + + optimizer : 'fmin_l_bfgs_b' or callable, default='fmin_l_bfgs_b' + Can either be one of the internally supported optimizers for optimizing + the kernel's parameters, specified by a string, or an externally + defined optimizer passed as a callable. If a callable is passed, it + must have the signature:: + + def optimizer(obj_func, initial_theta, bounds): + # * 'obj_func' is the objective function to be maximized, which + # takes the hyperparameters theta as parameter and an + # optional flag eval_gradient, which determines if the + # gradient is returned additionally to the function value + # * 'initial_theta': the initial value for theta, which can be + # used by local optimizers + # * 'bounds': the bounds on the values of theta + .... + # Returned are the best found hyperparameters theta and + # the corresponding value of the target function. + return theta_opt, func_min + + Per default, the 'L-BFGS-B' algorithm from scipy.optimize.minimize + is used. If None is passed, the kernel's parameters are kept fixed. + Available internal optimizers are:: + + 'fmin_l_bfgs_b' + + n_restarts_optimizer : int, default=0 + The number of restarts of the optimizer for finding the kernel's + parameters which maximize the log-marginal likelihood. The first run + of the optimizer is performed from the kernel's initial parameters, + the remaining ones (if any) from thetas sampled log-uniform randomly + from the space of allowed theta-values. If greater than 0, all bounds + must be finite. Note that n_restarts_optimizer=0 implies that one + run is performed. + + max_iter_predict : int, default=100 + The maximum number of iterations in Newton's method for approximating + the posterior during predict. Smaller values will reduce computation + time at the cost of worse results. + + warm_start : bool, default=False + If warm-starts are enabled, the solution of the last Newton iteration + on the Laplace approximation of the posterior mode is used as + initialization for the next call of _posterior_mode(). This can speed + up convergence when _posterior_mode is called several times on similar + problems as in hyperparameter optimization. See :term:`the Glossary + `. + + copy_X_train : bool, default=True + If True, a persistent copy of the training data is stored in the + object. Otherwise, just a reference to the training data is stored, + which might cause predictions to change if the data is modified + externally. + + random_state : int, RandomState instance or None, default=None + Determines random number generation used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + X_train_ : array-like of shape (n_samples, n_features) or list of object + Feature vectors or other representations of training data (also + required for prediction). + + y_train_ : array-like of shape (n_samples,) + Target values in training data (also required for prediction) + + classes_ : array-like of shape (n_classes,) + Unique class labels. + + kernel_ : kernl instance + The kernel used for prediction. The structure of the kernel is the + same as the one passed as parameter but with optimized hyperparameters + + L_ : array-like of shape (n_samples, n_samples) + Lower-triangular Cholesky decomposition of the kernel in X_train_ + + pi_ : array-like of shape (n_samples,) + The probabilities of the positive class for the training points + X_train_ + + W_sr_ : array-like of shape (n_samples,) + Square root of W, the Hessian of log-likelihood of the latent function + values for the observed labels. Since W is diagonal, only the diagonal + of sqrt(W) is stored. + + log_marginal_likelihood_value_ : float + The log-marginal-likelihood of ``self.kernel_.theta`` + + References + ---------- + .. [RW2006] `Carl E. Rasmussen and Christopher K.I. Williams, + "Gaussian Processes for Machine Learning", + MIT Press 2006 `_ + """ + + def __init__( + self, + kernel=None, + *, + optimizer="fmin_l_bfgs_b", + n_restarts_optimizer=0, + max_iter_predict=100, + warm_start=False, + copy_X_train=True, + random_state=None, + ): + self.kernel = kernel + self.optimizer = optimizer + self.n_restarts_optimizer = n_restarts_optimizer + self.max_iter_predict = max_iter_predict + self.warm_start = warm_start + self.copy_X_train = copy_X_train + self.random_state = random_state + + def fit(self, X, y): + """Fit Gaussian process classification model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Feature vectors or other representations of training data. + + y : array-like of shape (n_samples,) + Target values, must be binary. + + Returns + ------- + self : returns an instance of self. + """ + if self.kernel is None: # Use an RBF kernel as default + self.kernel_ = C(1.0, constant_value_bounds="fixed") * RBF( + 1.0, length_scale_bounds="fixed" + ) + else: + self.kernel_ = clone(self.kernel) + + self.rng = check_random_state(self.random_state) + + self.X_train_ = np.copy(X) if self.copy_X_train else X + + # Encode class labels and check that it is a binary classification + # problem + label_encoder = LabelEncoder() + self.y_train_ = label_encoder.fit_transform(y) + self.classes_ = label_encoder.classes_ + if self.classes_.size > 2: + raise ValueError( + "%s supports only binary classification. y contains classes %s" + % (self.__class__.__name__, self.classes_) + ) + elif self.classes_.size == 1: + raise ValueError( + "{0:s} requires 2 classes; got {1:d} class".format( + self.__class__.__name__, self.classes_.size + ) + ) + + if self.optimizer is not None and self.kernel_.n_dims > 0: + # Choose hyperparameters based on maximizing the log-marginal + # likelihood (potentially starting from several initial values) + def obj_func(theta, eval_gradient=True): + if eval_gradient: + lml, grad = self.log_marginal_likelihood( + theta, eval_gradient=True, clone_kernel=False + ) + return -lml, -grad + else: + return -self.log_marginal_likelihood(theta, clone_kernel=False) + + # First optimize starting from theta specified in kernel + optima = [ + self._constrained_optimization( + obj_func, self.kernel_.theta, self.kernel_.bounds + ) + ] + + # Additional runs are performed from log-uniform chosen initial + # theta + if self.n_restarts_optimizer > 0: + if not np.isfinite(self.kernel_.bounds).all(): + raise ValueError( + "Multiple optimizer restarts (n_restarts_optimizer>0) " + "requires that all bounds are finite." + ) + bounds = self.kernel_.bounds + for iteration in range(self.n_restarts_optimizer): + theta_initial = np.exp(self.rng.uniform(bounds[:, 0], bounds[:, 1])) + optima.append( + self._constrained_optimization(obj_func, theta_initial, bounds) + ) + # Select result from run with minimal (negative) log-marginal + # likelihood + lml_values = list(map(itemgetter(1), optima)) + self.kernel_.theta = optima[np.argmin(lml_values)][0] + self.kernel_._check_bounds_params() + + self.log_marginal_likelihood_value_ = -np.min(lml_values) + else: + self.log_marginal_likelihood_value_ = self.log_marginal_likelihood( + self.kernel_.theta + ) + + # Precompute quantities required for predictions which are independent + # of actual query points + K = self.kernel_(self.X_train_) + + _, (self.pi_, self.W_sr_, self.L_, _, _) = self._posterior_mode( + K, return_temporaries=True + ) + + return self + + def predict(self, X): + """Perform classification on an array of test vectors X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + C : ndarray of shape (n_samples,) + Predicted target values for X, values are from ``classes_`` + """ + check_is_fitted(self) + + # As discussed on Section 3.4.2 of GPML, for making hard binary + # decisions, it is enough to compute the MAP of the posterior and + # pass it through the link function + K_star = self.kernel_(self.X_train_, X) # K_star =k(x_star) + f_star = K_star.T.dot(self.y_train_ - self.pi_) # Algorithm 3.2,Line 4 + + return np.where(f_star > 0, self.classes_[1], self.classes_[0]) + + def predict_proba(self, X): + """Return probability estimates for the test vector X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + C : array-like of shape (n_samples, n_classes) + Returns the probability of the samples for each class in + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute ``classes_``. + """ + check_is_fitted(self) + + # Compute the mean and variance of the latent function + # (Lines 4-6 of Algorithm 3.2 of GPML) + latent_mean, latent_var = self.latent_mean_and_variance(X) + + # Line 7: + # Approximate \int log(z) * N(z | f_star, var_f_star) + # Approximation is due to Williams & Barber, "Bayesian Classification + # with Gaussian Processes", Appendix A: Approximate the logistic + # sigmoid by a linear combination of 5 error functions. + # For information on how this integral can be computed see + # blitiri.blogspot.de/2012/11/gaussian-integral-of-error-function.html + alpha = 1 / (2 * latent_var) + gamma = LAMBDAS * latent_mean + integrals = ( + np.sqrt(np.pi / alpha) + * erf(gamma * np.sqrt(alpha / (alpha + LAMBDAS**2))) + / (2 * np.sqrt(latent_var * 2 * np.pi)) + ) + pi_star = (COEFS * integrals).sum(axis=0) + 0.5 * COEFS.sum() + + return np.vstack((1 - pi_star, pi_star)).T + + def log_marginal_likelihood( + self, theta=None, eval_gradient=False, clone_kernel=True + ): + """Returns log-marginal likelihood of theta for training data. + + Parameters + ---------- + theta : array-like of shape (n_kernel_params,), default=None + Kernel hyperparameters for which the log-marginal likelihood is + evaluated. If None, the precomputed log_marginal_likelihood + of ``self.kernel_.theta`` is returned. + + eval_gradient : bool, default=False + If True, the gradient of the log-marginal likelihood with respect + to the kernel hyperparameters at position theta is returned + additionally. If True, theta must not be None. + + clone_kernel : bool, default=True + If True, the kernel attribute is copied. If False, the kernel + attribute is modified, but may result in a performance improvement. + + Returns + ------- + log_likelihood : float + Log-marginal likelihood of theta for training data. + + log_likelihood_gradient : ndarray of shape (n_kernel_params,), \ + optional + Gradient of the log-marginal likelihood with respect to the kernel + hyperparameters at position theta. + Only returned when `eval_gradient` is True. + """ + if theta is None: + if eval_gradient: + raise ValueError("Gradient can only be evaluated for theta!=None") + return self.log_marginal_likelihood_value_ + + if clone_kernel: + kernel = self.kernel_.clone_with_theta(theta) + else: + kernel = self.kernel_ + kernel.theta = theta + + if eval_gradient: + K, K_gradient = kernel(self.X_train_, eval_gradient=True) + else: + K = kernel(self.X_train_) + + # Compute log-marginal-likelihood Z and also store some temporaries + # which can be reused for computing Z's gradient + Z, (pi, W_sr, L, b, a) = self._posterior_mode(K, return_temporaries=True) + + if not eval_gradient: + return Z + + # Compute gradient based on Algorithm 5.1 of GPML + d_Z = np.empty(theta.shape[0]) + # XXX: Get rid of the np.diag() in the next line + R = W_sr[:, np.newaxis] * cho_solve((L, True), np.diag(W_sr)) # Line 7 + C = solve(L, W_sr[:, np.newaxis] * K) # Line 8 + # Line 9: (use einsum to compute np.diag(C.T.dot(C)))) + s_2 = ( + -0.5 + * (np.diag(K) - np.einsum("ij, ij -> j", C, C)) + * (pi * (1 - pi) * (1 - 2 * pi)) + ) # third derivative + + for j in range(d_Z.shape[0]): + C = K_gradient[:, :, j] # Line 11 + # Line 12: (R.T.ravel().dot(C.ravel()) = np.trace(R.dot(C))) + s_1 = 0.5 * a.T.dot(C).dot(a) - 0.5 * R.T.ravel().dot(C.ravel()) + + b = C.dot(self.y_train_ - pi) # Line 13 + s_3 = b - K.dot(R.dot(b)) # Line 14 + + d_Z[j] = s_1 + s_2.T.dot(s_3) # Line 15 + + return Z, d_Z + + def latent_mean_and_variance(self, X): + """Compute the mean and variance of the latent function values. + + Based on algorithm 3.2 of [RW2006]_, this function returns the latent + mean (Line 4) and variance (Line 6) of the Gaussian process + classification model. + + Note that this function is only supported for binary classification. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + latent_mean : array-like of shape (n_samples,) + Mean of the latent function values at the query points. + + latent_var : array-like of shape (n_samples,) + Variance of the latent function values at the query points. + """ + check_is_fitted(self) + + # Based on Algorithm 3.2 of GPML + K_star = self.kernel_(self.X_train_, X) # K_star =k(x_star) + latent_mean = K_star.T.dot(self.y_train_ - self.pi_) # Line 4 + v = solve(self.L_, self.W_sr_[:, np.newaxis] * K_star) # Line 5 + # Line 6 (compute np.diag(v.T.dot(v)) via einsum) + latent_var = self.kernel_.diag(X) - np.einsum("ij,ij->j", v, v) + + return latent_mean, latent_var + + def _posterior_mode(self, K, return_temporaries=False): + """Mode-finding for binary Laplace GPC and fixed kernel. + + This approximates the posterior of the latent function values for given + inputs and target observations with a Gaussian approximation and uses + Newton's iteration to find the mode of this approximation. + """ + # Based on Algorithm 3.1 of GPML + + # If warm_start are enabled, we reuse the last solution for the + # posterior mode as initialization; otherwise, we initialize with 0 + if ( + self.warm_start + and hasattr(self, "f_cached") + and self.f_cached.shape == self.y_train_.shape + ): + f = self.f_cached + else: + f = np.zeros_like(self.y_train_, dtype=np.float64) + + # Use Newton's iteration method to find mode of Laplace approximation + log_marginal_likelihood = -np.inf + for _ in range(self.max_iter_predict): + # Line 4 + pi = expit(f) + W = pi * (1 - pi) + # Line 5 + W_sr = np.sqrt(W) + W_sr_K = W_sr[:, np.newaxis] * K + B = np.eye(W.shape[0]) + W_sr_K * W_sr + L = cholesky(B, lower=True) + # Line 6 + b = W * f + (self.y_train_ - pi) + # Line 7 + a = b - W_sr * cho_solve((L, True), W_sr_K.dot(b)) + # Line 8 + f = K.dot(a) + + # Line 10: Compute log marginal likelihood in loop and use as + # convergence criterion + lml = ( + -0.5 * a.T.dot(f) + - np.log1p(np.exp(-(self.y_train_ * 2 - 1) * f)).sum() + - np.log(np.diag(L)).sum() + ) + # Check if we have converged (log marginal likelihood does + # not decrease) + # XXX: more complex convergence criterion + if lml - log_marginal_likelihood < 1e-10: + break + log_marginal_likelihood = lml + + self.f_cached = f # Remember solution for later warm-starts + if return_temporaries: + return log_marginal_likelihood, (pi, W_sr, L, b, a) + else: + return log_marginal_likelihood + + def _constrained_optimization(self, obj_func, initial_theta, bounds): + if self.optimizer == "fmin_l_bfgs_b": + opt_res = scipy.optimize.minimize( + obj_func, initial_theta, method="L-BFGS-B", jac=True, bounds=bounds + ) + _check_optimize_result("lbfgs", opt_res) + theta_opt, func_min = opt_res.x, opt_res.fun + elif callable(self.optimizer): + theta_opt, func_min = self.optimizer(obj_func, initial_theta, bounds=bounds) + else: + raise ValueError("Unknown optimizer %s." % self.optimizer) + + return theta_opt, func_min + + +class GaussianProcessClassifier(ClassifierMixin, BaseEstimator): + """Gaussian process classification (GPC) based on Laplace approximation. + + The implementation is based on Algorithm 3.1, 3.2, and 5.1 from [RW2006]_. + + Internally, the Laplace approximation is used for approximating the + non-Gaussian posterior by a Gaussian. + + Currently, the implementation is restricted to using the logistic link + function. For multi-class classification, several binary one-versus rest + classifiers are fitted. Note that this class thus does not implement + a true multi-class Laplace approximation. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + kernel : kernel instance, default=None + The kernel specifying the covariance function of the GP. If None is + passed, the kernel "1.0 * RBF(1.0)" is used as default. Note that + the kernel's hyperparameters are optimized during fitting. Also kernel + cannot be a `CompoundKernel`. + + optimizer : 'fmin_l_bfgs_b', callable or None, default='fmin_l_bfgs_b' + Can either be one of the internally supported optimizers for optimizing + the kernel's parameters, specified by a string, or an externally + defined optimizer passed as a callable. If a callable is passed, it + must have the signature:: + + def optimizer(obj_func, initial_theta, bounds): + # * 'obj_func' is the objective function to be maximized, which + # takes the hyperparameters theta as parameter and an + # optional flag eval_gradient, which determines if the + # gradient is returned additionally to the function value + # * 'initial_theta': the initial value for theta, which can be + # used by local optimizers + # * 'bounds': the bounds on the values of theta + .... + # Returned are the best found hyperparameters theta and + # the corresponding value of the target function. + return theta_opt, func_min + + Per default, the 'L-BFGS-B' algorithm from scipy.optimize.minimize + is used. If None is passed, the kernel's parameters are kept fixed. + Available internal optimizers are:: + + 'fmin_l_bfgs_b' + + n_restarts_optimizer : int, default=0 + The number of restarts of the optimizer for finding the kernel's + parameters which maximize the log-marginal likelihood. The first run + of the optimizer is performed from the kernel's initial parameters, + the remaining ones (if any) from thetas sampled log-uniform randomly + from the space of allowed theta-values. If greater than 0, all bounds + must be finite. Note that n_restarts_optimizer=0 implies that one + run is performed. + + max_iter_predict : int, default=100 + The maximum number of iterations in Newton's method for approximating + the posterior during predict. Smaller values will reduce computation + time at the cost of worse results. + + warm_start : bool, default=False + If warm-starts are enabled, the solution of the last Newton iteration + on the Laplace approximation of the posterior mode is used as + initialization for the next call of _posterior_mode(). This can speed + up convergence when _posterior_mode is called several times on similar + problems as in hyperparameter optimization. See :term:`the Glossary + `. + + copy_X_train : bool, default=True + If True, a persistent copy of the training data is stored in the + object. Otherwise, just a reference to the training data is stored, + which might cause predictions to change if the data is modified + externally. + + random_state : int, RandomState instance or None, default=None + Determines random number generation used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + multi_class : {'one_vs_rest', 'one_vs_one'}, default='one_vs_rest' + Specifies how multi-class classification problems are handled. + Supported are 'one_vs_rest' and 'one_vs_one'. In 'one_vs_rest', + one binary Gaussian process classifier is fitted for each class, which + is trained to separate this class from the rest. In 'one_vs_one', one + binary Gaussian process classifier is fitted for each pair of classes, + which is trained to separate these two classes. The predictions of + these binary predictors are combined into multi-class predictions. + Note that 'one_vs_one' does not support predicting probability + estimates. + + n_jobs : int, default=None + The number of jobs to use for the computation: the specified + multiclass problems are computed in parallel. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + base_estimator_ : ``Estimator`` instance + The estimator instance that defines the likelihood function + using the observed data. + + kernel_ : kernel instance + The kernel used for prediction. In case of binary classification, + the structure of the kernel is the same as the one passed as parameter + but with optimized hyperparameters. In case of multi-class + classification, a CompoundKernel is returned which consists of the + different kernels used in the one-versus-rest classifiers. + + log_marginal_likelihood_value_ : float + The log-marginal-likelihood of ``self.kernel_.theta`` + + classes_ : array-like of shape (n_classes,) + Unique class labels. + + n_classes_ : int + The number of classes in the training data + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + GaussianProcessRegressor : Gaussian process regression (GPR). + + References + ---------- + .. [RW2006] `Carl E. Rasmussen and Christopher K.I. Williams, + "Gaussian Processes for Machine Learning", + MIT Press 2006 `_ + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.gaussian_process import GaussianProcessClassifier + >>> from sklearn.gaussian_process.kernels import RBF + >>> X, y = load_iris(return_X_y=True) + >>> kernel = 1.0 * RBF(1.0) + >>> gpc = GaussianProcessClassifier(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpc.score(X, y) + 0.9866... + >>> gpc.predict_proba(X[:2,:]) + array([[0.83548752, 0.03228706, 0.13222543], + [0.79064206, 0.06525643, 0.14410151]]) + + For a comparison of the GaussianProcessClassifier with other classifiers see: + :ref:`sphx_glr_auto_examples_classification_plot_classification_probability.py`. + """ + + _parameter_constraints: dict = { + "kernel": [Kernel, None], + "optimizer": [StrOptions({"fmin_l_bfgs_b"}), callable, None], + "n_restarts_optimizer": [Interval(Integral, 0, None, closed="left")], + "max_iter_predict": [Interval(Integral, 1, None, closed="left")], + "warm_start": ["boolean"], + "copy_X_train": ["boolean"], + "random_state": ["random_state"], + "multi_class": [StrOptions({"one_vs_rest", "one_vs_one"})], + "n_jobs": [Integral, None], + } + + def __init__( + self, + kernel=None, + *, + optimizer="fmin_l_bfgs_b", + n_restarts_optimizer=0, + max_iter_predict=100, + warm_start=False, + copy_X_train=True, + random_state=None, + multi_class="one_vs_rest", + n_jobs=None, + ): + self.kernel = kernel + self.optimizer = optimizer + self.n_restarts_optimizer = n_restarts_optimizer + self.max_iter_predict = max_iter_predict + self.warm_start = warm_start + self.copy_X_train = copy_X_train + self.random_state = random_state + self.multi_class = multi_class + self.n_jobs = n_jobs + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit Gaussian process classification model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Feature vectors or other representations of training data. + + y : array-like of shape (n_samples,) + Target values, must be binary. + + Returns + ------- + self : object + Returns an instance of self. + """ + if isinstance(self.kernel, CompoundKernel): + raise ValueError("kernel cannot be a CompoundKernel") + + if self.kernel is None or self.kernel.requires_vector_input: + X, y = validate_data( + self, X, y, multi_output=False, ensure_2d=True, dtype="numeric" + ) + else: + X, y = validate_data( + self, X, y, multi_output=False, ensure_2d=False, dtype=None + ) + + self.base_estimator_ = _BinaryGaussianProcessClassifierLaplace( + kernel=self.kernel, + optimizer=self.optimizer, + n_restarts_optimizer=self.n_restarts_optimizer, + max_iter_predict=self.max_iter_predict, + warm_start=self.warm_start, + copy_X_train=self.copy_X_train, + random_state=self.random_state, + ) + + self.classes_ = np.unique(y) + self.n_classes_ = self.classes_.size + if self.n_classes_ == 1: + raise ValueError( + "GaussianProcessClassifier requires 2 or more " + "distinct classes; got %d class (only class %s " + "is present)" % (self.n_classes_, self.classes_[0]) + ) + if self.n_classes_ > 2: + if self.multi_class == "one_vs_rest": + self.base_estimator_ = OneVsRestClassifier( + self.base_estimator_, n_jobs=self.n_jobs + ) + elif self.multi_class == "one_vs_one": + self.base_estimator_ = OneVsOneClassifier( + self.base_estimator_, n_jobs=self.n_jobs + ) + else: + raise ValueError("Unknown multi-class mode %s" % self.multi_class) + + self.base_estimator_.fit(X, y) + + if self.n_classes_ > 2: + self.log_marginal_likelihood_value_ = np.mean( + [ + estimator.log_marginal_likelihood() + for estimator in self.base_estimator_.estimators_ + ] + ) + else: + self.log_marginal_likelihood_value_ = ( + self.base_estimator_.log_marginal_likelihood() + ) + + return self + + def predict(self, X): + """Perform classification on an array of test vectors X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + C : ndarray of shape (n_samples,) + Predicted target values for X, values are from ``classes_``. + """ + check_is_fitted(self) + + if self.kernel is None or self.kernel.requires_vector_input: + X = validate_data(self, X, ensure_2d=True, dtype="numeric", reset=False) + else: + X = validate_data(self, X, ensure_2d=False, dtype=None, reset=False) + + return self.base_estimator_.predict(X) + + def predict_proba(self, X): + """Return probability estimates for the test vector X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + C : array-like of shape (n_samples, n_classes) + Returns the probability of the samples for each class in + the model. The columns correspond to the classes in sorted + order, as they appear in the attribute :term:`classes_`. + """ + check_is_fitted(self) + if self.n_classes_ > 2 and self.multi_class == "one_vs_one": + raise ValueError( + "one_vs_one multi-class mode does not support " + "predicting probability estimates. Use " + "one_vs_rest mode instead." + ) + + if self.kernel is None or self.kernel.requires_vector_input: + X = validate_data(self, X, ensure_2d=True, dtype="numeric", reset=False) + else: + X = validate_data(self, X, ensure_2d=False, dtype=None, reset=False) + + return self.base_estimator_.predict_proba(X) + + @property + def kernel_(self): + """Return the kernel of the base estimator.""" + if self.n_classes_ == 2: + return self.base_estimator_.kernel_ + else: + return CompoundKernel( + [estimator.kernel_ for estimator in self.base_estimator_.estimators_] + ) + + def log_marginal_likelihood( + self, theta=None, eval_gradient=False, clone_kernel=True + ): + """Return log-marginal likelihood of theta for training data. + + In the case of multi-class classification, the mean log-marginal + likelihood of the one-versus-rest classifiers are returned. + + Parameters + ---------- + theta : array-like of shape (n_kernel_params,), default=None + Kernel hyperparameters for which the log-marginal likelihood is + evaluated. In the case of multi-class classification, theta may + be the hyperparameters of the compound kernel or of an individual + kernel. In the latter case, all individual kernel get assigned the + same theta values. If None, the precomputed log_marginal_likelihood + of ``self.kernel_.theta`` is returned. + + eval_gradient : bool, default=False + If True, the gradient of the log-marginal likelihood with respect + to the kernel hyperparameters at position theta is returned + additionally. Note that gradient computation is not supported + for non-binary classification. If True, theta must not be None. + + clone_kernel : bool, default=True + If True, the kernel attribute is copied. If False, the kernel + attribute is modified, but may result in a performance improvement. + + Returns + ------- + log_likelihood : float + Log-marginal likelihood of theta for training data. + + log_likelihood_gradient : ndarray of shape (n_kernel_params,), optional + Gradient of the log-marginal likelihood with respect to the kernel + hyperparameters at position theta. + Only returned when `eval_gradient` is True. + """ + check_is_fitted(self) + + if theta is None: + if eval_gradient: + raise ValueError("Gradient can only be evaluated for theta!=None") + return self.log_marginal_likelihood_value_ + + theta = np.asarray(theta) + if self.n_classes_ == 2: + return self.base_estimator_.log_marginal_likelihood( + theta, eval_gradient, clone_kernel=clone_kernel + ) + else: + if eval_gradient: + raise NotImplementedError( + "Gradient of log-marginal-likelihood not implemented for " + "multi-class GPC." + ) + estimators = self.base_estimator_.estimators_ + n_dims = estimators[0].kernel_.n_dims + if theta.shape[0] == n_dims: # use same theta for all sub-kernels + return np.mean( + [ + estimator.log_marginal_likelihood( + theta, clone_kernel=clone_kernel + ) + for i, estimator in enumerate(estimators) + ] + ) + elif theta.shape[0] == n_dims * self.classes_.shape[0]: + # theta for compound kernel + return np.mean( + [ + estimator.log_marginal_likelihood( + theta[n_dims * i : n_dims * (i + 1)], + clone_kernel=clone_kernel, + ) + for i, estimator in enumerate(estimators) + ] + ) + else: + raise ValueError( + "Shape of theta must be either %d or %d. " + "Obtained theta with shape %d." + % (n_dims, n_dims * self.classes_.shape[0], theta.shape[0]) + ) + + def latent_mean_and_variance(self, X): + """Compute the mean and variance of the latent function. + + Based on algorithm 3.2 of [RW2006]_, this function returns the latent + mean (Line 4) and variance (Line 6) of the Gaussian process + classification model. + + Note that this function is only supported for binary classification. + + .. versionadded:: 1.7 + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated for classification. + + Returns + ------- + latent_mean : array-like of shape (n_samples,) + Mean of the latent function values at the query points. + + latent_var : array-like of shape (n_samples,) + Variance of the latent function values at the query points. + """ + if self.n_classes_ > 2: + raise ValueError( + "Returning the mean and variance of the latent function f " + "is only supported for binary classification, received " + f"{self.n_classes_} classes." + ) + check_is_fitted(self) + + if self.kernel is None or self.kernel.requires_vector_input: + X = validate_data(self, X, ensure_2d=True, dtype="numeric", reset=False) + else: + X = validate_data(self, X, ensure_2d=False, dtype=None, reset=False) + + return self.base_estimator_.latent_mean_and_variance(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpr.py new file mode 100644 index 0000000000000000000000000000000000000000..d56e7735be787eaf2b1aaeaac0fce228651b2eb6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/_gpr.py @@ -0,0 +1,675 @@ +"""Gaussian processes regression.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real +from operator import itemgetter + +import numpy as np +import scipy.optimize +from scipy.linalg import cho_solve, cholesky, solve_triangular + +from ..base import BaseEstimator, MultiOutputMixin, RegressorMixin, _fit_context, clone +from ..preprocessing._data import _handle_zeros_in_scale +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.optimize import _check_optimize_result +from ..utils.validation import validate_data +from .kernels import RBF, Kernel +from .kernels import ConstantKernel as C + +GPR_CHOLESKY_LOWER = True + + +class GaussianProcessRegressor(MultiOutputMixin, RegressorMixin, BaseEstimator): + """Gaussian process regression (GPR). + + The implementation is based on Algorithm 2.1 of [RW2006]_. + + In addition to standard scikit-learn estimator API, + :class:`GaussianProcessRegressor`: + + * allows prediction without prior fitting (based on the GP prior) + * provides an additional method `sample_y(X)`, which evaluates samples + drawn from the GPR (prior or posterior) at given inputs + * exposes a method `log_marginal_likelihood(theta)`, which can be used + externally for other ways of selecting hyperparameters, e.g., via + Markov chain Monte Carlo. + + To learn the difference between a point-estimate approach vs. a more + Bayesian modelling approach, refer to the example entitled + :ref:`sphx_glr_auto_examples_gaussian_process_plot_compare_gpr_krr.py`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + kernel : kernel instance, default=None + The kernel specifying the covariance function of the GP. If None is + passed, the kernel ``ConstantKernel(1.0, constant_value_bounds="fixed") + * RBF(1.0, length_scale_bounds="fixed")`` is used as default. Note that + the kernel hyperparameters are optimized during fitting unless the + bounds are marked as "fixed". + + alpha : float or ndarray of shape (n_samples,), default=1e-10 + Value added to the diagonal of the kernel matrix during fitting. + This can prevent a potential numerical issue during fitting, by + ensuring that the calculated values form a positive definite matrix. + It can also be interpreted as the variance of additional Gaussian + measurement noise on the training observations. Note that this is + different from using a `WhiteKernel`. If an array is passed, it must + have the same number of entries as the data used for fitting and is + used as datapoint-dependent noise level. Allowing to specify the + noise level directly as a parameter is mainly for convenience and + for consistency with :class:`~sklearn.linear_model.Ridge`. + For an example illustrating how the alpha parameter controls + the noise variance in Gaussian Process Regression, see + :ref:`sphx_glr_auto_examples_gaussian_process_plot_gpr_noisy_targets.py`. + + optimizer : "fmin_l_bfgs_b", callable or None, default="fmin_l_bfgs_b" + Can either be one of the internally supported optimizers for optimizing + the kernel's parameters, specified by a string, or an externally + defined optimizer passed as a callable. If a callable is passed, it + must have the signature:: + + def optimizer(obj_func, initial_theta, bounds): + # * 'obj_func': the objective function to be minimized, which + # takes the hyperparameters theta as a parameter and an + # optional flag eval_gradient, which determines if the + # gradient is returned additionally to the function value + # * 'initial_theta': the initial value for theta, which can be + # used by local optimizers + # * 'bounds': the bounds on the values of theta + .... + # Returned are the best found hyperparameters theta and + # the corresponding value of the target function. + return theta_opt, func_min + + Per default, the L-BFGS-B algorithm from `scipy.optimize.minimize` + is used. If None is passed, the kernel's parameters are kept fixed. + Available internal optimizers are: `{'fmin_l_bfgs_b'}`. + + n_restarts_optimizer : int, default=0 + The number of restarts of the optimizer for finding the kernel's + parameters which maximize the log-marginal likelihood. The first run + of the optimizer is performed from the kernel's initial parameters, + the remaining ones (if any) from thetas sampled log-uniform randomly + from the space of allowed theta-values. If greater than 0, all bounds + must be finite. Note that `n_restarts_optimizer == 0` implies that one + run is performed. + + normalize_y : bool, default=False + Whether or not to normalize the target values `y` by removing the mean + and scaling to unit-variance. This is recommended for cases where + zero-mean, unit-variance priors are used. Note that, in this + implementation, the normalisation is reversed before the GP predictions + are reported. + + .. versionchanged:: 0.23 + + copy_X_train : bool, default=True + If True, a persistent copy of the training data is stored in the + object. Otherwise, just a reference to the training data is stored, + which might cause predictions to change if the data is modified + externally. + + n_targets : int, default=None + The number of dimensions of the target values. Used to decide the number + of outputs when sampling from the prior distributions (i.e. calling + :meth:`sample_y` before :meth:`fit`). This parameter is ignored once + :meth:`fit` has been called. + + .. versionadded:: 1.3 + + random_state : int, RandomState instance or None, default=None + Determines random number generation used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + X_train_ : array-like of shape (n_samples, n_features) or list of object + Feature vectors or other representations of training data (also + required for prediction). + + y_train_ : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values in training data (also required for prediction). + + kernel_ : kernel instance + The kernel used for prediction. The structure of the kernel is the + same as the one passed as parameter but with optimized hyperparameters. + + L_ : array-like of shape (n_samples, n_samples) + Lower-triangular Cholesky decomposition of the kernel in ``X_train_``. + + alpha_ : array-like of shape (n_samples,) + Dual coefficients of training data points in kernel space. + + log_marginal_likelihood_value_ : float + The log-marginal-likelihood of ``self.kernel_.theta``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + GaussianProcessClassifier : Gaussian process classification (GPC) + based on Laplace approximation. + + References + ---------- + .. [RW2006] `Carl E. Rasmussen and Christopher K.I. Williams, + "Gaussian Processes for Machine Learning", + MIT Press 2006 `_ + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = DotProduct() + WhiteKernel() + >>> gpr = GaussianProcessRegressor(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.3680... + >>> gpr.predict(X[:2,:], return_std=True) + (array([653.0, 592.1]), array([316.6, 316.6])) + """ + + _parameter_constraints: dict = { + "kernel": [None, Kernel], + "alpha": [Interval(Real, 0, None, closed="left"), np.ndarray], + "optimizer": [StrOptions({"fmin_l_bfgs_b"}), callable, None], + "n_restarts_optimizer": [Interval(Integral, 0, None, closed="left")], + "normalize_y": ["boolean"], + "copy_X_train": ["boolean"], + "n_targets": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + } + + def __init__( + self, + kernel=None, + *, + alpha=1e-10, + optimizer="fmin_l_bfgs_b", + n_restarts_optimizer=0, + normalize_y=False, + copy_X_train=True, + n_targets=None, + random_state=None, + ): + self.kernel = kernel + self.alpha = alpha + self.optimizer = optimizer + self.n_restarts_optimizer = n_restarts_optimizer + self.normalize_y = normalize_y + self.copy_X_train = copy_X_train + self.n_targets = n_targets + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit Gaussian process regression model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Feature vectors or other representations of training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + Returns + ------- + self : object + GaussianProcessRegressor class instance. + """ + if self.kernel is None: # Use an RBF kernel as default + self.kernel_ = C(1.0, constant_value_bounds="fixed") * RBF( + 1.0, length_scale_bounds="fixed" + ) + else: + self.kernel_ = clone(self.kernel) + + self._rng = check_random_state(self.random_state) + + if self.kernel_.requires_vector_input: + dtype, ensure_2d = "numeric", True + else: + dtype, ensure_2d = None, False + X, y = validate_data( + self, + X, + y, + multi_output=True, + y_numeric=True, + ensure_2d=ensure_2d, + dtype=dtype, + ) + + n_targets_seen = y.shape[1] if y.ndim > 1 else 1 + if self.n_targets is not None and n_targets_seen != self.n_targets: + raise ValueError( + "The number of targets seen in `y` is different from the parameter " + f"`n_targets`. Got {n_targets_seen} != {self.n_targets}." + ) + + # Normalize target value + if self.normalize_y: + self._y_train_mean = np.mean(y, axis=0) + self._y_train_std = _handle_zeros_in_scale(np.std(y, axis=0), copy=False) + + # Remove mean and make unit variance + y = (y - self._y_train_mean) / self._y_train_std + + else: + shape_y_stats = (y.shape[1],) if y.ndim == 2 else 1 + self._y_train_mean = np.zeros(shape=shape_y_stats) + self._y_train_std = np.ones(shape=shape_y_stats) + + if np.iterable(self.alpha) and self.alpha.shape[0] != y.shape[0]: + if self.alpha.shape[0] == 1: + self.alpha = self.alpha[0] + else: + raise ValueError( + "alpha must be a scalar or an array with same number of " + f"entries as y. ({self.alpha.shape[0]} != {y.shape[0]})" + ) + + self.X_train_ = np.copy(X) if self.copy_X_train else X + self.y_train_ = np.copy(y) if self.copy_X_train else y + + if self.optimizer is not None and self.kernel_.n_dims > 0: + # Choose hyperparameters based on maximizing the log-marginal + # likelihood (potentially starting from several initial values) + def obj_func(theta, eval_gradient=True): + if eval_gradient: + lml, grad = self.log_marginal_likelihood( + theta, eval_gradient=True, clone_kernel=False + ) + return -lml, -grad + else: + return -self.log_marginal_likelihood(theta, clone_kernel=False) + + # First optimize starting from theta specified in kernel + optima = [ + ( + self._constrained_optimization( + obj_func, self.kernel_.theta, self.kernel_.bounds + ) + ) + ] + + # Additional runs are performed from log-uniform chosen initial + # theta + if self.n_restarts_optimizer > 0: + if not np.isfinite(self.kernel_.bounds).all(): + raise ValueError( + "Multiple optimizer restarts (n_restarts_optimizer>0) " + "requires that all bounds are finite." + ) + bounds = self.kernel_.bounds + for iteration in range(self.n_restarts_optimizer): + theta_initial = self._rng.uniform(bounds[:, 0], bounds[:, 1]) + optima.append( + self._constrained_optimization(obj_func, theta_initial, bounds) + ) + # Select result from run with minimal (negative) log-marginal + # likelihood + lml_values = list(map(itemgetter(1), optima)) + self.kernel_.theta = optima[np.argmin(lml_values)][0] + self.kernel_._check_bounds_params() + + self.log_marginal_likelihood_value_ = -np.min(lml_values) + else: + self.log_marginal_likelihood_value_ = self.log_marginal_likelihood( + self.kernel_.theta, clone_kernel=False + ) + + # Precompute quantities required for predictions which are independent + # of actual query points + # Alg. 2.1, page 19, line 2 -> L = cholesky(K + sigma^2 I) + K = self.kernel_(self.X_train_) + K[np.diag_indices_from(K)] += self.alpha + try: + self.L_ = cholesky(K, lower=GPR_CHOLESKY_LOWER, check_finite=False) + except np.linalg.LinAlgError as exc: + exc.args = ( + ( + f"The kernel, {self.kernel_}, is not returning a positive " + "definite matrix. Try gradually increasing the 'alpha' " + "parameter of your GaussianProcessRegressor estimator." + ), + ) + exc.args + raise + # Alg 2.1, page 19, line 3 -> alpha = L^T \ (L \ y) + self.alpha_ = cho_solve( + (self.L_, GPR_CHOLESKY_LOWER), + self.y_train_, + check_finite=False, + ) + return self + + def predict(self, X, return_std=False, return_cov=False): + """Predict using the Gaussian process regression model. + + We can also predict based on an unfitted model by using the GP prior. + In addition to the mean of the predictive distribution, optionally also + returns its standard deviation (`return_std=True`) or covariance + (`return_cov=True`). Note that at most one of the two can be requested. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or list of object + Query points where the GP is evaluated. + + return_std : bool, default=False + If True, the standard-deviation of the predictive distribution at + the query points is returned along with the mean. + + return_cov : bool, default=False + If True, the covariance of the joint predictive distribution at + the query points is returned along with the mean. + + Returns + ------- + y_mean : ndarray of shape (n_samples,) or (n_samples, n_targets) + Mean of predictive distribution at query points. + + y_std : ndarray of shape (n_samples,) or (n_samples, n_targets), optional + Standard deviation of predictive distribution at query points. + Only returned when `return_std` is True. + + y_cov : ndarray of shape (n_samples, n_samples) or \ + (n_samples, n_samples, n_targets), optional + Covariance of joint predictive distribution at query points. + Only returned when `return_cov` is True. + """ + if return_std and return_cov: + raise RuntimeError( + "At most one of return_std or return_cov can be requested." + ) + + if self.kernel is None or self.kernel.requires_vector_input: + dtype, ensure_2d = "numeric", True + else: + dtype, ensure_2d = None, False + + X = validate_data(self, X, ensure_2d=ensure_2d, dtype=dtype, reset=False) + + if not hasattr(self, "X_train_"): # Unfitted;predict based on GP prior + if self.kernel is None: + kernel = C(1.0, constant_value_bounds="fixed") * RBF( + 1.0, length_scale_bounds="fixed" + ) + else: + kernel = self.kernel + + n_targets = self.n_targets if self.n_targets is not None else 1 + y_mean = np.zeros(shape=(X.shape[0], n_targets)).squeeze() + + if return_cov: + y_cov = kernel(X) + if n_targets > 1: + y_cov = np.repeat( + np.expand_dims(y_cov, -1), repeats=n_targets, axis=-1 + ) + return y_mean, y_cov + elif return_std: + y_var = kernel.diag(X) + if n_targets > 1: + y_var = np.repeat( + np.expand_dims(y_var, -1), repeats=n_targets, axis=-1 + ) + return y_mean, np.sqrt(y_var) + else: + return y_mean + else: # Predict based on GP posterior + # Alg 2.1, page 19, line 4 -> f*_bar = K(X_test, X_train) . alpha + K_trans = self.kernel_(X, self.X_train_) + y_mean = K_trans @ self.alpha_ + + # undo normalisation + y_mean = self._y_train_std * y_mean + self._y_train_mean + + # if y_mean has shape (n_samples, 1), reshape to (n_samples,) + if y_mean.ndim > 1 and y_mean.shape[1] == 1: + y_mean = np.squeeze(y_mean, axis=1) + + # Alg 2.1, page 19, line 5 -> v = L \ K(X_test, X_train)^T + V = solve_triangular( + self.L_, K_trans.T, lower=GPR_CHOLESKY_LOWER, check_finite=False + ) + + if return_cov: + # Alg 2.1, page 19, line 6 -> K(X_test, X_test) - v^T. v + y_cov = self.kernel_(X) - V.T @ V + + # undo normalisation + y_cov = np.outer(y_cov, self._y_train_std**2).reshape(*y_cov.shape, -1) + # if y_cov has shape (n_samples, n_samples, 1), reshape to + # (n_samples, n_samples) + if y_cov.shape[2] == 1: + y_cov = np.squeeze(y_cov, axis=2) + + return y_mean, y_cov + elif return_std: + # Compute variance of predictive distribution + # Use einsum to avoid explicitly forming the large matrix + # V^T @ V just to extract its diagonal afterward. + y_var = self.kernel_.diag(X).copy() + y_var -= np.einsum("ij,ji->i", V.T, V) + + # Check if any of the variances is negative because of + # numerical issues. If yes: set the variance to 0. + y_var_negative = y_var < 0 + if np.any(y_var_negative): + warnings.warn( + "Predicted variances smaller than 0. " + "Setting those variances to 0." + ) + y_var[y_var_negative] = 0.0 + + # undo normalisation + y_var = np.outer(y_var, self._y_train_std**2).reshape(*y_var.shape, -1) + + # if y_var has shape (n_samples, 1), reshape to (n_samples,) + if y_var.shape[1] == 1: + y_var = np.squeeze(y_var, axis=1) + + return y_mean, np.sqrt(y_var) + else: + return y_mean + + def sample_y(self, X, n_samples=1, random_state=0): + """Draw samples from Gaussian process and evaluate at X. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Query points where the GP is evaluated. + + n_samples : int, default=1 + Number of samples drawn from the Gaussian process per query point. + + random_state : int, RandomState instance or None, default=0 + Determines random number generation to randomly draw samples. + Pass an int for reproducible results across multiple function + calls. + See :term:`Glossary `. + + Returns + ------- + y_samples : ndarray of shape (n_samples_X, n_samples), or \ + (n_samples_X, n_targets, n_samples) + Values of n_samples samples drawn from Gaussian process and + evaluated at query points. + """ + rng = check_random_state(random_state) + + y_mean, y_cov = self.predict(X, return_cov=True) + if y_mean.ndim == 1: + y_samples = rng.multivariate_normal(y_mean, y_cov, n_samples).T + else: + y_samples = [ + rng.multivariate_normal( + y_mean[:, target], y_cov[..., target], n_samples + ).T[:, np.newaxis] + for target in range(y_mean.shape[1]) + ] + y_samples = np.hstack(y_samples) + return y_samples + + def log_marginal_likelihood( + self, theta=None, eval_gradient=False, clone_kernel=True + ): + """Return log-marginal likelihood of theta for training data. + + Parameters + ---------- + theta : array-like of shape (n_kernel_params,) default=None + Kernel hyperparameters for which the log-marginal likelihood is + evaluated. If None, the precomputed log_marginal_likelihood + of ``self.kernel_.theta`` is returned. + + eval_gradient : bool, default=False + If True, the gradient of the log-marginal likelihood with respect + to the kernel hyperparameters at position theta is returned + additionally. If True, theta must not be None. + + clone_kernel : bool, default=True + If True, the kernel attribute is copied. If False, the kernel + attribute is modified, but may result in a performance improvement. + + Returns + ------- + log_likelihood : float + Log-marginal likelihood of theta for training data. + + log_likelihood_gradient : ndarray of shape (n_kernel_params,), optional + Gradient of the log-marginal likelihood with respect to the kernel + hyperparameters at position theta. + Only returned when eval_gradient is True. + """ + if theta is None: + if eval_gradient: + raise ValueError("Gradient can only be evaluated for theta!=None") + return self.log_marginal_likelihood_value_ + + if clone_kernel: + kernel = self.kernel_.clone_with_theta(theta) + else: + kernel = self.kernel_ + kernel.theta = theta + + if eval_gradient: + K, K_gradient = kernel(self.X_train_, eval_gradient=True) + else: + K = kernel(self.X_train_) + + # Alg. 2.1, page 19, line 2 -> L = cholesky(K + sigma^2 I) + K[np.diag_indices_from(K)] += self.alpha + try: + L = cholesky(K, lower=GPR_CHOLESKY_LOWER, check_finite=False) + except np.linalg.LinAlgError: + return (-np.inf, np.zeros_like(theta)) if eval_gradient else -np.inf + + # Support multi-dimensional output of self.y_train_ + y_train = self.y_train_ + if y_train.ndim == 1: + y_train = y_train[:, np.newaxis] + + # Alg 2.1, page 19, line 3 -> alpha = L^T \ (L \ y) + alpha = cho_solve((L, GPR_CHOLESKY_LOWER), y_train, check_finite=False) + + # Alg 2.1, page 19, line 7 + # -0.5 . y^T . alpha - sum(log(diag(L))) - n_samples / 2 log(2*pi) + # y is originally thought to be a (1, n_samples) row vector. However, + # in multioutputs, y is of shape (n_samples, 2) and we need to compute + # y^T . alpha for each output, independently using einsum. Thus, it + # is equivalent to: + # for output_idx in range(n_outputs): + # log_likelihood_dims[output_idx] = ( + # y_train[:, [output_idx]] @ alpha[:, [output_idx]] + # ) + log_likelihood_dims = -0.5 * np.einsum("ik,ik->k", y_train, alpha) + log_likelihood_dims -= np.log(np.diag(L)).sum() + log_likelihood_dims -= K.shape[0] / 2 * np.log(2 * np.pi) + # the log likelihood is sum-up across the outputs + log_likelihood = log_likelihood_dims.sum(axis=-1) + + if eval_gradient: + # Eq. 5.9, p. 114, and footnote 5 in p. 114 + # 0.5 * trace((alpha . alpha^T - K^-1) . K_gradient) + # alpha is supposed to be a vector of (n_samples,) elements. With + # multioutputs, alpha is a matrix of size (n_samples, n_outputs). + # Therefore, we want to construct a matrix of + # (n_samples, n_samples, n_outputs) equivalent to + # for output_idx in range(n_outputs): + # output_alpha = alpha[:, [output_idx]] + # inner_term[..., output_idx] = output_alpha @ output_alpha.T + inner_term = np.einsum("ik,jk->ijk", alpha, alpha) + # compute K^-1 of shape (n_samples, n_samples) + K_inv = cho_solve( + (L, GPR_CHOLESKY_LOWER), np.eye(K.shape[0]), check_finite=False + ) + # create a new axis to use broadcasting between inner_term and + # K_inv + inner_term -= K_inv[..., np.newaxis] + # Since we are interested about the trace of + # inner_term @ K_gradient, we don't explicitly compute the + # matrix-by-matrix operation and instead use an einsum. Therefore + # it is equivalent to: + # for param_idx in range(n_kernel_params): + # for output_idx in range(n_output): + # log_likehood_gradient_dims[param_idx, output_idx] = ( + # inner_term[..., output_idx] @ + # K_gradient[..., param_idx] + # ) + log_likelihood_gradient_dims = 0.5 * np.einsum( + "ijl,jik->kl", inner_term, K_gradient + ) + # the log likelihood gradient is the sum-up across the outputs + log_likelihood_gradient = log_likelihood_gradient_dims.sum(axis=-1) + + if eval_gradient: + return log_likelihood, log_likelihood_gradient + else: + return log_likelihood + + def _constrained_optimization(self, obj_func, initial_theta, bounds): + if self.optimizer == "fmin_l_bfgs_b": + opt_res = scipy.optimize.minimize( + obj_func, + initial_theta, + method="L-BFGS-B", + jac=True, + bounds=bounds, + ) + _check_optimize_result("lbfgs", opt_res) + theta_opt, func_min = opt_res.x, opt_res.fun + elif callable(self.optimizer): + theta_opt, func_min = self.optimizer(obj_func, initial_theta, bounds=bounds) + else: + raise ValueError(f"Unknown optimizer {self.optimizer}.") + + return theta_opt, func_min + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.requires_fit = False + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/kernels.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..4a0a6ec667be421695e9d5e85d8282887614a2fe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/kernels.py @@ -0,0 +1,2408 @@ +"""A set of kernels that can be combined by operators and used in Gaussian processes.""" + +# Kernels for Gaussian process regression and classification. +# +# The kernels in this module allow kernel-engineering, i.e., they can be +# combined via the "+" and "*" operators or be exponentiated with a scalar +# via "**". These sum and product expressions can also contain scalar values, +# which are automatically converted to a constant kernel. +# +# All kernels allow (analytic) gradient-based hyperparameter optimization. +# The space of hyperparameters can be specified by giving lower und upper +# boundaries for the value of each hyperparameter (the search space is thus +# rectangular). Instead of specifying bounds, hyperparameters can also be +# declared to be "fixed", which causes these hyperparameters to be excluded from +# optimization. + + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# Note: this module is strongly inspired by the kernel module of the george +# package. + +import math +import warnings +from abc import ABCMeta, abstractmethod +from collections import namedtuple +from inspect import signature + +import numpy as np +from scipy.spatial.distance import cdist, pdist, squareform +from scipy.special import gamma, kv + +from ..base import clone +from ..exceptions import ConvergenceWarning +from ..metrics.pairwise import pairwise_kernels +from ..utils.validation import _num_samples + + +def _check_length_scale(X, length_scale): + length_scale = np.squeeze(length_scale).astype(float) + if np.ndim(length_scale) > 1: + raise ValueError("length_scale cannot be of dimension greater than 1") + if np.ndim(length_scale) == 1 and X.shape[1] != length_scale.shape[0]: + raise ValueError( + "Anisotropic kernel must have the same number of " + "dimensions as data (%d!=%d)" % (length_scale.shape[0], X.shape[1]) + ) + return length_scale + + +class Hyperparameter( + namedtuple( + "Hyperparameter", ("name", "value_type", "bounds", "n_elements", "fixed") + ) +): + """A kernel hyperparameter's specification in form of a namedtuple. + + .. versionadded:: 0.18 + + Attributes + ---------- + name : str + The name of the hyperparameter. Note that a kernel using a + hyperparameter with name "x" must have the attributes self.x and + self.x_bounds + + value_type : str + The type of the hyperparameter. Currently, only "numeric" + hyperparameters are supported. + + bounds : pair of floats >= 0 or "fixed" + The lower and upper bound on the parameter. If n_elements>1, a pair + of 1d array with n_elements each may be given alternatively. If + the string "fixed" is passed as bounds, the hyperparameter's value + cannot be changed. + + n_elements : int, default=1 + The number of elements of the hyperparameter value. Defaults to 1, + which corresponds to a scalar hyperparameter. n_elements > 1 + corresponds to a hyperparameter which is vector-valued, + such as, e.g., anisotropic length-scales. + + fixed : bool, default=None + Whether the value of this hyperparameter is fixed, i.e., cannot be + changed during hyperparameter tuning. If None is passed, the "fixed" is + derived based on the given bounds. + + Examples + -------- + >>> from sklearn.gaussian_process.kernels import ConstantKernel + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import Hyperparameter + >>> X, y = make_friedman2(n_samples=50, noise=0, random_state=0) + >>> kernel = ConstantKernel(constant_value=1.0, + ... constant_value_bounds=(0.0, 10.0)) + + We can access each hyperparameter: + + >>> for hyperparameter in kernel.hyperparameters: + ... print(hyperparameter) + Hyperparameter(name='constant_value', value_type='numeric', + bounds=array([[ 0., 10.]]), n_elements=1, fixed=False) + + >>> params = kernel.get_params() + >>> for key in sorted(params): print(f"{key} : {params[key]}") + constant_value : 1.0 + constant_value_bounds : (0.0, 10.0) + """ + + # A raw namedtuple is very memory efficient as it packs the attributes + # in a struct to get rid of the __dict__ of attributes in particular it + # does not copy the string for the keys on each instance. + # By deriving a namedtuple class just to introduce the __init__ method we + # would also reintroduce the __dict__ on the instance. By telling the + # Python interpreter that this subclass uses static __slots__ instead of + # dynamic attributes. Furthermore we don't need any additional slot in the + # subclass so we set __slots__ to the empty tuple. + __slots__ = () + + def __new__(cls, name, value_type, bounds, n_elements=1, fixed=None): + if not isinstance(bounds, str) or bounds != "fixed": + bounds = np.atleast_2d(bounds) + if n_elements > 1: # vector-valued parameter + if bounds.shape[0] == 1: + bounds = np.repeat(bounds, n_elements, 0) + elif bounds.shape[0] != n_elements: + raise ValueError( + "Bounds on %s should have either 1 or " + "%d dimensions. Given are %d" + % (name, n_elements, bounds.shape[0]) + ) + + if fixed is None: + fixed = isinstance(bounds, str) and bounds == "fixed" + return super().__new__(cls, name, value_type, bounds, n_elements, fixed) + + # This is mainly a testing utility to check that two hyperparameters + # are equal. + def __eq__(self, other): + return ( + self.name == other.name + and self.value_type == other.value_type + and np.all(self.bounds == other.bounds) + and self.n_elements == other.n_elements + and self.fixed == other.fixed + ) + + +class Kernel(metaclass=ABCMeta): + """Base class for all kernels. + + .. versionadded:: 0.18 + + Examples + -------- + >>> from sklearn.gaussian_process.kernels import Kernel, RBF + >>> import numpy as np + >>> class CustomKernel(Kernel): + ... def __init__(self, length_scale=1.0): + ... self.length_scale = length_scale + ... def __call__(self, X, Y=None): + ... if Y is None: + ... Y = X + ... return np.inner(X, X if Y is None else Y) ** 2 + ... def diag(self, X): + ... return np.ones(X.shape[0]) + ... def is_stationary(self): + ... return True + >>> kernel = CustomKernel(length_scale=2.0) + >>> X = np.array([[1, 2], [3, 4]]) + >>> print(kernel(X)) + [[ 25 121] + [121 625]] + """ + + def get_params(self, deep=True): + """Get parameters of this kernel. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : dict + Parameter names mapped to their values. + """ + params = dict() + + # introspect the constructor arguments to find the model parameters + # to represent + cls = self.__class__ + init = getattr(cls.__init__, "deprecated_original", cls.__init__) + init_sign = signature(init) + args, varargs = [], [] + for parameter in init_sign.parameters.values(): + if parameter.kind != parameter.VAR_KEYWORD and parameter.name != "self": + args.append(parameter.name) + if parameter.kind == parameter.VAR_POSITIONAL: + varargs.append(parameter.name) + + if len(varargs) != 0: + raise RuntimeError( + "scikit-learn kernels should always " + "specify their parameters in the signature" + " of their __init__ (no varargs)." + " %s doesn't follow this convention." % (cls,) + ) + for arg in args: + params[arg] = getattr(self, arg) + + return params + + def set_params(self, **params): + """Set the parameters of this kernel. + + The method works on simple kernels as well as on nested kernels. + The latter have parameters of the form ``__`` + so that it's possible to update each component of a nested object. + + Returns + ------- + self + """ + if not params: + # Simple optimisation to gain speed (inspect is slow) + return self + valid_params = self.get_params(deep=True) + for key, value in params.items(): + split = key.split("__", 1) + if len(split) > 1: + # nested objects case + name, sub_name = split + if name not in valid_params: + raise ValueError( + "Invalid parameter %s for kernel %s. " + "Check the list of available parameters " + "with `kernel.get_params().keys()`." % (name, self) + ) + sub_object = valid_params[name] + sub_object.set_params(**{sub_name: value}) + else: + # simple objects case + if key not in valid_params: + raise ValueError( + "Invalid parameter %s for kernel %s. " + "Check the list of available parameters " + "with `kernel.get_params().keys()`." + % (key, self.__class__.__name__) + ) + setattr(self, key, value) + return self + + def clone_with_theta(self, theta): + """Returns a clone of self with given hyperparameters theta. + + Parameters + ---------- + theta : ndarray of shape (n_dims,) + The hyperparameters + """ + cloned = clone(self) + cloned.theta = theta + return cloned + + @property + def n_dims(self): + """Returns the number of non-fixed hyperparameters of the kernel.""" + return self.theta.shape[0] + + @property + def hyperparameters(self): + """Returns a list of all hyperparameter specifications.""" + r = [ + getattr(self, attr) + for attr in dir(self) + if attr.startswith("hyperparameter_") + ] + return r + + @property + def theta(self): + """Returns the (flattened, log-transformed) non-fixed hyperparameters. + + Note that theta are typically the log-transformed values of the + kernel's hyperparameters as this representation of the search space + is more amenable for hyperparameter search, as hyperparameters like + length-scales naturally live on a log-scale. + + Returns + ------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + theta = [] + params = self.get_params() + for hyperparameter in self.hyperparameters: + if not hyperparameter.fixed: + theta.append(params[hyperparameter.name]) + if len(theta) > 0: + return np.log(np.hstack(theta)) + else: + return np.array([]) + + @theta.setter + def theta(self, theta): + """Sets the (flattened, log-transformed) non-fixed hyperparameters. + + Parameters + ---------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + params = self.get_params() + i = 0 + for hyperparameter in self.hyperparameters: + if hyperparameter.fixed: + continue + if hyperparameter.n_elements > 1: + # vector-valued parameter + params[hyperparameter.name] = np.exp( + theta[i : i + hyperparameter.n_elements] + ) + i += hyperparameter.n_elements + else: + params[hyperparameter.name] = np.exp(theta[i]) + i += 1 + + if i != len(theta): + raise ValueError( + "theta has not the correct number of entries." + " Should be %d; given are %d" % (i, len(theta)) + ) + self.set_params(**params) + + @property + def bounds(self): + """Returns the log-transformed bounds on the theta. + + Returns + ------- + bounds : ndarray of shape (n_dims, 2) + The log-transformed bounds on the kernel's hyperparameters theta + """ + bounds = [ + hyperparameter.bounds + for hyperparameter in self.hyperparameters + if not hyperparameter.fixed + ] + if len(bounds) > 0: + return np.log(np.vstack(bounds)) + else: + return np.array([]) + + def __add__(self, b): + if not isinstance(b, Kernel): + return Sum(self, ConstantKernel(b)) + return Sum(self, b) + + def __radd__(self, b): + if not isinstance(b, Kernel): + return Sum(ConstantKernel(b), self) + return Sum(b, self) + + def __mul__(self, b): + if not isinstance(b, Kernel): + return Product(self, ConstantKernel(b)) + return Product(self, b) + + def __rmul__(self, b): + if not isinstance(b, Kernel): + return Product(ConstantKernel(b), self) + return Product(b, self) + + def __pow__(self, b): + return Exponentiation(self, b) + + def __eq__(self, b): + if type(self) != type(b): + return False + params_a = self.get_params() + params_b = b.get_params() + for key in set(list(params_a.keys()) + list(params_b.keys())): + if np.any(params_a.get(key, None) != params_b.get(key, None)): + return False + return True + + def __repr__(self): + return "{0}({1})".format( + self.__class__.__name__, ", ".join(map("{0:.3g}".format, self.theta)) + ) + + @abstractmethod + def __call__(self, X, Y=None, eval_gradient=False): + """Evaluate the kernel.""" + + @abstractmethod + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples,) + Left argument of the returned kernel k(X, Y) + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + + @abstractmethod + def is_stationary(self): + """Returns whether the kernel is stationary.""" + + @property + def requires_vector_input(self): + """Returns whether the kernel is defined on fixed-length feature + vectors or generic objects. Defaults to True for backward + compatibility.""" + return True + + def _check_bounds_params(self): + """Called after fitting to warn if bounds may have been too tight.""" + list_close = np.isclose(self.bounds, np.atleast_2d(self.theta).T) + idx = 0 + for hyp in self.hyperparameters: + if hyp.fixed: + continue + for dim in range(hyp.n_elements): + if list_close[idx, 0]: + warnings.warn( + "The optimal value found for " + "dimension %s of parameter %s is " + "close to the specified lower " + "bound %s. Decreasing the bound and" + " calling fit again may find a " + "better value." % (dim, hyp.name, hyp.bounds[dim][0]), + ConvergenceWarning, + ) + elif list_close[idx, 1]: + warnings.warn( + "The optimal value found for " + "dimension %s of parameter %s is " + "close to the specified upper " + "bound %s. Increasing the bound and" + " calling fit again may find a " + "better value." % (dim, hyp.name, hyp.bounds[dim][1]), + ConvergenceWarning, + ) + idx += 1 + + +class NormalizedKernelMixin: + """Mixin for kernels which are normalized: k(X, X)=1. + + .. versionadded:: 0.18 + """ + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return np.ones(X.shape[0]) + + +class StationaryKernelMixin: + """Mixin for kernels which are stationary: k(X, Y)= f(X-Y). + + .. versionadded:: 0.18 + """ + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return True + + +class GenericKernelMixin: + """Mixin for kernels which operate on generic objects such as variable- + length sequences, trees, and graphs. + + .. versionadded:: 0.22 + """ + + @property + def requires_vector_input(self): + """Whether the kernel works only on fixed-length feature vectors.""" + return False + + +class CompoundKernel(Kernel): + """Kernel which is composed of a set of other kernels. + + .. versionadded:: 0.18 + + Parameters + ---------- + kernels : list of Kernels + The other kernels + + Examples + -------- + >>> from sklearn.gaussian_process.kernels import WhiteKernel + >>> from sklearn.gaussian_process.kernels import RBF + >>> from sklearn.gaussian_process.kernels import CompoundKernel + >>> kernel = CompoundKernel( + ... [WhiteKernel(noise_level=3.0), RBF(length_scale=2.0)]) + >>> print(kernel.bounds) + [[-11.51292546 11.51292546] + [-11.51292546 11.51292546]] + >>> print(kernel.n_dims) + 2 + >>> print(kernel.theta) + [1.09861229 0.69314718] + """ + + def __init__(self, kernels): + self.kernels = kernels + + def get_params(self, deep=True): + """Get parameters of this kernel. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : dict + Parameter names mapped to their values. + """ + return dict(kernels=self.kernels) + + @property + def theta(self): + """Returns the (flattened, log-transformed) non-fixed hyperparameters. + + Note that theta are typically the log-transformed values of the + kernel's hyperparameters as this representation of the search space + is more amenable for hyperparameter search, as hyperparameters like + length-scales naturally live on a log-scale. + + Returns + ------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + return np.hstack([kernel.theta for kernel in self.kernels]) + + @theta.setter + def theta(self, theta): + """Sets the (flattened, log-transformed) non-fixed hyperparameters. + + Parameters + ---------- + theta : array of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + k_dims = self.k1.n_dims + for i, kernel in enumerate(self.kernels): + kernel.theta = theta[i * k_dims : (i + 1) * k_dims] + + @property + def bounds(self): + """Returns the log-transformed bounds on the theta. + + Returns + ------- + bounds : array of shape (n_dims, 2) + The log-transformed bounds on the kernel's hyperparameters theta + """ + return np.vstack([kernel.bounds for kernel in self.kernels]) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Note that this compound kernel returns the results of all simple kernel + stacked along an additional axis. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object, \ + default=None + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_X, n_features) or list of object, \ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of the + kernel hyperparameter is computed. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y, n_kernels) + Kernel k(X, Y) + + K_gradient : ndarray of shape \ + (n_samples_X, n_samples_X, n_dims, n_kernels), optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + if eval_gradient: + K = [] + K_grad = [] + for kernel in self.kernels: + K_single, K_grad_single = kernel(X, Y, eval_gradient) + K.append(K_single) + K_grad.append(K_grad_single[..., np.newaxis]) + return np.dstack(K), np.concatenate(K_grad, 3) + else: + return np.dstack([kernel(X, Y, eval_gradient) for kernel in self.kernels]) + + def __eq__(self, b): + if type(self) != type(b) or len(self.kernels) != len(b.kernels): + return False + return np.all( + [self.kernels[i] == b.kernels[i] for i in range(len(self.kernels))] + ) + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return np.all([kernel.is_stationary() for kernel in self.kernels]) + + @property + def requires_vector_input(self): + """Returns whether the kernel is defined on discrete structures.""" + return np.any([kernel.requires_vector_input for kernel in self.kernels]) + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to `np.diag(self(X))`; however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X, n_kernels) + Diagonal of kernel k(X, X) + """ + return np.vstack([kernel.diag(X) for kernel in self.kernels]).T + + +class KernelOperator(Kernel): + """Base class for all kernel operators. + + .. versionadded:: 0.18 + """ + + def __init__(self, k1, k2): + self.k1 = k1 + self.k2 = k2 + + def get_params(self, deep=True): + """Get parameters of this kernel. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : dict + Parameter names mapped to their values. + """ + params = dict(k1=self.k1, k2=self.k2) + if deep: + deep_items = self.k1.get_params().items() + params.update(("k1__" + k, val) for k, val in deep_items) + deep_items = self.k2.get_params().items() + params.update(("k2__" + k, val) for k, val in deep_items) + + return params + + @property + def hyperparameters(self): + """Returns a list of all hyperparameter.""" + r = [ + Hyperparameter( + "k1__" + hyperparameter.name, + hyperparameter.value_type, + hyperparameter.bounds, + hyperparameter.n_elements, + ) + for hyperparameter in self.k1.hyperparameters + ] + + for hyperparameter in self.k2.hyperparameters: + r.append( + Hyperparameter( + "k2__" + hyperparameter.name, + hyperparameter.value_type, + hyperparameter.bounds, + hyperparameter.n_elements, + ) + ) + return r + + @property + def theta(self): + """Returns the (flattened, log-transformed) non-fixed hyperparameters. + + Note that theta are typically the log-transformed values of the + kernel's hyperparameters as this representation of the search space + is more amenable for hyperparameter search, as hyperparameters like + length-scales naturally live on a log-scale. + + Returns + ------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + return np.append(self.k1.theta, self.k2.theta) + + @theta.setter + def theta(self, theta): + """Sets the (flattened, log-transformed) non-fixed hyperparameters. + + Parameters + ---------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + k1_dims = self.k1.n_dims + self.k1.theta = theta[:k1_dims] + self.k2.theta = theta[k1_dims:] + + @property + def bounds(self): + """Returns the log-transformed bounds on the theta. + + Returns + ------- + bounds : ndarray of shape (n_dims, 2) + The log-transformed bounds on the kernel's hyperparameters theta + """ + if self.k1.bounds.size == 0: + return self.k2.bounds + if self.k2.bounds.size == 0: + return self.k1.bounds + return np.vstack((self.k1.bounds, self.k2.bounds)) + + def __eq__(self, b): + if type(self) != type(b): + return False + return (self.k1 == b.k1 and self.k2 == b.k2) or ( + self.k1 == b.k2 and self.k2 == b.k1 + ) + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return self.k1.is_stationary() and self.k2.is_stationary() + + @property + def requires_vector_input(self): + """Returns whether the kernel is stationary.""" + return self.k1.requires_vector_input or self.k2.requires_vector_input + + +class Sum(KernelOperator): + """The `Sum` kernel takes two kernels :math:`k_1` and :math:`k_2` + and combines them via + + .. math:: + k_{sum}(X, Y) = k_1(X, Y) + k_2(X, Y) + + Note that the `__add__` magic method is overridden, so + `Sum(RBF(), RBF())` is equivalent to using the + operator + with `RBF() + RBF()`. + + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + k1 : Kernel + The first base-kernel of the sum-kernel + + k2 : Kernel + The second base-kernel of the sum-kernel + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import RBF, Sum, ConstantKernel + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = Sum(ConstantKernel(2), RBF()) + >>> gpr = GaussianProcessRegressor(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 1.0 + >>> kernel + 1.41**2 + RBF(length_scale=1) + """ + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_X, n_features) or list of object,\ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims),\ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + if eval_gradient: + K1, K1_gradient = self.k1(X, Y, eval_gradient=True) + K2, K2_gradient = self.k2(X, Y, eval_gradient=True) + return K1 + K2, np.dstack((K1_gradient, K2_gradient)) + else: + return self.k1(X, Y) + self.k2(X, Y) + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to `np.diag(self(X))`; however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return self.k1.diag(X) + self.k2.diag(X) + + def __repr__(self): + return "{0} + {1}".format(self.k1, self.k2) + + +class Product(KernelOperator): + """The `Product` kernel takes two kernels :math:`k_1` and :math:`k_2` + and combines them via + + .. math:: + k_{prod}(X, Y) = k_1(X, Y) * k_2(X, Y) + + Note that the `__mul__` magic method is overridden, so + `Product(RBF(), RBF())` is equivalent to using the * operator + with `RBF() * RBF()`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + k1 : Kernel + The first base-kernel of the product-kernel + + k2 : Kernel + The second base-kernel of the product-kernel + + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import (RBF, Product, + ... ConstantKernel) + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = Product(ConstantKernel(2), RBF()) + >>> gpr = GaussianProcessRegressor(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 1.0 + >>> kernel + 1.41**2 * RBF(length_scale=1) + """ + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_Y, n_features) or list of object,\ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims), \ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + if eval_gradient: + K1, K1_gradient = self.k1(X, Y, eval_gradient=True) + K2, K2_gradient = self.k2(X, Y, eval_gradient=True) + return K1 * K2, np.dstack( + (K1_gradient * K2[:, :, np.newaxis], K2_gradient * K1[:, :, np.newaxis]) + ) + else: + return self.k1(X, Y) * self.k2(X, Y) + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return self.k1.diag(X) * self.k2.diag(X) + + def __repr__(self): + return "{0} * {1}".format(self.k1, self.k2) + + +class Exponentiation(Kernel): + """The Exponentiation kernel takes one base kernel and a scalar parameter + :math:`p` and combines them via + + .. math:: + k_{exp}(X, Y) = k(X, Y) ^p + + Note that the `__pow__` magic method is overridden, so + `Exponentiation(RBF(), 2)` is equivalent to using the ** operator + with `RBF() ** 2`. + + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + kernel : Kernel + The base kernel + + exponent : float + The exponent for the base kernel + + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import (RationalQuadratic, + ... Exponentiation) + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = Exponentiation(RationalQuadratic(), exponent=2) + >>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.419 + >>> gpr.predict(X[:1,:], return_std=True) + (array([635.5]), array([0.559])) + """ + + def __init__(self, kernel, exponent): + self.kernel = kernel + self.exponent = exponent + + def get_params(self, deep=True): + """Get parameters of this kernel. + + Parameters + ---------- + deep : bool, default=True + If True, will return the parameters for this estimator and + contained subobjects that are estimators. + + Returns + ------- + params : dict + Parameter names mapped to their values. + """ + params = dict(kernel=self.kernel, exponent=self.exponent) + if deep: + deep_items = self.kernel.get_params().items() + params.update(("kernel__" + k, val) for k, val in deep_items) + return params + + @property + def hyperparameters(self): + """Returns a list of all hyperparameter.""" + r = [] + for hyperparameter in self.kernel.hyperparameters: + r.append( + Hyperparameter( + "kernel__" + hyperparameter.name, + hyperparameter.value_type, + hyperparameter.bounds, + hyperparameter.n_elements, + ) + ) + return r + + @property + def theta(self): + """Returns the (flattened, log-transformed) non-fixed hyperparameters. + + Note that theta are typically the log-transformed values of the + kernel's hyperparameters as this representation of the search space + is more amenable for hyperparameter search, as hyperparameters like + length-scales naturally live on a log-scale. + + Returns + ------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + return self.kernel.theta + + @theta.setter + def theta(self, theta): + """Sets the (flattened, log-transformed) non-fixed hyperparameters. + + Parameters + ---------- + theta : ndarray of shape (n_dims,) + The non-fixed, log-transformed hyperparameters of the kernel + """ + self.kernel.theta = theta + + @property + def bounds(self): + """Returns the log-transformed bounds on the theta. + + Returns + ------- + bounds : ndarray of shape (n_dims, 2) + The log-transformed bounds on the kernel's hyperparameters theta + """ + return self.kernel.bounds + + def __eq__(self, b): + if type(self) != type(b): + return False + return self.kernel == b.kernel and self.exponent == b.exponent + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_Y, n_features) or list of object,\ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims),\ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + if eval_gradient: + K, K_gradient = self.kernel(X, Y, eval_gradient=True) + K_gradient *= self.exponent * K[:, :, np.newaxis] ** (self.exponent - 1) + return K**self.exponent, K_gradient + else: + K = self.kernel(X, Y, eval_gradient=False) + return K**self.exponent + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return self.kernel.diag(X) ** self.exponent + + def __repr__(self): + return "{0} ** {1}".format(self.kernel, self.exponent) + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return self.kernel.is_stationary() + + @property + def requires_vector_input(self): + """Returns whether the kernel is defined on discrete structures.""" + return self.kernel.requires_vector_input + + +class ConstantKernel(StationaryKernelMixin, GenericKernelMixin, Kernel): + """Constant kernel. + + Can be used as part of a product-kernel where it scales the magnitude of + the other factor (kernel) or as part of a sum-kernel, where it modifies + the mean of the Gaussian process. + + .. math:: + k(x_1, x_2) = constant\\_value \\;\\forall\\; x_1, x_2 + + Adding a constant kernel is equivalent to adding a constant:: + + kernel = RBF() + ConstantKernel(constant_value=2) + + is the same as:: + + kernel = RBF() + 2 + + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + constant_value : float, default=1.0 + The constant value which defines the covariance: + k(x_1, x_2) = constant_value + + constant_value_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on `constant_value`. + If set to "fixed", `constant_value` cannot be changed during + hyperparameter tuning. + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import RBF, ConstantKernel + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = RBF() + ConstantKernel(constant_value=2) + >>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.3696 + >>> gpr.predict(X[:1,:], return_std=True) + (array([606.1]), array([0.248])) + """ + + def __init__(self, constant_value=1.0, constant_value_bounds=(1e-5, 1e5)): + self.constant_value = constant_value + self.constant_value_bounds = constant_value_bounds + + @property + def hyperparameter_constant_value(self): + return Hyperparameter("constant_value", "numeric", self.constant_value_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_X, n_features) or list of object, \ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims), \ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when eval_gradient + is True. + """ + if Y is None: + Y = X + elif eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + + K = np.full( + (_num_samples(X), _num_samples(Y)), + self.constant_value, + dtype=np.array(self.constant_value).dtype, + ) + if eval_gradient: + if not self.hyperparameter_constant_value.fixed: + return ( + K, + np.full( + (_num_samples(X), _num_samples(X), 1), + self.constant_value, + dtype=np.array(self.constant_value).dtype, + ), + ) + else: + return K, np.empty((_num_samples(X), _num_samples(X), 0)) + else: + return K + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return np.full( + _num_samples(X), + self.constant_value, + dtype=np.array(self.constant_value).dtype, + ) + + def __repr__(self): + return "{0:.3g}**2".format(np.sqrt(self.constant_value)) + + +class WhiteKernel(StationaryKernelMixin, GenericKernelMixin, Kernel): + """White kernel. + + The main use-case of this kernel is as part of a sum-kernel where it + explains the noise of the signal as independently and identically + normally-distributed. The parameter noise_level equals the variance of this + noise. + + .. math:: + k(x_1, x_2) = noise\\_level \\text{ if } x_i == x_j \\text{ else } 0 + + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + noise_level : float, default=1.0 + Parameter controlling the noise level (variance) + + noise_level_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'noise_level'. + If set to "fixed", 'noise_level' cannot be changed during + hyperparameter tuning. + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = DotProduct() + WhiteKernel(noise_level=0.5) + >>> gpr = GaussianProcessRegressor(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.3680 + >>> gpr.predict(X[:2,:], return_std=True) + (array([653.0, 592.1 ]), array([316.6, 316.6])) + """ + + def __init__(self, noise_level=1.0, noise_level_bounds=(1e-5, 1e5)): + self.noise_level = noise_level + self.noise_level_bounds = noise_level_bounds + + @property + def hyperparameter_noise_level(self): + return Hyperparameter("noise_level", "numeric", self.noise_level_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Left argument of the returned kernel k(X, Y) + + Y : array-like of shape (n_samples_X, n_features) or list of object,\ + default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + is evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims),\ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when eval_gradient + is True. + """ + if Y is not None and eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + + if Y is None: + K = self.noise_level * np.eye(_num_samples(X)) + if eval_gradient: + if not self.hyperparameter_noise_level.fixed: + return ( + K, + self.noise_level * np.eye(_num_samples(X))[:, :, np.newaxis], + ) + else: + return K, np.empty((_num_samples(X), _num_samples(X), 0)) + else: + return K + else: + return np.zeros((_num_samples(X), _num_samples(Y))) + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) or list of object + Argument to the kernel. + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + return np.full( + _num_samples(X), self.noise_level, dtype=np.array(self.noise_level).dtype + ) + + def __repr__(self): + return "{0}(noise_level={1:.3g})".format( + self.__class__.__name__, self.noise_level + ) + + +class RBF(StationaryKernelMixin, NormalizedKernelMixin, Kernel): + """Radial basis function kernel (aka squared-exponential kernel). + + The RBF kernel is a stationary kernel. It is also known as the + "squared exponential" kernel. It is parameterized by a length scale + parameter :math:`l>0`, which can either be a scalar (isotropic variant + of the kernel) or a vector with the same number of dimensions as the inputs + X (anisotropic variant of the kernel). The kernel is given by: + + .. math:: + k(x_i, x_j) = \\exp\\left(- \\frac{d(x_i, x_j)^2}{2l^2} \\right) + + where :math:`l` is the length scale of the kernel and + :math:`d(\\cdot,\\cdot)` is the Euclidean distance. + For advice on how to set the length scale parameter, see e.g. [1]_. + + This kernel is infinitely differentiable, which implies that GPs with this + kernel as covariance function have mean square derivatives of all orders, + and are thus very smooth. + See [2]_, Chapter 4, Section 4.2, for further details of the RBF kernel. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + length_scale : float or ndarray of shape (n_features,), default=1.0 + The length scale of the kernel. If a float, an isotropic kernel is + used. If an array, an anisotropic kernel is used where each dimension + of l defines the length-scale of the respective feature dimension. + + length_scale_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'length_scale'. + If set to "fixed", 'length_scale' cannot be changed during + hyperparameter tuning. + + References + ---------- + .. [1] `David Duvenaud (2014). "The Kernel Cookbook: + Advice on Covariance functions". + `_ + + .. [2] `Carl Edward Rasmussen, Christopher K. I. Williams (2006). + "Gaussian Processes for Machine Learning". The MIT Press. + `_ + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.gaussian_process import GaussianProcessClassifier + >>> from sklearn.gaussian_process.kernels import RBF + >>> X, y = load_iris(return_X_y=True) + >>> kernel = 1.0 * RBF(1.0) + >>> gpc = GaussianProcessClassifier(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpc.score(X, y) + 0.9866 + >>> gpc.predict_proba(X[:2,:]) + array([[0.8354, 0.03228, 0.1322], + [0.7906, 0.0652, 0.1441]]) + """ + + def __init__(self, length_scale=1.0, length_scale_bounds=(1e-5, 1e5)): + self.length_scale = length_scale + self.length_scale_bounds = length_scale_bounds + + @property + def anisotropic(self): + return np.iterable(self.length_scale) and len(self.length_scale) > 1 + + @property + def hyperparameter_length_scale(self): + if self.anisotropic: + return Hyperparameter( + "length_scale", + "numeric", + self.length_scale_bounds, + len(self.length_scale), + ) + return Hyperparameter("length_scale", "numeric", self.length_scale_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims), \ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + X = np.atleast_2d(X) + length_scale = _check_length_scale(X, self.length_scale) + if Y is None: + dists = pdist(X / length_scale, metric="sqeuclidean") + K = np.exp(-0.5 * dists) + # convert from upper-triangular matrix to square matrix + K = squareform(K) + np.fill_diagonal(K, 1) + else: + if eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + dists = cdist(X / length_scale, Y / length_scale, metric="sqeuclidean") + K = np.exp(-0.5 * dists) + + if eval_gradient: + if self.hyperparameter_length_scale.fixed: + # Hyperparameter l kept fixed + return K, np.empty((X.shape[0], X.shape[0], 0)) + elif not self.anisotropic or length_scale.shape[0] == 1: + K_gradient = (K * squareform(dists))[:, :, np.newaxis] + return K, K_gradient + elif self.anisotropic: + # We need to recompute the pairwise dimension-wise distances + K_gradient = (X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2 / ( + length_scale**2 + ) + K_gradient *= K[..., np.newaxis] + return K, K_gradient + else: + return K + + def __repr__(self): + if self.anisotropic: + return "{0}(length_scale=[{1}])".format( + self.__class__.__name__, + ", ".join(map("{0:.3g}".format, self.length_scale)), + ) + else: # isotropic + return "{0}(length_scale={1:.3g})".format( + self.__class__.__name__, np.ravel(self.length_scale)[0] + ) + + +class Matern(RBF): + """Matern kernel. + + The class of Matern kernels is a generalization of the :class:`RBF`. + It has an additional parameter :math:`\\nu` which controls the + smoothness of the resulting function. The smaller :math:`\\nu`, + the less smooth the approximated function is. + As :math:`\\nu\\rightarrow\\infty`, the kernel becomes equivalent to + the :class:`RBF` kernel. When :math:`\\nu = 1/2`, the Matérn kernel + becomes identical to the absolute exponential kernel. + Important intermediate values are + :math:`\\nu=1.5` (once differentiable functions) + and :math:`\\nu=2.5` (twice differentiable functions). + + The kernel is given by: + + .. math:: + k(x_i, x_j) = \\frac{1}{\\Gamma(\\nu)2^{\\nu-1}}\\Bigg( + \\frac{\\sqrt{2\\nu}}{l} d(x_i , x_j ) + \\Bigg)^\\nu K_\\nu\\Bigg( + \\frac{\\sqrt{2\\nu}}{l} d(x_i , x_j )\\Bigg) + + + + where :math:`d(\\cdot,\\cdot)` is the Euclidean distance, + :math:`K_{\\nu}(\\cdot)` is a modified Bessel function and + :math:`\\Gamma(\\cdot)` is the gamma function. + See [1]_, Chapter 4, Section 4.2, for details regarding the different + variants of the Matern kernel. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + length_scale : float or ndarray of shape (n_features,), default=1.0 + The length scale of the kernel. If a float, an isotropic kernel is + used. If an array, an anisotropic kernel is used where each dimension + of l defines the length-scale of the respective feature dimension. + + length_scale_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'length_scale'. + If set to "fixed", 'length_scale' cannot be changed during + hyperparameter tuning. + + nu : float, default=1.5 + The parameter nu controlling the smoothness of the learned function. + The smaller nu, the less smooth the approximated function is. + For nu=inf, the kernel becomes equivalent to the RBF kernel and for + nu=0.5 to the absolute exponential kernel. Important intermediate + values are nu=1.5 (once differentiable functions) and nu=2.5 + (twice differentiable functions). Note that values of nu not in + [0.5, 1.5, 2.5, inf] incur a considerably higher computational cost + (appr. 10 times higher) since they require to evaluate the modified + Bessel function. Furthermore, in contrast to l, nu is kept fixed to + its initial value and not optimized. + + References + ---------- + .. [1] `Carl Edward Rasmussen, Christopher K. I. Williams (2006). + "Gaussian Processes for Machine Learning". The MIT Press. + `_ + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.gaussian_process import GaussianProcessClassifier + >>> from sklearn.gaussian_process.kernels import Matern + >>> X, y = load_iris(return_X_y=True) + >>> kernel = 1.0 * Matern(length_scale=1.0, nu=1.5) + >>> gpc = GaussianProcessClassifier(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpc.score(X, y) + 0.9866 + >>> gpc.predict_proba(X[:2,:]) + array([[0.8513, 0.0368, 0.1117], + [0.8086, 0.0693, 0.1220]]) + """ + + def __init__(self, length_scale=1.0, length_scale_bounds=(1e-5, 1e5), nu=1.5): + super().__init__(length_scale, length_scale_bounds) + self.nu = nu + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims), \ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + X = np.atleast_2d(X) + length_scale = _check_length_scale(X, self.length_scale) + if Y is None: + dists = pdist(X / length_scale, metric="euclidean") + else: + if eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + dists = cdist(X / length_scale, Y / length_scale, metric="euclidean") + + if self.nu == 0.5: + K = np.exp(-dists) + elif self.nu == 1.5: + K = dists * math.sqrt(3) + K = (1.0 + K) * np.exp(-K) + elif self.nu == 2.5: + K = dists * math.sqrt(5) + K = (1.0 + K + K**2 / 3.0) * np.exp(-K) + elif self.nu == np.inf: + K = np.exp(-(dists**2) / 2.0) + else: # general case; expensive to evaluate + K = dists + K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan + tmp = math.sqrt(2 * self.nu) * K + K.fill((2 ** (1.0 - self.nu)) / gamma(self.nu)) + K *= tmp**self.nu + K *= kv(self.nu, tmp) + + if Y is None: + # convert from upper-triangular matrix to square matrix + K = squareform(K) + np.fill_diagonal(K, 1) + + if eval_gradient: + if self.hyperparameter_length_scale.fixed: + # Hyperparameter l kept fixed + K_gradient = np.empty((X.shape[0], X.shape[0], 0)) + return K, K_gradient + + # We need to recompute the pairwise dimension-wise distances + if self.anisotropic: + D = (X[:, np.newaxis, :] - X[np.newaxis, :, :]) ** 2 / (length_scale**2) + else: + D = squareform(dists**2)[:, :, np.newaxis] + + if self.nu == 0.5: + denominator = np.sqrt(D.sum(axis=2))[:, :, np.newaxis] + divide_result = np.zeros_like(D) + np.divide( + D, + denominator, + out=divide_result, + where=denominator != 0, + ) + K_gradient = K[..., np.newaxis] * divide_result + elif self.nu == 1.5: + K_gradient = 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis] + elif self.nu == 2.5: + tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis] + K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp) + elif self.nu == np.inf: + K_gradient = D * K[..., np.newaxis] + else: + # approximate gradient numerically + def f(theta): # helper function + return self.clone_with_theta(theta)(X, Y) + + return K, _approx_fprime(self.theta, f, 1e-10) + + if not self.anisotropic: + return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis] + else: + return K, K_gradient + else: + return K + + def __repr__(self): + if self.anisotropic: + return "{0}(length_scale=[{1}], nu={2:.3g})".format( + self.__class__.__name__, + ", ".join(map("{0:.3g}".format, self.length_scale)), + self.nu, + ) + else: + return "{0}(length_scale={1:.3g}, nu={2:.3g})".format( + self.__class__.__name__, np.ravel(self.length_scale)[0], self.nu + ) + + +class RationalQuadratic(StationaryKernelMixin, NormalizedKernelMixin, Kernel): + """Rational Quadratic kernel. + + The RationalQuadratic kernel can be seen as a scale mixture (an infinite + sum) of RBF kernels with different characteristic length scales. It is + parameterized by a length scale parameter :math:`l>0` and a scale + mixture parameter :math:`\\alpha>0`. Only the isotropic variant + where length_scale :math:`l` is a scalar is supported at the moment. + The kernel is given by: + + .. math:: + k(x_i, x_j) = \\left( + 1 + \\frac{d(x_i, x_j)^2 }{ 2\\alpha l^2}\\right)^{-\\alpha} + + where :math:`\\alpha` is the scale mixture parameter, :math:`l` is + the length scale of the kernel and :math:`d(\\cdot,\\cdot)` is the + Euclidean distance. + For advice on how to set the parameters, see e.g. [1]_. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + length_scale : float > 0, default=1.0 + The length scale of the kernel. + + alpha : float > 0, default=1.0 + Scale mixture parameter + + length_scale_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'length_scale'. + If set to "fixed", 'length_scale' cannot be changed during + hyperparameter tuning. + + alpha_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'alpha'. + If set to "fixed", 'alpha' cannot be changed during + hyperparameter tuning. + + References + ---------- + .. [1] `David Duvenaud (2014). "The Kernel Cookbook: + Advice on Covariance functions". + `_ + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.gaussian_process import GaussianProcessClassifier + >>> from sklearn.gaussian_process.kernels import RationalQuadratic + >>> X, y = load_iris(return_X_y=True) + >>> kernel = RationalQuadratic(length_scale=1.0, alpha=1.5) + >>> gpc = GaussianProcessClassifier(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpc.score(X, y) + 0.9733 + >>> gpc.predict_proba(X[:2,:]) + array([[0.8881, 0.0566, 0.05518], + [0.8678, 0.0707 , 0.0614]]) + """ + + def __init__( + self, + length_scale=1.0, + alpha=1.0, + length_scale_bounds=(1e-5, 1e5), + alpha_bounds=(1e-5, 1e5), + ): + self.length_scale = length_scale + self.alpha = alpha + self.length_scale_bounds = length_scale_bounds + self.alpha_bounds = alpha_bounds + + @property + def hyperparameter_length_scale(self): + return Hyperparameter("length_scale", "numeric", self.length_scale_bounds) + + @property + def hyperparameter_alpha(self): + return Hyperparameter("alpha", "numeric", self.alpha_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims) + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when eval_gradient + is True. + """ + if len(np.atleast_1d(self.length_scale)) > 1: + raise AttributeError( + "RationalQuadratic kernel only supports isotropic version, " + "please use a single scalar for length_scale" + ) + X = np.atleast_2d(X) + if Y is None: + dists = squareform(pdist(X, metric="sqeuclidean")) + tmp = dists / (2 * self.alpha * self.length_scale**2) + base = 1 + tmp + K = base**-self.alpha + np.fill_diagonal(K, 1) + else: + if eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + dists = cdist(X, Y, metric="sqeuclidean") + K = (1 + dists / (2 * self.alpha * self.length_scale**2)) ** -self.alpha + + if eval_gradient: + # gradient with respect to length_scale + if not self.hyperparameter_length_scale.fixed: + length_scale_gradient = dists * K / (self.length_scale**2 * base) + length_scale_gradient = length_scale_gradient[:, :, np.newaxis] + else: # l is kept fixed + length_scale_gradient = np.empty((K.shape[0], K.shape[1], 0)) + + # gradient with respect to alpha + if not self.hyperparameter_alpha.fixed: + alpha_gradient = K * ( + -self.alpha * np.log(base) + + dists / (2 * self.length_scale**2 * base) + ) + alpha_gradient = alpha_gradient[:, :, np.newaxis] + else: # alpha is kept fixed + alpha_gradient = np.empty((K.shape[0], K.shape[1], 0)) + + return K, np.dstack((alpha_gradient, length_scale_gradient)) + else: + return K + + def __repr__(self): + return "{0}(alpha={1:.3g}, length_scale={2:.3g})".format( + self.__class__.__name__, self.alpha, self.length_scale + ) + + +class ExpSineSquared(StationaryKernelMixin, NormalizedKernelMixin, Kernel): + r"""Exp-Sine-Squared kernel (aka periodic kernel). + + The ExpSineSquared kernel allows one to model functions which repeat + themselves exactly. It is parameterized by a length scale + parameter :math:`l>0` and a periodicity parameter :math:`p>0`. + Only the isotropic variant where :math:`l` is a scalar is + supported at the moment. The kernel is given by: + + .. math:: + k(x_i, x_j) = \text{exp}\left(- + \frac{ 2\sin^2(\pi d(x_i, x_j)/p) }{ l^ 2} \right) + + where :math:`l` is the length scale of the kernel, :math:`p` the + periodicity of the kernel and :math:`d(\cdot,\cdot)` is the + Euclidean distance. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + + length_scale : float > 0, default=1.0 + The length scale of the kernel. + + periodicity : float > 0, default=1.0 + The periodicity of the kernel. + + length_scale_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'length_scale'. + If set to "fixed", 'length_scale' cannot be changed during + hyperparameter tuning. + + periodicity_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'periodicity'. + If set to "fixed", 'periodicity' cannot be changed during + hyperparameter tuning. + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import ExpSineSquared + >>> X, y = make_friedman2(n_samples=50, noise=0, random_state=0) + >>> kernel = ExpSineSquared(length_scale=1, periodicity=1) + >>> gpr = GaussianProcessRegressor(kernel=kernel, alpha=5, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.0144 + >>> gpr.predict(X[:2,:], return_std=True) + (array([425.6, 457.5]), array([0.3894, 0.3467])) + """ + + def __init__( + self, + length_scale=1.0, + periodicity=1.0, + length_scale_bounds=(1e-5, 1e5), + periodicity_bounds=(1e-5, 1e5), + ): + self.length_scale = length_scale + self.periodicity = periodicity + self.length_scale_bounds = length_scale_bounds + self.periodicity_bounds = periodicity_bounds + + @property + def hyperparameter_length_scale(self): + """Returns the length scale""" + return Hyperparameter("length_scale", "numeric", self.length_scale_bounds) + + @property + def hyperparameter_periodicity(self): + return Hyperparameter("periodicity", "numeric", self.periodicity_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims), \ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + X = np.atleast_2d(X) + if Y is None: + dists = squareform(pdist(X, metric="euclidean")) + arg = np.pi * dists / self.periodicity + sin_of_arg = np.sin(arg) + K = np.exp(-2 * (sin_of_arg / self.length_scale) ** 2) + else: + if eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + dists = cdist(X, Y, metric="euclidean") + K = np.exp( + -2 * (np.sin(np.pi / self.periodicity * dists) / self.length_scale) ** 2 + ) + + if eval_gradient: + cos_of_arg = np.cos(arg) + # gradient with respect to length_scale + if not self.hyperparameter_length_scale.fixed: + length_scale_gradient = 4 / self.length_scale**2 * sin_of_arg**2 * K + length_scale_gradient = length_scale_gradient[:, :, np.newaxis] + else: # length_scale is kept fixed + length_scale_gradient = np.empty((K.shape[0], K.shape[1], 0)) + # gradient with respect to p + if not self.hyperparameter_periodicity.fixed: + periodicity_gradient = ( + 4 * arg / self.length_scale**2 * cos_of_arg * sin_of_arg * K + ) + periodicity_gradient = periodicity_gradient[:, :, np.newaxis] + else: # p is kept fixed + periodicity_gradient = np.empty((K.shape[0], K.shape[1], 0)) + + return K, np.dstack((length_scale_gradient, periodicity_gradient)) + else: + return K + + def __repr__(self): + return "{0}(length_scale={1:.3g}, periodicity={2:.3g})".format( + self.__class__.__name__, self.length_scale, self.periodicity + ) + + +class DotProduct(Kernel): + r"""Dot-Product kernel. + + The DotProduct kernel is non-stationary and can be obtained from linear + regression by putting :math:`N(0, 1)` priors on the coefficients + of :math:`x_d (d = 1, . . . , D)` and a prior of :math:`N(0, \sigma_0^2)` + on the bias. The DotProduct kernel is invariant to a rotation of + the coordinates about the origin, but not translations. + It is parameterized by a parameter sigma_0 :math:`\sigma` + which controls the inhomogenity of the kernel. For :math:`\sigma_0^2 =0`, + the kernel is called the homogeneous linear kernel, otherwise + it is inhomogeneous. The kernel is given by + + .. math:: + k(x_i, x_j) = \sigma_0 ^ 2 + x_i \cdot x_j + + The DotProduct kernel is commonly combined with exponentiation. + + See [1]_, Chapter 4, Section 4.2, for further details regarding the + DotProduct kernel. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + sigma_0 : float >= 0, default=1.0 + Parameter controlling the inhomogenity of the kernel. If sigma_0=0, + the kernel is homogeneous. + + sigma_0_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'sigma_0'. + If set to "fixed", 'sigma_0' cannot be changed during + hyperparameter tuning. + + References + ---------- + .. [1] `Carl Edward Rasmussen, Christopher K. I. Williams (2006). + "Gaussian Processes for Machine Learning". The MIT Press. + `_ + + Examples + -------- + >>> from sklearn.datasets import make_friedman2 + >>> from sklearn.gaussian_process import GaussianProcessRegressor + >>> from sklearn.gaussian_process.kernels import DotProduct, WhiteKernel + >>> X, y = make_friedman2(n_samples=500, noise=0, random_state=0) + >>> kernel = DotProduct() + WhiteKernel() + >>> gpr = GaussianProcessRegressor(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpr.score(X, y) + 0.3680 + >>> gpr.predict(X[:2,:], return_std=True) + (array([653.0, 592.1]), array([316.6, 316.6])) + """ + + def __init__(self, sigma_0=1.0, sigma_0_bounds=(1e-5, 1e5)): + self.sigma_0 = sigma_0 + self.sigma_0_bounds = sigma_0_bounds + + @property + def hyperparameter_sigma_0(self): + return Hyperparameter("sigma_0", "numeric", self.sigma_0_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims),\ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + X = np.atleast_2d(X) + if Y is None: + K = np.inner(X, X) + self.sigma_0**2 + else: + if eval_gradient: + raise ValueError("Gradient can only be evaluated when Y is None.") + K = np.inner(X, Y) + self.sigma_0**2 + + if eval_gradient: + if not self.hyperparameter_sigma_0.fixed: + K_gradient = np.empty((K.shape[0], K.shape[1], 1)) + K_gradient[..., 0] = 2 * self.sigma_0**2 + return K, K_gradient + else: + return K, np.empty((X.shape[0], X.shape[0], 0)) + else: + return K + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y). + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X). + """ + return np.einsum("ij,ij->i", X, X) + self.sigma_0**2 + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return False + + def __repr__(self): + return "{0}(sigma_0={1:.3g})".format(self.__class__.__name__, self.sigma_0) + + +# adapted from scipy/optimize/optimize.py for functions with 2d output +def _approx_fprime(xk, f, epsilon, args=()): + f0 = f(*((xk,) + args)) + grad = np.zeros((f0.shape[0], f0.shape[1], len(xk)), float) + ei = np.zeros((len(xk),), float) + for k in range(len(xk)): + ei[k] = 1.0 + d = epsilon * ei + grad[:, :, k] = (f(*((xk + d,) + args)) - f0) / d[k] + ei[k] = 0.0 + return grad + + +class PairwiseKernel(Kernel): + """Wrapper for kernels in sklearn.metrics.pairwise. + + A thin wrapper around the functionality of the kernels in + sklearn.metrics.pairwise. + + Note: Evaluation of eval_gradient is not analytic but numeric and all + kernels support only isotropic distances. The parameter gamma is + considered to be a hyperparameter and may be optimized. The other + kernel parameters are set directly at initialization and are kept + fixed. + + .. versionadded:: 0.18 + + Parameters + ---------- + gamma : float, default=1.0 + Parameter gamma of the pairwise kernel specified by metric. It should + be positive. + + gamma_bounds : pair of floats >= 0 or "fixed", default=(1e-5, 1e5) + The lower and upper bound on 'gamma'. + If set to "fixed", 'gamma' cannot be changed during + hyperparameter tuning. + + metric : {"linear", "additive_chi2", "chi2", "poly", "polynomial", \ + "rbf", "laplacian", "sigmoid", "cosine"} or callable, \ + default="linear" + The metric to use when calculating kernel between instances in a + feature array. If metric is a string, it must be one of the metrics + in pairwise.PAIRWISE_KERNEL_FUNCTIONS. + If metric is "precomputed", X is assumed to be a kernel matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. + + pairwise_kernels_kwargs : dict, default=None + All entries of this dict (if any) are passed as keyword arguments to + the pairwise kernel function. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.gaussian_process import GaussianProcessClassifier + >>> from sklearn.gaussian_process.kernels import PairwiseKernel + >>> X, y = load_iris(return_X_y=True) + >>> kernel = PairwiseKernel(metric='rbf') + >>> gpc = GaussianProcessClassifier(kernel=kernel, + ... random_state=0).fit(X, y) + >>> gpc.score(X, y) + 0.9733 + >>> gpc.predict_proba(X[:2,:]) + array([[0.8880, 0.05663, 0.05532], + [0.8676, 0.07073, 0.06165]]) + """ + + def __init__( + self, + gamma=1.0, + gamma_bounds=(1e-5, 1e5), + metric="linear", + pairwise_kernels_kwargs=None, + ): + self.gamma = gamma + self.gamma_bounds = gamma_bounds + self.metric = metric + self.pairwise_kernels_kwargs = pairwise_kernels_kwargs + + @property + def hyperparameter_gamma(self): + return Hyperparameter("gamma", "numeric", self.gamma_bounds) + + def __call__(self, X, Y=None, eval_gradient=False): + """Return the kernel k(X, Y) and optionally its gradient. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Y : ndarray of shape (n_samples_Y, n_features), default=None + Right argument of the returned kernel k(X, Y). If None, k(X, X) + if evaluated instead. + + eval_gradient : bool, default=False + Determines whether the gradient with respect to the log of + the kernel hyperparameter is computed. + Only supported when Y is None. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_Y) + Kernel k(X, Y) + + K_gradient : ndarray of shape (n_samples_X, n_samples_X, n_dims),\ + optional + The gradient of the kernel k(X, X) with respect to the log of the + hyperparameter of the kernel. Only returned when `eval_gradient` + is True. + """ + pairwise_kernels_kwargs = self.pairwise_kernels_kwargs + if self.pairwise_kernels_kwargs is None: + pairwise_kernels_kwargs = {} + + X = np.atleast_2d(X) + K = pairwise_kernels( + X, + Y, + metric=self.metric, + gamma=self.gamma, + filter_params=True, + **pairwise_kernels_kwargs, + ) + if eval_gradient: + if self.hyperparameter_gamma.fixed: + return K, np.empty((X.shape[0], X.shape[0], 0)) + else: + # approximate gradient numerically + def f(gamma): # helper function + return pairwise_kernels( + X, + Y, + metric=self.metric, + gamma=np.exp(gamma), + filter_params=True, + **pairwise_kernels_kwargs, + ) + + return K, _approx_fprime(self.theta, f, 1e-10) + else: + return K + + def diag(self, X): + """Returns the diagonal of the kernel k(X, X). + + The result of this method is identical to np.diag(self(X)); however, + it can be evaluated more efficiently since only the diagonal is + evaluated. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + Left argument of the returned kernel k(X, Y) + + Returns + ------- + K_diag : ndarray of shape (n_samples_X,) + Diagonal of kernel k(X, X) + """ + # We have to fall back to slow way of computing diagonal + return np.apply_along_axis(self, 1, X).ravel() + + def is_stationary(self): + """Returns whether the kernel is stationary.""" + return self.metric in ["rbf"] + + def __repr__(self): + return "{0}(gamma={1}, metric={2})".format( + self.__class__.__name__, self.gamma, self.metric + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/_mini_sequence_kernel.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/_mini_sequence_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..4667329aff9b8dbeffa90bb0c40c98a708fcc205 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/_mini_sequence_kernel.py @@ -0,0 +1,54 @@ +import numpy as np + +from sklearn.base import clone +from sklearn.gaussian_process.kernels import ( + GenericKernelMixin, + Hyperparameter, + Kernel, + StationaryKernelMixin, +) + + +class MiniSeqKernel(GenericKernelMixin, StationaryKernelMixin, Kernel): + """ + A minimal (but valid) convolutional kernel for sequences of variable + length. + """ + + def __init__(self, baseline_similarity=0.5, baseline_similarity_bounds=(1e-5, 1)): + self.baseline_similarity = baseline_similarity + self.baseline_similarity_bounds = baseline_similarity_bounds + + @property + def hyperparameter_baseline_similarity(self): + return Hyperparameter( + "baseline_similarity", "numeric", self.baseline_similarity_bounds + ) + + def _f(self, s1, s2): + return sum( + [1.0 if c1 == c2 else self.baseline_similarity for c1 in s1 for c2 in s2] + ) + + def _g(self, s1, s2): + return sum([0.0 if c1 == c2 else 1.0 for c1 in s1 for c2 in s2]) + + def __call__(self, X, Y=None, eval_gradient=False): + if Y is None: + Y = X + + if eval_gradient: + return ( + np.array([[self._f(x, y) for y in Y] for x in X]), + np.array([[[self._g(x, y)] for y in Y] for x in X]), + ) + else: + return np.array([[self._f(x, y) for y in Y] for x in X]) + + def diag(self, X): + return np.array([self._f(x, x) for x in X]) + + def clone_with_theta(self, theta): + cloned = clone(self) + cloned.theta = theta + return cloned diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpc.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpc.py new file mode 100644 index 0000000000000000000000000000000000000000..365b8f5a114417fdd2ab9979341ba95489c2b1d2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpc.py @@ -0,0 +1,320 @@ +"""Testing for Gaussian process classification""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np +import pytest +from scipy.optimize import approx_fprime + +from sklearn.exceptions import ConvergenceWarning +from sklearn.gaussian_process import GaussianProcessClassifier +from sklearn.gaussian_process.kernels import ( + RBF, + CompoundKernel, + WhiteKernel, +) +from sklearn.gaussian_process.kernels import ( + ConstantKernel as C, +) +from sklearn.gaussian_process.tests._mini_sequence_kernel import MiniSeqKernel +from sklearn.utils._testing import assert_almost_equal, assert_array_equal + + +def f(x): + return np.sin(x) + + +X = np.atleast_2d(np.linspace(0, 10, 30)).T +X2 = np.atleast_2d([2.0, 4.0, 5.5, 6.5, 7.5]).T +y = np.array(f(X).ravel() > 0, dtype=int) +fX = f(X).ravel() +y_mc = np.empty(y.shape, dtype=int) # multi-class +y_mc[fX < -0.35] = 0 +y_mc[(fX >= -0.35) & (fX < 0.35)] = 1 +y_mc[fX > 0.35] = 2 + + +fixed_kernel = RBF(length_scale=1.0, length_scale_bounds="fixed") +kernels = [ + RBF(length_scale=0.1), + fixed_kernel, + RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)), + C(1.0, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)), +] +non_fixed_kernels = [kernel for kernel in kernels if kernel != fixed_kernel] + + +@pytest.mark.parametrize("kernel", kernels) +def test_predict_consistent(kernel): + # Check binary predict decision has also predicted probability above 0.5. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + assert_array_equal(gpc.predict(X), gpc.predict_proba(X)[:, 1] >= 0.5) + + +def test_predict_consistent_structured(): + # Check binary predict decision has also predicted probability above 0.5. + X = ["A", "AB", "B"] + y = np.array([True, False, True]) + kernel = MiniSeqKernel(baseline_similarity_bounds="fixed") + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + assert_array_equal(gpc.predict(X), gpc.predict_proba(X)[:, 1] >= 0.5) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_lml_improving(kernel): + # Test that hyperparameter-tuning improves log-marginal likelihood. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + assert gpc.log_marginal_likelihood(gpc.kernel_.theta) > gpc.log_marginal_likelihood( + kernel.theta + ) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_precomputed(kernel): + # Test that lml of optimized kernel is stored correctly. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + assert_almost_equal( + gpc.log_marginal_likelihood(gpc.kernel_.theta), gpc.log_marginal_likelihood(), 7 + ) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_without_cloning_kernel(kernel): + # Test that clone_kernel=False has side-effects of kernel.theta. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + input_theta = np.ones(gpc.kernel_.theta.shape, dtype=np.float64) + + gpc.log_marginal_likelihood(input_theta, clone_kernel=False) + assert_almost_equal(gpc.kernel_.theta, input_theta, 7) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_converged_to_local_maximum(kernel): + # Test that we are in local maximum after hyperparameter-optimization. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + + lml, lml_gradient = gpc.log_marginal_likelihood(gpc.kernel_.theta, True) + + assert np.all( + (np.abs(lml_gradient) < 1e-4) + | (gpc.kernel_.theta == gpc.kernel_.bounds[:, 0]) + | (gpc.kernel_.theta == gpc.kernel_.bounds[:, 1]) + ) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_gradient(kernel): + # Compare analytic and numeric gradient of log marginal likelihood. + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + + lml, lml_gradient = gpc.log_marginal_likelihood(kernel.theta, True) + lml_gradient_approx = approx_fprime( + kernel.theta, lambda theta: gpc.log_marginal_likelihood(theta, False), 1e-10 + ) + + assert_almost_equal(lml_gradient, lml_gradient_approx, 3) + + +def test_random_starts(global_random_seed): + # Test that an increasing number of random-starts of GP fitting only + # increases the log marginal likelihood of the chosen theta. + n_samples, n_features = 25, 2 + rng = np.random.RandomState(global_random_seed) + X = rng.randn(n_samples, n_features) * 2 - 1 + y = (np.sin(X).sum(axis=1) + np.sin(3 * X).sum(axis=1)) > 0 + + kernel = C(1.0, (1e-2, 1e2)) * RBF( + length_scale=[1e-3] * n_features, length_scale_bounds=[(1e-4, 1e2)] * n_features + ) + last_lml = -np.inf + for n_restarts_optimizer in range(5): + gp = GaussianProcessClassifier( + kernel=kernel, + n_restarts_optimizer=n_restarts_optimizer, + random_state=global_random_seed, + ).fit(X, y) + lml = gp.log_marginal_likelihood(gp.kernel_.theta) + assert lml > last_lml - np.finfo(np.float32).eps + last_lml = lml + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_custom_optimizer(kernel, global_random_seed): + # Test that GPC can use externally defined optimizers. + # Define a dummy optimizer that simply tests 10 random hyperparameters + def optimizer(obj_func, initial_theta, bounds): + rng = np.random.RandomState(global_random_seed) + theta_opt, func_min = ( + initial_theta, + obj_func(initial_theta, eval_gradient=False), + ) + for _ in range(10): + theta = np.atleast_1d( + rng.uniform(np.maximum(-2, bounds[:, 0]), np.minimum(1, bounds[:, 1])) + ) + f = obj_func(theta, eval_gradient=False) + if f < func_min: + theta_opt, func_min = theta, f + return theta_opt, func_min + + gpc = GaussianProcessClassifier(kernel=kernel, optimizer=optimizer) + gpc.fit(X, y_mc) + # Checks that optimizer improved marginal likelihood + assert gpc.log_marginal_likelihood( + gpc.kernel_.theta + ) >= gpc.log_marginal_likelihood(kernel.theta) + + +@pytest.mark.parametrize("kernel", kernels) +def test_multi_class(kernel): + # Test GPC for multi-class classification problems. + gpc = GaussianProcessClassifier(kernel=kernel) + gpc.fit(X, y_mc) + + y_prob = gpc.predict_proba(X2) + assert_almost_equal(y_prob.sum(1), 1) + + y_pred = gpc.predict(X2) + assert_array_equal(np.argmax(y_prob, 1), y_pred) + + +@pytest.mark.parametrize("kernel", kernels) +def test_multi_class_n_jobs(kernel): + # Test that multi-class GPC produces identical results with n_jobs>1. + gpc = GaussianProcessClassifier(kernel=kernel) + gpc.fit(X, y_mc) + + gpc_2 = GaussianProcessClassifier(kernel=kernel, n_jobs=2) + gpc_2.fit(X, y_mc) + + y_prob = gpc.predict_proba(X2) + y_prob_2 = gpc_2.predict_proba(X2) + assert_almost_equal(y_prob, y_prob_2) + + +def test_warning_bounds(): + kernel = RBF(length_scale_bounds=[1e-5, 1e-3]) + gpc = GaussianProcessClassifier(kernel=kernel) + warning_message = ( + "The optimal value found for dimension 0 of parameter " + "length_scale is close to the specified upper bound " + "0.001. Increasing the bound and calling fit again may " + "find a better value." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + gpc.fit(X, y) + + kernel_sum = WhiteKernel(noise_level_bounds=[1e-5, 1e-3]) + RBF( + length_scale_bounds=[1e3, 1e5] + ) + gpc_sum = GaussianProcessClassifier(kernel=kernel_sum) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + gpc_sum.fit(X, y) + + assert len(record) == 2 + + assert issubclass(record[0].category, ConvergenceWarning) + assert ( + record[0].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "k1__noise_level is close to the " + "specified upper bound 0.001. " + "Increasing the bound and calling " + "fit again may find a better value." + ) + + assert issubclass(record[1].category, ConvergenceWarning) + assert ( + record[1].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "k2__length_scale is close to the " + "specified lower bound 1000.0. " + "Decreasing the bound and calling " + "fit again may find a better value." + ) + + X_tile = np.tile(X, 2) + kernel_dims = RBF(length_scale=[1.0, 2.0], length_scale_bounds=[1e1, 1e2]) + gpc_dims = GaussianProcessClassifier(kernel=kernel_dims) + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + gpc_dims.fit(X_tile, y) + + assert len(record) == 2 + + assert issubclass(record[0].category, ConvergenceWarning) + assert ( + record[0].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "length_scale is close to the " + "specified upper bound 100.0. " + "Increasing the bound and calling " + "fit again may find a better value." + ) + + assert issubclass(record[1].category, ConvergenceWarning) + assert ( + record[1].message.args[0] == "The optimal value found for " + "dimension 1 of parameter " + "length_scale is close to the " + "specified upper bound 100.0. " + "Increasing the bound and calling " + "fit again may find a better value." + ) + + +@pytest.mark.parametrize( + "params, error_type, err_msg", + [ + ( + {"kernel": CompoundKernel(0)}, + ValueError, + "kernel cannot be a CompoundKernel", + ) + ], +) +def test_gpc_fit_error(params, error_type, err_msg): + """Check that expected error are raised during fit.""" + gpc = GaussianProcessClassifier(**params) + with pytest.raises(error_type, match=err_msg): + gpc.fit(X, y) + + +@pytest.mark.parametrize("kernel", kernels) +def test_gpc_latent_mean_and_variance_shape(kernel): + """Checks that the latent mean and variance have the right shape.""" + gpc = GaussianProcessClassifier(kernel=kernel) + gpc.fit(X, y) + + # Check that the latent mean and variance have the right shape + latent_mean, latent_variance = gpc.latent_mean_and_variance(X) + assert latent_mean.shape == (X.shape[0],) + assert latent_variance.shape == (X.shape[0],) + + +def test_gpc_latent_mean_and_variance_complain_on_more_than_2_classes(): + """Checks that the latent mean and variance have the right shape.""" + gpc = GaussianProcessClassifier(kernel=RBF()) + gpc.fit(X, y_mc) + + # Check that the latent mean and variance have the right shape + with pytest.raises( + ValueError, + match="Returning the mean and variance of the latent function f " + "is only supported for binary classification", + ): + gpc.latent_mean_and_variance(X) + + +def test_latent_mean_and_variance_works_on_structured_kernels(): + X = ["A", "AB", "B"] + y = np.array([True, False, True]) + kernel = MiniSeqKernel(baseline_similarity_bounds="fixed") + gpc = GaussianProcessClassifier(kernel=kernel).fit(X, y) + + gpc.latent_mean_and_variance(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpr.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpr.py new file mode 100644 index 0000000000000000000000000000000000000000..f43cc3613b3ff7669aba9b73526fd774bfd8452e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_gpr.py @@ -0,0 +1,849 @@ +"""Testing for Gaussian process regression""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import re +import sys +import warnings + +import numpy as np +import pytest +from scipy.optimize import approx_fprime + +from sklearn.exceptions import ConvergenceWarning +from sklearn.gaussian_process import GaussianProcessRegressor +from sklearn.gaussian_process.kernels import ( + RBF, + DotProduct, + ExpSineSquared, + WhiteKernel, +) +from sklearn.gaussian_process.kernels import ( + ConstantKernel as C, +) +from sklearn.gaussian_process.tests._mini_sequence_kernel import MiniSeqKernel +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_less, +) + + +def f(x): + return x * np.sin(x) + + +X = np.atleast_2d([1.0, 3.0, 5.0, 6.0, 7.0, 8.0]).T +X2 = np.atleast_2d([2.0, 4.0, 5.5, 6.5, 7.5]).T +y = f(X).ravel() + +fixed_kernel = RBF(length_scale=1.0, length_scale_bounds="fixed") +kernels = [ + RBF(length_scale=1.0), + fixed_kernel, + RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)), + C(1.0, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)), + C(1.0, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)) + + C(1e-5, (1e-5, 1e2)), + C(0.1, (1e-2, 1e2)) * RBF(length_scale=1.0, length_scale_bounds=(1e-3, 1e3)) + + C(1e-5, (1e-5, 1e2)), +] +non_fixed_kernels = [kernel for kernel in kernels if kernel != fixed_kernel] + + +@pytest.mark.parametrize("kernel", kernels) +def test_gpr_interpolation(kernel): + if sys.maxsize <= 2**32: + pytest.xfail("This test may fail on 32 bit Python") + + # Test the interpolating property for different kernels. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + y_pred, y_cov = gpr.predict(X, return_cov=True) + + assert_almost_equal(y_pred, y) + assert_almost_equal(np.diag(y_cov), 0.0) + + +def test_gpr_interpolation_structured(): + # Test the interpolating property for different kernels. + kernel = MiniSeqKernel(baseline_similarity_bounds="fixed") + X = ["A", "B", "C"] + y = np.array([1, 2, 3]) + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + y_pred, y_cov = gpr.predict(X, return_cov=True) + + assert_almost_equal( + kernel(X, eval_gradient=True)[1].ravel(), (1 - np.eye(len(X))).ravel() + ) + assert_almost_equal(y_pred, y) + assert_almost_equal(np.diag(y_cov), 0.0) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_lml_improving(kernel): + if sys.maxsize <= 2**32: + pytest.xfail("This test may fail on 32 bit Python") + + # Test that hyperparameter-tuning improves log-marginal likelihood. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + assert gpr.log_marginal_likelihood(gpr.kernel_.theta) > gpr.log_marginal_likelihood( + kernel.theta + ) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_precomputed(kernel): + # Test that lml of optimized kernel is stored correctly. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + assert gpr.log_marginal_likelihood(gpr.kernel_.theta) == pytest.approx( + gpr.log_marginal_likelihood() + ) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_without_cloning_kernel(kernel): + # Test that lml of optimized kernel is stored correctly. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + input_theta = np.ones(gpr.kernel_.theta.shape, dtype=np.float64) + + gpr.log_marginal_likelihood(input_theta, clone_kernel=False) + assert_almost_equal(gpr.kernel_.theta, input_theta, 7) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_converged_to_local_maximum(kernel): + # Test that we are in local maximum after hyperparameter-optimization. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + + lml, lml_gradient = gpr.log_marginal_likelihood(gpr.kernel_.theta, True) + + assert np.all( + (np.abs(lml_gradient) < 1e-4) + | (gpr.kernel_.theta == gpr.kernel_.bounds[:, 0]) + | (gpr.kernel_.theta == gpr.kernel_.bounds[:, 1]) + ) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_solution_inside_bounds(kernel): + # Test that hyperparameter-optimization remains in bounds# + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + + bounds = gpr.kernel_.bounds + max_ = np.finfo(gpr.kernel_.theta.dtype).max + tiny = 1e-10 + bounds[~np.isfinite(bounds[:, 1]), 1] = max_ + + assert_array_less(bounds[:, 0], gpr.kernel_.theta + tiny) + assert_array_less(gpr.kernel_.theta, bounds[:, 1] + tiny) + + +@pytest.mark.parametrize("kernel", kernels) +def test_lml_gradient(kernel): + # Compare analytic and numeric gradient of log marginal likelihood. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + + lml, lml_gradient = gpr.log_marginal_likelihood(kernel.theta, True) + lml_gradient_approx = approx_fprime( + kernel.theta, lambda theta: gpr.log_marginal_likelihood(theta, False), 1e-10 + ) + + assert_almost_equal(lml_gradient, lml_gradient_approx, 3) + + +@pytest.mark.parametrize("kernel", kernels) +def test_prior(kernel): + # Test that GP prior has mean 0 and identical variances. + gpr = GaussianProcessRegressor(kernel=kernel) + + y_mean, y_cov = gpr.predict(X, return_cov=True) + + assert_almost_equal(y_mean, 0, 5) + if len(gpr.kernel.theta) > 1: + # XXX: quite hacky, works only for current kernels + assert_almost_equal(np.diag(y_cov), np.exp(kernel.theta[0]), 5) + else: + assert_almost_equal(np.diag(y_cov), 1, 5) + + +@pytest.mark.parametrize("kernel", kernels) +def test_sample_statistics(kernel): + # Test that statistics of samples drawn from GP are correct. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + + y_mean, y_cov = gpr.predict(X2, return_cov=True) + + samples = gpr.sample_y(X2, 300000) + + # More digits accuracy would require many more samples + assert_almost_equal(y_mean, np.mean(samples, 1), 1) + assert_almost_equal( + np.diag(y_cov) / np.diag(y_cov).max(), + np.var(samples, 1) / np.diag(y_cov).max(), + 1, + ) + + +def test_no_optimizer(): + # Test that kernel parameters are unmodified when optimizer is None. + kernel = RBF(1.0) + gpr = GaussianProcessRegressor(kernel=kernel, optimizer=None).fit(X, y) + assert np.exp(gpr.kernel_.theta) == 1.0 + + +@pytest.mark.parametrize("kernel", kernels) +@pytest.mark.parametrize("target", [y, np.ones(X.shape[0], dtype=np.float64)]) +def test_predict_cov_vs_std(kernel, target): + if sys.maxsize <= 2**32: + pytest.xfail("This test may fail on 32 bit Python") + + # Test that predicted std.-dev. is consistent with cov's diagonal. + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + y_mean, y_cov = gpr.predict(X2, return_cov=True) + y_mean, y_std = gpr.predict(X2, return_std=True) + assert_almost_equal(np.sqrt(np.diag(y_cov)), y_std) + + +def test_anisotropic_kernel(): + # Test that GPR can identify meaningful anisotropic length-scales. + # We learn a function which varies in one dimension ten-times slower + # than in the other. The corresponding length-scales should differ by at + # least a factor 5 + rng = np.random.RandomState(0) + X = rng.uniform(-1, 1, (50, 2)) + y = X[:, 0] + 0.1 * X[:, 1] + + kernel = RBF([1.0, 1.0]) + gpr = GaussianProcessRegressor(kernel=kernel).fit(X, y) + assert np.exp(gpr.kernel_.theta[1]) > np.exp(gpr.kernel_.theta[0]) * 5 + + +def test_random_starts(): + # Test that an increasing number of random-starts of GP fitting only + # increases the log marginal likelihood of the chosen theta. + n_samples, n_features = 25, 2 + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) * 2 - 1 + y = ( + np.sin(X).sum(axis=1) + + np.sin(3 * X).sum(axis=1) + + rng.normal(scale=0.1, size=n_samples) + ) + + kernel = C(1.0, (1e-2, 1e2)) * RBF( + length_scale=[1.0] * n_features, length_scale_bounds=[(1e-4, 1e2)] * n_features + ) + WhiteKernel(noise_level=1e-5, noise_level_bounds=(1e-5, 1e1)) + last_lml = -np.inf + for n_restarts_optimizer in range(5): + gp = GaussianProcessRegressor( + kernel=kernel, + n_restarts_optimizer=n_restarts_optimizer, + random_state=0, + ).fit(X, y) + lml = gp.log_marginal_likelihood(gp.kernel_.theta) + assert lml > last_lml - np.finfo(np.float32).eps + last_lml = lml + + +@pytest.mark.parametrize("kernel", kernels) +def test_y_normalization(kernel): + """ + Test normalization of the target values in GP + + Fitting non-normalizing GP on normalized y and fitting normalizing GP + on unnormalized y should yield identical results. Note that, here, + 'normalized y' refers to y that has been made zero mean and unit + variance. + + """ + + y_mean = np.mean(y) + y_std = np.std(y) + y_norm = (y - y_mean) / y_std + + # Fit non-normalizing GP on normalized y + gpr = GaussianProcessRegressor(kernel=kernel) + gpr.fit(X, y_norm) + + # Fit normalizing GP on unnormalized y + gpr_norm = GaussianProcessRegressor(kernel=kernel, normalize_y=True) + gpr_norm.fit(X, y) + + # Compare predicted mean, std-devs and covariances + y_pred, y_pred_std = gpr.predict(X2, return_std=True) + y_pred = y_pred * y_std + y_mean + y_pred_std = y_pred_std * y_std + y_pred_norm, y_pred_std_norm = gpr_norm.predict(X2, return_std=True) + + assert_almost_equal(y_pred, y_pred_norm) + assert_almost_equal(y_pred_std, y_pred_std_norm) + + _, y_cov = gpr.predict(X2, return_cov=True) + y_cov = y_cov * y_std**2 + _, y_cov_norm = gpr_norm.predict(X2, return_cov=True) + + assert_almost_equal(y_cov, y_cov_norm) + + +def test_large_variance_y(): + """ + Here we test that, when noramlize_y=True, our GP can produce a + sensible fit to training data whose variance is significantly + larger than unity. This test was made in response to issue #15612. + + GP predictions are verified against predictions that were made + using GPy which, here, is treated as the 'gold standard'. Note that we + only investigate the RBF kernel here, as that is what was used in the + GPy implementation. + + The following code can be used to recreate the GPy data: + + -------------------------------------------------------------------------- + import GPy + + kernel_gpy = GPy.kern.RBF(input_dim=1, lengthscale=1.) + gpy = GPy.models.GPRegression(X, np.vstack(y_large), kernel_gpy) + gpy.optimize() + y_pred_gpy, y_var_gpy = gpy.predict(X2) + y_pred_std_gpy = np.sqrt(y_var_gpy) + -------------------------------------------------------------------------- + """ + + # Here we utilise a larger variance version of the training data + y_large = 10 * y + + # Standard GP with normalize_y=True + RBF_params = {"length_scale": 1.0} + kernel = RBF(**RBF_params) + gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True) + gpr.fit(X, y_large) + y_pred, y_pred_std = gpr.predict(X2, return_std=True) + + # 'Gold standard' mean predictions from GPy + y_pred_gpy = np.array( + [15.16918303, -27.98707845, -39.31636019, 14.52605515, 69.18503589] + ) + + # 'Gold standard' std predictions from GPy + y_pred_std_gpy = np.array( + [7.78860962, 3.83179178, 0.63149951, 0.52745188, 0.86170042] + ) + + # Based on numerical experiments, it's reasonable to expect our + # GP's mean predictions to get within 7% of predictions of those + # made by GPy. + assert_allclose(y_pred, y_pred_gpy, rtol=0.07, atol=0) + + # Based on numerical experiments, it's reasonable to expect our + # GP's std predictions to get within 15% of predictions of those + # made by GPy. + assert_allclose(y_pred_std, y_pred_std_gpy, rtol=0.15, atol=0) + + +def test_y_multioutput(): + # Test that GPR can deal with multi-dimensional target values + y_2d = np.vstack((y, y * 2)).T + + # Test for fixed kernel that first dimension of 2d GP equals the output + # of 1d GP and that second dimension is twice as large + kernel = RBF(length_scale=1.0) + + gpr = GaussianProcessRegressor(kernel=kernel, optimizer=None, normalize_y=False) + gpr.fit(X, y) + + gpr_2d = GaussianProcessRegressor(kernel=kernel, optimizer=None, normalize_y=False) + gpr_2d.fit(X, y_2d) + + y_pred_1d, y_std_1d = gpr.predict(X2, return_std=True) + y_pred_2d, y_std_2d = gpr_2d.predict(X2, return_std=True) + _, y_cov_1d = gpr.predict(X2, return_cov=True) + _, y_cov_2d = gpr_2d.predict(X2, return_cov=True) + + assert_almost_equal(y_pred_1d, y_pred_2d[:, 0]) + assert_almost_equal(y_pred_1d, y_pred_2d[:, 1] / 2) + + # Standard deviation and covariance do not depend on output + for target in range(y_2d.shape[1]): + assert_almost_equal(y_std_1d, y_std_2d[..., target]) + assert_almost_equal(y_cov_1d, y_cov_2d[..., target]) + + y_sample_1d = gpr.sample_y(X2, n_samples=10) + y_sample_2d = gpr_2d.sample_y(X2, n_samples=10) + + assert y_sample_1d.shape == (5, 10) + assert y_sample_2d.shape == (5, 2, 10) + # Only the first target will be equal + assert_almost_equal(y_sample_1d, y_sample_2d[:, 0, :]) + + # Test hyperparameter optimization + for kernel in kernels: + gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True) + gpr.fit(X, y) + + gpr_2d = GaussianProcessRegressor(kernel=kernel, normalize_y=True) + gpr_2d.fit(X, np.vstack((y, y)).T) + + assert_almost_equal(gpr.kernel_.theta, gpr_2d.kernel_.theta, 4) + + +@pytest.mark.parametrize("kernel", non_fixed_kernels) +def test_custom_optimizer(kernel): + # Test that GPR can use externally defined optimizers. + # Define a dummy optimizer that simply tests 50 random hyperparameters + def optimizer(obj_func, initial_theta, bounds): + rng = np.random.RandomState(0) + theta_opt, func_min = ( + initial_theta, + obj_func(initial_theta, eval_gradient=False), + ) + for _ in range(50): + theta = np.atleast_1d( + rng.uniform(np.maximum(-2, bounds[:, 0]), np.minimum(1, bounds[:, 1])) + ) + f = obj_func(theta, eval_gradient=False) + if f < func_min: + theta_opt, func_min = theta, f + return theta_opt, func_min + + gpr = GaussianProcessRegressor(kernel=kernel, optimizer=optimizer) + gpr.fit(X, y) + # Checks that optimizer improved marginal likelihood + assert gpr.log_marginal_likelihood(gpr.kernel_.theta) > gpr.log_marginal_likelihood( + gpr.kernel.theta + ) + + +def test_gpr_correct_error_message(): + X = np.arange(12).reshape(6, -1) + y = np.ones(6) + kernel = DotProduct() + gpr = GaussianProcessRegressor(kernel=kernel, alpha=0.0) + message = ( + "The kernel, %s, is not returning a " + "positive definite matrix. Try gradually increasing " + "the 'alpha' parameter of your " + "GaussianProcessRegressor estimator." % kernel + ) + with pytest.raises(np.linalg.LinAlgError, match=re.escape(message)): + gpr.fit(X, y) + + +@pytest.mark.parametrize("kernel", kernels) +def test_duplicate_input(kernel): + # Test GPR can handle two different output-values for the same input. + gpr_equal_inputs = GaussianProcessRegressor(kernel=kernel, alpha=1e-2) + gpr_similar_inputs = GaussianProcessRegressor(kernel=kernel, alpha=1e-2) + + X_ = np.vstack((X, X[0])) + y_ = np.hstack((y, y[0] + 1)) + gpr_equal_inputs.fit(X_, y_) + + X_ = np.vstack((X, X[0] + 1e-15)) + y_ = np.hstack((y, y[0] + 1)) + gpr_similar_inputs.fit(X_, y_) + + X_test = np.linspace(0, 10, 100)[:, None] + y_pred_equal, y_std_equal = gpr_equal_inputs.predict(X_test, return_std=True) + y_pred_similar, y_std_similar = gpr_similar_inputs.predict(X_test, return_std=True) + + assert_almost_equal(y_pred_equal, y_pred_similar) + assert_almost_equal(y_std_equal, y_std_similar) + + +def test_no_fit_default_predict(): + # Test that GPR predictions without fit does not break by default. + default_kernel = C(1.0, constant_value_bounds="fixed") * RBF( + 1.0, length_scale_bounds="fixed" + ) + gpr1 = GaussianProcessRegressor() + _, y_std1 = gpr1.predict(X, return_std=True) + _, y_cov1 = gpr1.predict(X, return_cov=True) + + gpr2 = GaussianProcessRegressor(kernel=default_kernel) + _, y_std2 = gpr2.predict(X, return_std=True) + _, y_cov2 = gpr2.predict(X, return_cov=True) + + assert_array_almost_equal(y_std1, y_std2) + assert_array_almost_equal(y_cov1, y_cov2) + + +def test_warning_bounds(): + kernel = RBF(length_scale_bounds=[1e-5, 1e-3]) + gpr = GaussianProcessRegressor(kernel=kernel) + warning_message = ( + "The optimal value found for dimension 0 of parameter " + "length_scale is close to the specified upper bound " + "0.001. Increasing the bound and calling fit again may " + "find a better value." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + gpr.fit(X, y) + + kernel_sum = WhiteKernel(noise_level_bounds=[1e-5, 1e-3]) + RBF( + length_scale_bounds=[1e3, 1e5] + ) + gpr_sum = GaussianProcessRegressor(kernel=kernel_sum) + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + gpr_sum.fit(X, y) + + assert len(record) == 2 + + assert issubclass(record[0].category, ConvergenceWarning) + assert ( + record[0].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "k1__noise_level is close to the " + "specified upper bound 0.001. " + "Increasing the bound and calling " + "fit again may find a better value." + ) + + assert issubclass(record[1].category, ConvergenceWarning) + assert ( + record[1].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "k2__length_scale is close to the " + "specified lower bound 1000.0. " + "Decreasing the bound and calling " + "fit again may find a better value." + ) + + X_tile = np.tile(X, 2) + kernel_dims = RBF(length_scale=[1.0, 2.0], length_scale_bounds=[1e1, 1e2]) + gpr_dims = GaussianProcessRegressor(kernel=kernel_dims) + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + gpr_dims.fit(X_tile, y) + + assert len(record) == 2 + + assert issubclass(record[0].category, ConvergenceWarning) + assert ( + record[0].message.args[0] == "The optimal value found for " + "dimension 0 of parameter " + "length_scale is close to the " + "specified lower bound 10.0. " + "Decreasing the bound and calling " + "fit again may find a better value." + ) + + assert issubclass(record[1].category, ConvergenceWarning) + assert ( + record[1].message.args[0] == "The optimal value found for " + "dimension 1 of parameter " + "length_scale is close to the " + "specified lower bound 10.0. " + "Decreasing the bound and calling " + "fit again may find a better value." + ) + + +def test_bound_check_fixed_hyperparameter(): + # Regression test for issue #17943 + # Check that having a hyperparameter with fixed bounds doesn't cause an + # error + k1 = 50.0**2 * RBF(length_scale=50.0) # long term smooth rising trend + k2 = ExpSineSquared( + length_scale=1.0, periodicity=1.0, periodicity_bounds="fixed" + ) # seasonal component + kernel = k1 + k2 + GaussianProcessRegressor(kernel=kernel).fit(X, y) + + +@pytest.mark.parametrize("kernel", kernels) +def test_constant_target(kernel): + """Check that the std. dev. is affected to 1 when normalizing a constant + feature. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/18318 + NaN where affected to the target when scaling due to null std. dev. with + constant target. + """ + y_constant = np.ones(X.shape[0], dtype=np.float64) + + gpr = GaussianProcessRegressor(kernel=kernel, normalize_y=True) + gpr.fit(X, y_constant) + assert gpr._y_train_std == pytest.approx(1.0) + + y_pred, y_cov = gpr.predict(X, return_cov=True) + assert_allclose(y_pred, y_constant) + # set atol because we compare to zero + assert_allclose(np.diag(y_cov), 0.0, atol=1e-9) + + # Test multi-target data + n_samples, n_targets = X.shape[0], 2 + rng = np.random.RandomState(0) + y = np.concatenate( + [ + rng.normal(size=(n_samples, 1)), # non-constant target + np.full(shape=(n_samples, 1), fill_value=2), # constant target + ], + axis=1, + ) + + gpr.fit(X, y) + Y_pred, Y_cov = gpr.predict(X, return_cov=True) + + assert_allclose(Y_pred[:, 1], 2) + assert_allclose(np.diag(Y_cov[..., 1]), 0.0, atol=1e-9) + + assert Y_pred.shape == (n_samples, n_targets) + assert Y_cov.shape == (n_samples, n_samples, n_targets) + + +def test_gpr_consistency_std_cov_non_invertible_kernel(): + """Check the consistency between the returned std. dev. and the covariance. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/19936 + Inconsistencies were observed when the kernel cannot be inverted (or + numerically stable). + """ + kernel = C(8.98576054e05, (1e-12, 1e12)) * RBF( + [5.91326520e02, 1.32584051e03], (1e-12, 1e12) + ) + WhiteKernel(noise_level=1e-5) + gpr = GaussianProcessRegressor(kernel=kernel, alpha=0, optimizer=None) + X_train = np.array( + [ + [0.0, 0.0], + [1.54919334, -0.77459667], + [-1.54919334, 0.0], + [0.0, -1.54919334], + [0.77459667, 0.77459667], + [-0.77459667, 1.54919334], + ] + ) + y_train = np.array( + [ + [-2.14882017e-10], + [-4.66975823e00], + [4.01823986e00], + [-1.30303674e00], + [-1.35760156e00], + [3.31215668e00], + ] + ) + gpr.fit(X_train, y_train) + X_test = np.array( + [ + [-1.93649167, -1.93649167], + [1.93649167, -1.93649167], + [-1.93649167, 1.93649167], + [1.93649167, 1.93649167], + ] + ) + pred1, std = gpr.predict(X_test, return_std=True) + pred2, cov = gpr.predict(X_test, return_cov=True) + assert_allclose(std, np.sqrt(np.diagonal(cov)), rtol=1e-5) + + +@pytest.mark.parametrize( + "params, TypeError, err_msg", + [ + ( + {"alpha": np.zeros(100)}, + ValueError, + "alpha must be a scalar or an array with same number of entries as y", + ), + ( + { + "kernel": WhiteKernel(noise_level_bounds=(-np.inf, np.inf)), + "n_restarts_optimizer": 2, + }, + ValueError, + "requires that all bounds are finite", + ), + ], +) +def test_gpr_fit_error(params, TypeError, err_msg): + """Check that expected error are raised during fit.""" + gpr = GaussianProcessRegressor(**params) + with pytest.raises(TypeError, match=err_msg): + gpr.fit(X, y) + + +def test_gpr_lml_error(): + """Check that we raise the proper error in the LML method.""" + gpr = GaussianProcessRegressor(kernel=RBF()).fit(X, y) + + err_msg = "Gradient can only be evaluated for theta!=None" + with pytest.raises(ValueError, match=err_msg): + gpr.log_marginal_likelihood(eval_gradient=True) + + +def test_gpr_predict_error(): + """Check that we raise the proper error during predict.""" + gpr = GaussianProcessRegressor(kernel=RBF()).fit(X, y) + + err_msg = "At most one of return_std or return_cov can be requested." + with pytest.raises(RuntimeError, match=err_msg): + gpr.predict(X, return_cov=True, return_std=True) + + +@pytest.mark.parametrize("normalize_y", [True, False]) +@pytest.mark.parametrize("n_targets", [None, 1, 10]) +def test_predict_shapes(normalize_y, n_targets): + """Check the shapes of y_mean, y_std, and y_cov in single-output + (n_targets=None) and multi-output settings, including the edge case when + n_targets=1, where the sklearn convention is to squeeze the predictions. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/17394 + https://github.com/scikit-learn/scikit-learn/issues/18065 + https://github.com/scikit-learn/scikit-learn/issues/22174 + """ + rng = np.random.RandomState(1234) + + n_features, n_samples_train, n_samples_test = 6, 9, 7 + + y_train_shape = (n_samples_train,) + if n_targets is not None: + y_train_shape = y_train_shape + (n_targets,) + + # By convention single-output data is squeezed upon prediction + y_test_shape = (n_samples_test,) + if n_targets is not None and n_targets > 1: + y_test_shape = y_test_shape + (n_targets,) + + X_train = rng.randn(n_samples_train, n_features) + X_test = rng.randn(n_samples_test, n_features) + y_train = rng.randn(*y_train_shape) + + model = GaussianProcessRegressor(normalize_y=normalize_y) + model.fit(X_train, y_train) + + y_pred, y_std = model.predict(X_test, return_std=True) + _, y_cov = model.predict(X_test, return_cov=True) + + assert y_pred.shape == y_test_shape + assert y_std.shape == y_test_shape + assert y_cov.shape == (n_samples_test,) + y_test_shape + + +@pytest.mark.parametrize("normalize_y", [True, False]) +@pytest.mark.parametrize("n_targets", [None, 1, 10]) +def test_sample_y_shapes(normalize_y, n_targets): + """Check the shapes of y_samples in single-output (n_targets=0) and + multi-output settings, including the edge case when n_targets=1, where the + sklearn convention is to squeeze the predictions. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/22175 + """ + rng = np.random.RandomState(1234) + + n_features, n_samples_train = 6, 9 + # Number of spatial locations to predict at + n_samples_X_test = 7 + # Number of sample predictions per test point + n_samples_y_test = 5 + + y_train_shape = (n_samples_train,) + if n_targets is not None: + y_train_shape = y_train_shape + (n_targets,) + + # By convention single-output data is squeezed upon prediction + if n_targets is not None and n_targets > 1: + y_test_shape = (n_samples_X_test, n_targets, n_samples_y_test) + else: + y_test_shape = (n_samples_X_test, n_samples_y_test) + + X_train = rng.randn(n_samples_train, n_features) + X_test = rng.randn(n_samples_X_test, n_features) + y_train = rng.randn(*y_train_shape) + + model = GaussianProcessRegressor(normalize_y=normalize_y) + + # FIXME: before fitting, the estimator does not have information regarding + # the number of targets and default to 1. This is inconsistent with the shape + # provided after `fit`. This assert should be made once the following issue + # is fixed: + # https://github.com/scikit-learn/scikit-learn/issues/22430 + # y_samples = model.sample_y(X_test, n_samples=n_samples_y_test) + # assert y_samples.shape == y_test_shape + + model.fit(X_train, y_train) + + y_samples = model.sample_y(X_test, n_samples=n_samples_y_test) + assert y_samples.shape == y_test_shape + + +@pytest.mark.parametrize("n_targets", [None, 1, 2, 3]) +@pytest.mark.parametrize("n_samples", [1, 5]) +def test_sample_y_shape_with_prior(n_targets, n_samples): + """Check the output shape of `sample_y` is consistent before and after `fit`.""" + rng = np.random.RandomState(1024) + + X = rng.randn(10, 3) + y = rng.randn(10, n_targets if n_targets is not None else 1) + + model = GaussianProcessRegressor(n_targets=n_targets) + shape_before_fit = model.sample_y(X, n_samples=n_samples).shape + model.fit(X, y) + shape_after_fit = model.sample_y(X, n_samples=n_samples).shape + assert shape_before_fit == shape_after_fit + + +@pytest.mark.parametrize("n_targets", [None, 1, 2, 3]) +def test_predict_shape_with_prior(n_targets): + """Check the output shape of `predict` with prior distribution.""" + rng = np.random.RandomState(1024) + + n_sample = 10 + X = rng.randn(n_sample, 3) + y = rng.randn(n_sample, n_targets if n_targets is not None else 1) + + model = GaussianProcessRegressor(n_targets=n_targets) + mean_prior, cov_prior = model.predict(X, return_cov=True) + _, std_prior = model.predict(X, return_std=True) + + model.fit(X, y) + mean_post, cov_post = model.predict(X, return_cov=True) + _, std_post = model.predict(X, return_std=True) + + assert mean_prior.shape == mean_post.shape + assert cov_prior.shape == cov_post.shape + assert std_prior.shape == std_post.shape + + +def test_n_targets_error(): + """Check that an error is raised when the number of targets seen at fit is + inconsistent with n_targets. + """ + rng = np.random.RandomState(0) + X = rng.randn(10, 3) + y = rng.randn(10, 2) + + model = GaussianProcessRegressor(n_targets=1) + with pytest.raises(ValueError, match="The number of targets seen in `y`"): + model.fit(X, y) + + +class CustomKernel(C): + """ + A custom kernel that has a diag method that returns the first column of the + input matrix X. This is a helper for the test to check that the input + matrix X is not mutated. + """ + + def diag(self, X): + return X[:, 0] + + +def test_gpr_predict_input_not_modified(): + """ + Check that the input X is not modified by the predict method of the + GaussianProcessRegressor when setting return_std=True. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/24340 + """ + gpr = GaussianProcessRegressor(kernel=CustomKernel()).fit(X, y) + + X2_copy = np.copy(X2) + _, _ = gpr.predict(X2, return_std=True) + + assert_allclose(X2, X2_copy) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_kernels.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..5174d50b7df9210fbf67677ed5f18eaedf209ecc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/gaussian_process/tests/test_kernels.py @@ -0,0 +1,403 @@ +"""Testing for kernels for Gaussian processes.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from inspect import signature + +import numpy as np +import pytest + +from sklearn.base import clone +from sklearn.gaussian_process.kernels import ( + RBF, + CompoundKernel, + ConstantKernel, + DotProduct, + Exponentiation, + ExpSineSquared, + KernelOperator, + Matern, + PairwiseKernel, + RationalQuadratic, + WhiteKernel, + _approx_fprime, +) +from sklearn.metrics.pairwise import ( + PAIRWISE_KERNEL_FUNCTIONS, + euclidean_distances, + pairwise_kernels, +) +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) + +X = np.random.RandomState(0).normal(0, 1, (5, 2)) +Y = np.random.RandomState(0).normal(0, 1, (6, 2)) +# Set shared test data as read-only to avoid unintentional in-place +# modifications that would introduce side-effects between tests. +X.flags.writeable = False +Y.flags.writeable = False + +kernel_rbf_plus_white = RBF(length_scale=2.0) + WhiteKernel(noise_level=3.0) +kernels = [ + RBF(length_scale=2.0), + RBF(length_scale_bounds=(0.5, 2.0)), + ConstantKernel(constant_value=10.0), + 2.0 * RBF(length_scale=0.33, length_scale_bounds="fixed"), + 2.0 * RBF(length_scale=0.5), + kernel_rbf_plus_white, + 2.0 * RBF(length_scale=[0.5, 2.0]), + 2.0 * Matern(length_scale=0.33, length_scale_bounds="fixed"), + 2.0 * Matern(length_scale=0.5, nu=0.5), + 2.0 * Matern(length_scale=1.5, nu=1.5), + 2.0 * Matern(length_scale=2.5, nu=2.5), + 2.0 * Matern(length_scale=[0.5, 2.0], nu=0.5), + 3.0 * Matern(length_scale=[2.0, 0.5], nu=1.5), + 4.0 * Matern(length_scale=[0.5, 0.5], nu=2.5), + RationalQuadratic(length_scale=0.5, alpha=1.5), + ExpSineSquared(length_scale=0.5, periodicity=1.5), + DotProduct(sigma_0=2.0), + DotProduct(sigma_0=2.0) ** 2, + RBF(length_scale=[2.0]), + Matern(length_scale=[2.0]), +] +for metric in PAIRWISE_KERNEL_FUNCTIONS: + if metric in ["additive_chi2", "chi2"]: + continue + kernels.append(PairwiseKernel(gamma=1.0, metric=metric)) + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_gradient(kernel): + # Compare analytic and numeric gradient of kernels. + kernel = clone(kernel) # make tests independent of one-another + K, K_gradient = kernel(X, eval_gradient=True) + + assert K_gradient.shape[0] == X.shape[0] + assert K_gradient.shape[1] == X.shape[0] + assert K_gradient.shape[2] == kernel.theta.shape[0] + + def eval_kernel_for_theta(theta): + kernel_clone = kernel.clone_with_theta(theta) + K = kernel_clone(X, eval_gradient=False) + return K + + K_gradient_approx = _approx_fprime(kernel.theta, eval_kernel_for_theta, 1e-10) + + assert_almost_equal(K_gradient, K_gradient_approx, 4) + + +@pytest.mark.parametrize( + "kernel", + [ + kernel + for kernel in kernels + # skip non-basic kernels + if not (isinstance(kernel, (KernelOperator, Exponentiation))) + ], +) +def test_kernel_theta(kernel): + # Check that parameter vector theta of kernel is set correctly. + kernel = clone(kernel) # make tests independent of one-another + theta = kernel.theta + _, K_gradient = kernel(X, eval_gradient=True) + + # Determine kernel parameters that contribute to theta + init_sign = signature(kernel.__class__.__init__).parameters.values() + args = [p.name for p in init_sign if p.name != "self"] + theta_vars = map( + lambda s: s[0 : -len("_bounds")], filter(lambda s: s.endswith("_bounds"), args) + ) + assert set(hyperparameter.name for hyperparameter in kernel.hyperparameters) == set( + theta_vars + ) + + # Check that values returned in theta are consistent with + # hyperparameter values (being their logarithms) + for i, hyperparameter in enumerate(kernel.hyperparameters): + assert theta[i] == np.log(getattr(kernel, hyperparameter.name)) + + # Fixed kernel parameters must be excluded from theta and gradient. + for i, hyperparameter in enumerate(kernel.hyperparameters): + # create copy with certain hyperparameter fixed + params = kernel.get_params() + params[hyperparameter.name + "_bounds"] = "fixed" + kernel_class = kernel.__class__ + new_kernel = kernel_class(**params) + # Check that theta and K_gradient are identical with the fixed + # dimension left out + _, K_gradient_new = new_kernel(X, eval_gradient=True) + assert theta.shape[0] == new_kernel.theta.shape[0] + 1 + assert K_gradient.shape[2] == K_gradient_new.shape[2] + 1 + if i > 0: + assert theta[:i] == new_kernel.theta[:i] + assert_array_equal(K_gradient[..., :i], K_gradient_new[..., :i]) + if i + 1 < len(kernel.hyperparameters): + assert theta[i + 1 :] == new_kernel.theta[i:] + assert_array_equal(K_gradient[..., i + 1 :], K_gradient_new[..., i:]) + + # Check that values of theta are modified correctly + for i, hyperparameter in enumerate(kernel.hyperparameters): + theta[i] = np.log(42) + kernel.theta = theta + assert_almost_equal(getattr(kernel, hyperparameter.name), 42) + + setattr(kernel, hyperparameter.name, 43) + assert_almost_equal(kernel.theta[i], np.log(43)) + + +@pytest.mark.parametrize( + "kernel", + [ + kernel + for kernel in kernels + # Identity is not satisfied on diagonal + if kernel != kernel_rbf_plus_white + ], +) +def test_auto_vs_cross(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Auto-correlation and cross-correlation should be consistent. + K_auto = kernel(X) + K_cross = kernel(X, X) + assert_almost_equal(K_auto, K_cross, 5) + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_diag(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Test that diag method of kernel returns consistent results. + K_call_diag = np.diag(kernel(X)) + K_diag = kernel.diag(X) + assert_almost_equal(K_call_diag, K_diag, 5) + + +def test_kernel_operator_commutative(): + # Adding kernels and multiplying kernels should be commutative. + # Check addition + assert_almost_equal((RBF(2.0) + 1.0)(X), (1.0 + RBF(2.0))(X)) + + # Check multiplication + assert_almost_equal((3.0 * RBF(2.0))(X), (RBF(2.0) * 3.0)(X)) + + +def test_kernel_anisotropic(): + # Anisotropic kernel should be consistent with isotropic kernels. + kernel = 3.0 * RBF([0.5, 2.0]) + + K = kernel(X) + X1 = X.copy() + X1[:, 0] *= 4 + K1 = 3.0 * RBF(2.0)(X1) + assert_almost_equal(K, K1) + + X2 = X.copy() + X2[:, 1] /= 4 + K2 = 3.0 * RBF(0.5)(X2) + assert_almost_equal(K, K2) + + # Check getting and setting via theta + kernel.theta = kernel.theta + np.log(2) + assert_array_equal(kernel.theta, np.log([6.0, 1.0, 4.0])) + assert_array_equal(kernel.k2.length_scale, [1.0, 4.0]) + + +@pytest.mark.parametrize( + "kernel", [kernel for kernel in kernels if kernel.is_stationary()] +) +def test_kernel_stationary(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Test stationarity of kernels. + K = kernel(X, X + 1) + assert_almost_equal(K[0, 0], np.diag(K)) + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_input_type(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Test whether kernels is for vectors or structured data + if isinstance(kernel, Exponentiation): + assert kernel.requires_vector_input == kernel.kernel.requires_vector_input + if isinstance(kernel, KernelOperator): + assert kernel.requires_vector_input == ( + kernel.k1.requires_vector_input or kernel.k2.requires_vector_input + ) + + +def test_compound_kernel_input_type(): + kernel = CompoundKernel([WhiteKernel(noise_level=3.0)]) + assert not kernel.requires_vector_input + + kernel = CompoundKernel([WhiteKernel(noise_level=3.0), RBF(length_scale=2.0)]) + assert kernel.requires_vector_input + + +def check_hyperparameters_equal(kernel1, kernel2): + # Check that hyperparameters of two kernels are equal + for attr in set(dir(kernel1) + dir(kernel2)): + if attr.startswith("hyperparameter_"): + attr_value1 = getattr(kernel1, attr) + attr_value2 = getattr(kernel2, attr) + assert attr_value1 == attr_value2 + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_clone(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Test that sklearn's clone works correctly on kernels. + kernel_cloned = clone(kernel) + + # XXX: Should this be fixed? + # This differs from the sklearn's estimators equality check. + assert kernel == kernel_cloned + assert id(kernel) != id(kernel_cloned) + + # Check that all constructor parameters are equal. + assert kernel.get_params() == kernel_cloned.get_params() + + # Check that all hyperparameters are equal. + check_hyperparameters_equal(kernel, kernel_cloned) + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_clone_after_set_params(kernel): + kernel = clone(kernel) # make tests independent of one-another + # This test is to verify that using set_params does not + # break clone on kernels. + # This used to break because in kernels such as the RBF, non-trivial + # logic that modified the length scale used to be in the constructor + # See https://github.com/scikit-learn/scikit-learn/issues/6961 + # for more details. + bounds = (1e-5, 1e5) + kernel_cloned = clone(kernel) + params = kernel.get_params() + # RationalQuadratic kernel is isotropic. + isotropic_kernels = (ExpSineSquared, RationalQuadratic) + if "length_scale" in params and not isinstance(kernel, isotropic_kernels): + length_scale = params["length_scale"] + if np.iterable(length_scale): + # XXX unreached code as of v0.22 + params["length_scale"] = length_scale[0] + params["length_scale_bounds"] = bounds + else: + params["length_scale"] = [length_scale] * 2 + params["length_scale_bounds"] = bounds * 2 + kernel_cloned.set_params(**params) + kernel_cloned_clone = clone(kernel_cloned) + assert kernel_cloned_clone.get_params() == kernel_cloned.get_params() + assert id(kernel_cloned_clone) != id(kernel_cloned) + check_hyperparameters_equal(kernel_cloned, kernel_cloned_clone) + + +def test_matern_kernel(): + # Test consistency of Matern kernel for special values of nu. + K = Matern(nu=1.5, length_scale=1.0)(X) + # the diagonal elements of a matern kernel are 1 + assert_array_almost_equal(np.diag(K), np.ones(X.shape[0])) + # matern kernel for coef0==0.5 is equal to absolute exponential kernel + K_absexp = np.exp(-euclidean_distances(X, X, squared=False)) + K = Matern(nu=0.5, length_scale=1.0)(X) + assert_array_almost_equal(K, K_absexp) + # matern kernel with coef0==inf is equal to RBF kernel + K_rbf = RBF(length_scale=1.0)(X) + K = Matern(nu=np.inf, length_scale=1.0)(X) + assert_array_almost_equal(K, K_rbf) + assert_allclose(K, K_rbf) + # test that special cases of matern kernel (coef0 in [0.5, 1.5, 2.5]) + # result in nearly identical results as the general case for coef0 in + # [0.5 + tiny, 1.5 + tiny, 2.5 + tiny] + tiny = 1e-10 + for nu in [0.5, 1.5, 2.5]: + K1 = Matern(nu=nu, length_scale=1.0)(X) + K2 = Matern(nu=nu + tiny, length_scale=1.0)(X) + assert_array_almost_equal(K1, K2) + # test that coef0==large is close to RBF + large = 100 + K1 = Matern(nu=large, length_scale=1.0)(X) + K2 = RBF(length_scale=1.0)(X) + assert_array_almost_equal(K1, K2, decimal=2) + + +@pytest.mark.parametrize("kernel", kernels) +def test_kernel_versus_pairwise(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Check that GP kernels can also be used as pairwise kernels. + + # Test auto-kernel + if kernel != kernel_rbf_plus_white: + # For WhiteKernel: k(X) != k(X,X). This is assumed by + # pairwise_kernels + K1 = kernel(X) + K2 = pairwise_kernels(X, metric=kernel) + assert_array_almost_equal(K1, K2) + + # Test cross-kernel + K1 = kernel(X, Y) + K2 = pairwise_kernels(X, Y, metric=kernel) + assert_array_almost_equal(K1, K2) + + +@pytest.mark.parametrize("kernel", kernels) +def test_set_get_params(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Check that set_params()/get_params() is consistent with kernel.theta. + + # Test get_params() + index = 0 + params = kernel.get_params() + for hyperparameter in kernel.hyperparameters: + if isinstance("string", type(hyperparameter.bounds)): + if hyperparameter.bounds == "fixed": + continue + size = hyperparameter.n_elements + if size > 1: # anisotropic kernels + assert_almost_equal( + np.exp(kernel.theta[index : index + size]), params[hyperparameter.name] + ) + index += size + else: + assert_almost_equal( + np.exp(kernel.theta[index]), params[hyperparameter.name] + ) + index += 1 + # Test set_params() + index = 0 + value = 10 # arbitrary value + for hyperparameter in kernel.hyperparameters: + if isinstance("string", type(hyperparameter.bounds)): + if hyperparameter.bounds == "fixed": + continue + size = hyperparameter.n_elements + if size > 1: # anisotropic kernels + kernel.set_params(**{hyperparameter.name: [value] * size}) + assert_almost_equal( + np.exp(kernel.theta[index : index + size]), [value] * size + ) + index += size + else: + kernel.set_params(**{hyperparameter.name: value}) + assert_almost_equal(np.exp(kernel.theta[index]), value) + index += 1 + + +@pytest.mark.parametrize("kernel", kernels) +def test_repr_kernels(kernel): + kernel = clone(kernel) # make tests independent of one-another + # Smoke-test for repr in kernels. + + repr(kernel) + + +def test_rational_quadratic_kernel(): + kernel = RationalQuadratic(length_scale=[1.0, 1.0]) + message = ( + "RationalQuadratic kernel only supports isotropic " + "version, please use a single " + "scalar for length_scale" + ) + with pytest.raises(AttributeError, match=message): + kernel(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aaa81d73c34a19004645733c05ea362aae8dcb01 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/__init__.py @@ -0,0 +1,28 @@ +"""Transformers for missing value imputation.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import typing + +from ._base import MissingIndicator, SimpleImputer +from ._knn import KNNImputer + +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 ._iterative import IterativeImputer # noqa: F401 + +__all__ = ["KNNImputer", "MissingIndicator", "SimpleImputer"] + + +# TODO: remove this check once the estimator is no longer experimental. +def __getattr__(name): + if name == "IterativeImputer": + raise ImportError( + f"{name} is experimental and the API might change without any " + "deprecation cycle. To use it, you need to explicitly import " + "enable_iterative_imputer:\n" + "from sklearn.experimental import enable_iterative_imputer" + ) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..ae74068145678bd362296a367007371a5a353a95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_base.py @@ -0,0 +1,1155 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import warnings +from collections import Counter +from functools import partial +from typing import Callable + +import numpy as np +import numpy.ma as ma +from scipy import sparse as sp + +from ..base import BaseEstimator, TransformerMixin, _fit_context +from ..utils._mask import _get_mask +from ..utils._missing import is_pandas_na, is_scalar_nan +from ..utils._param_validation import MissingValues, StrOptions +from ..utils.fixes import _mode +from ..utils.sparsefuncs import _get_median +from ..utils.validation import ( + FLOAT_DTYPES, + _check_feature_names_in, + _check_n_features, + check_is_fitted, + validate_data, +) + + +def _check_inputs_dtype(X, missing_values): + if is_pandas_na(missing_values): + # Allow using `pd.NA` as missing values to impute numerical arrays. + return + if X.dtype.kind in ("f", "i", "u") and not isinstance(missing_values, numbers.Real): + raise ValueError( + "'X' and 'missing_values' types are expected to be" + " both numerical. Got X.dtype={} and " + " type(missing_values)={}.".format(X.dtype, type(missing_values)) + ) + + +def _safe_min(items): + """Compute the minimum of a list of potentially non-comparable values. + + If values cannot be directly compared due to type incompatibility, the object with + the lowest string representation is returned. + """ + try: + return min(items) + except TypeError as e: + if "'<' not supported between" in str(e): + return min(items, key=lambda x: (str(type(x)), str(x))) + raise # pragma: no cover + + +def _most_frequent(array, extra_value, n_repeat): + """Compute the most frequent value in a 1d array extended with + [extra_value] * n_repeat, where extra_value is assumed to be not part + of the array.""" + # Compute the most frequent value in array only + if array.size > 0: + if array.dtype == object: + # scipy.stats.mode is slow with object dtype array. + # Python Counter is more efficient + counter = Counter(array) + most_frequent_count = counter.most_common(1)[0][1] + # tie breaking similarly to scipy.stats.mode + most_frequent_value = _safe_min( + [ + value + for value, count in counter.items() + if count == most_frequent_count + ] + ) + else: + mode = _mode(array) + most_frequent_value = mode[0][0] + most_frequent_count = mode[1][0] + else: + most_frequent_value = 0 + most_frequent_count = 0 + + # Compare to array + [extra_value] * n_repeat + if most_frequent_count == 0 and n_repeat == 0: + return np.nan + elif most_frequent_count < n_repeat: + return extra_value + elif most_frequent_count > n_repeat: + return most_frequent_value + elif most_frequent_count == n_repeat: + # tie breaking similarly to scipy.stats.mode + return _safe_min([most_frequent_value, extra_value]) + + +class _BaseImputer(TransformerMixin, BaseEstimator): + """Base class for all imputers. + + It adds automatically support for `add_indicator`. + """ + + _parameter_constraints: dict = { + "missing_values": [MissingValues()], + "add_indicator": ["boolean"], + "keep_empty_features": ["boolean"], + } + + def __init__( + self, *, missing_values=np.nan, add_indicator=False, keep_empty_features=False + ): + self.missing_values = missing_values + self.add_indicator = add_indicator + self.keep_empty_features = keep_empty_features + + def _fit_indicator(self, X): + """Fit a MissingIndicator.""" + if self.add_indicator: + self.indicator_ = MissingIndicator( + missing_values=self.missing_values, error_on_new=False + ) + self.indicator_._fit(X, precomputed=True) + else: + self.indicator_ = None + + def _transform_indicator(self, X): + """Compute the indicator mask.' + + Note that X must be the original data as passed to the imputer before + any imputation, since imputation may be done inplace in some cases. + """ + if self.add_indicator: + if not hasattr(self, "indicator_"): + raise ValueError( + "Make sure to call _fit_indicator before _transform_indicator" + ) + return self.indicator_.transform(X) + + def _concatenate_indicator(self, X_imputed, X_indicator): + """Concatenate indicator mask with the imputed data.""" + if not self.add_indicator: + return X_imputed + + if sp.issparse(X_imputed): + # sp.hstack may result in different formats between sparse arrays and + # matrices; specify the format to keep consistent behavior + hstack = partial(sp.hstack, format=X_imputed.format) + else: + hstack = np.hstack + + if X_indicator is None: + raise ValueError( + "Data from the missing indicator are not provided. Call " + "_fit_indicator and _transform_indicator in the imputer " + "implementation." + ) + + 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 __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = is_scalar_nan(self.missing_values) + return tags + + +class SimpleImputer(_BaseImputer): + """Univariate imputer for completing missing values with simple strategies. + + Replace missing values using a descriptive statistic (e.g. mean, median, or + most frequent) along each column, or using a constant value. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + `SimpleImputer` replaces the previous `sklearn.preprocessing.Imputer` + estimator which is now removed. + + Parameters + ---------- + missing_values : int, float, str, np.nan, None or pandas.NA, default=np.nan + The placeholder for the missing values. All occurrences of + `missing_values` will be imputed. For pandas' dataframes with + nullable integer dtypes with missing values, `missing_values` + can be set to either `np.nan` or `pd.NA`. + + strategy : str or Callable, default='mean' + The imputation strategy. + + - If "mean", then replace missing values using the mean along + each column. Can only be used with numeric data. + - If "median", then replace missing values using the median along + each column. Can only be used with numeric data. + - If "most_frequent", then replace missing using the most frequent + value along each column. Can be used with strings or numeric data. + If there is more than one such value, only the smallest is returned. + - If "constant", then replace missing values with fill_value. Can be + used with strings or numeric data. + - If an instance of Callable, then replace missing values using the + scalar statistic returned by running the callable over a dense 1d + array containing non-missing values of each column. + + .. versionadded:: 0.20 + strategy="constant" for fixed value imputation. + + .. versionadded:: 1.5 + strategy=callable for custom value imputation. + + fill_value : str or numerical value, default=None + When strategy == "constant", `fill_value` is used to replace all + occurrences of missing_values. For string or object data types, + `fill_value` must be a string. + If `None`, `fill_value` will be 0 when imputing numerical + data and "missing_value" for strings or object data types. + + copy : bool, default=True + If True, a copy of X will be created. If False, imputation will + be done in-place whenever possible. Note that, in the following cases, + a new copy will always be made, even if `copy=False`: + + - If `X` is not an array of floating values; + - If `X` is encoded as a CSR matrix; + - If `add_indicator=True`. + + add_indicator : bool, default=False + If True, a :class:`MissingIndicator` transform will stack onto output + of the imputer's transform. This allows a predictive estimator + to account for missingness despite imputation. If a feature has no + missing values at fit/train time, the feature won't appear on + the missing indicator even if there are missing values at + transform/test time. + + keep_empty_features : bool, default=False + If True, features that consist exclusively of missing values when + `fit` is called are returned in results when `transform` is called. + The imputed value is always `0` except when `strategy="constant"` + in which case `fill_value` will be used instead. + + .. versionadded:: 1.2 + + .. versionchanged:: 1.6 + Currently, when `keep_empty_feature=False` and `strategy="constant"`, + empty features are not dropped. This behaviour will change in version + 1.8. Set `keep_empty_feature=True` to preserve this behaviour. + + Attributes + ---------- + statistics_ : array of shape (n_features,) + The imputation fill value for each feature. + Computing statistics can result in `np.nan` values. + During :meth:`transform`, features corresponding to `np.nan` + statistics will be discarded. + + indicator_ : :class:`~sklearn.impute.MissingIndicator` + Indicator used to add binary indicators for missing values. + `None` if `add_indicator=False`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + IterativeImputer : Multivariate imputer that estimates values to impute for + each feature with missing values from all the others. + KNNImputer : Multivariate imputer that estimates missing features using + nearest samples. + + Notes + ----- + Columns which only contained missing values at :meth:`fit` are discarded + upon :meth:`transform` if strategy is not `"constant"`. + + In a prediction context, simple imputation usually performs poorly when + associated with a weak learner. However, with a powerful learner, it can + lead to as good or better performance than complex imputation such as + :class:`~sklearn.impute.IterativeImputer` or :class:`~sklearn.impute.KNNImputer`. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.impute import SimpleImputer + >>> imp_mean = SimpleImputer(missing_values=np.nan, strategy='mean') + >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]]) + SimpleImputer() + >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]] + >>> print(imp_mean.transform(X)) + [[ 7. 2. 3. ] + [ 4. 3.5 6. ] + [10. 3.5 9. ]] + + For a more detailed example see + :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py`. + """ + + _parameter_constraints: dict = { + **_BaseImputer._parameter_constraints, + "strategy": [ + StrOptions({"mean", "median", "most_frequent", "constant"}), + callable, + ], + "fill_value": "no_validation", # any object is valid + "copy": ["boolean"], + } + + def __init__( + self, + *, + missing_values=np.nan, + strategy="mean", + fill_value=None, + copy=True, + add_indicator=False, + keep_empty_features=False, + ): + super().__init__( + missing_values=missing_values, + add_indicator=add_indicator, + keep_empty_features=keep_empty_features, + ) + self.strategy = strategy + self.fill_value = fill_value + self.copy = copy + + def _validate_input(self, X, in_fit): + if self.strategy in ("most_frequent", "constant"): + # 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 + + if not in_fit and self._fit_dtype.kind == "O": + # Use object dtype if fitted on object dtypes + dtype = self._fit_dtype + + if is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values): + ensure_all_finite = "allow-nan" + else: + ensure_all_finite = True + + try: + X = validate_data( + self, + X, + reset=in_fit, + accept_sparse="csc", + dtype=dtype, + force_writeable=True if not in_fit else None, + ensure_all_finite=ensure_all_finite, + copy=self.copy, + ) + except ValueError as ve: + if "could not convert" in str(ve): + new_ve = ValueError( + "Cannot use {} strategy with non-numeric data:\n{}".format( + self.strategy, ve + ) + ) + raise new_ve from None + else: + raise ve + + if in_fit: + # Use the dtype seen in `fit` for non-`fit` conversion + self._fit_dtype = X.dtype + + _check_inputs_dtype(X, self.missing_values) + if X.dtype.kind not in ("i", "u", "f", "O"): + raise ValueError( + "SimpleImputer does not support data with dtype " + "{0}. Please provide either a numeric array (with" + " a floating point or integer dtype) or " + "categorical data represented either as an array " + "with integer dtype or an array of string values " + "with an object dtype.".format(X.dtype) + ) + + if sp.issparse(X) and self.missing_values == 0: + # missing_values = 0 not allowed with sparse data as it would + # force densification + raise ValueError( + "Imputation not possible when missing_values " + "== 0 and input is sparse. Provide a dense " + "array instead." + ) + + if self.strategy == "constant": + if in_fit and self.fill_value is not None: + fill_value_dtype = type(self.fill_value) + err_msg = ( + f"fill_value={self.fill_value!r} (of type {fill_value_dtype!r}) " + f"cannot be cast to the input data that is {X.dtype!r}. " + "If fill_value is a Python scalar, instead pass a numpy scalar " + "(e.g. fill_value=np.uint8(0) if your data is of type np.uint8). " + "Make sure that both dtypes are of the same kind." + ) + elif not in_fit: + fill_value_dtype = self.statistics_.dtype + err_msg = ( + f"The dtype of the filling value (i.e. {fill_value_dtype!r}) " + f"cannot be cast to the input data that is {X.dtype!r}. " + "Make sure that the dtypes of the input data are of the same kind " + "between fit and transform." + ) + else: + # By default, fill_value=None, and the replacement is always + # compatible with the input data + fill_value_dtype = X.dtype + + # Make sure we can safely cast fill_value dtype to the input data dtype + if not np.can_cast(fill_value_dtype, X.dtype, casting="same_kind"): + raise ValueError(err_msg) + + return X + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the imputer on `X`. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Fitted estimator. + """ + X = self._validate_input(X, in_fit=True) + + # default fill_value is 0 for numerical input and "missing_value" + # otherwise + if self.fill_value is None: + if X.dtype.kind in ("i", "u", "f"): + fill_value = 0 + else: + fill_value = "missing_value" + else: + fill_value = self.fill_value + + if sp.issparse(X): + self.statistics_ = self._sparse_fit( + X, self.strategy, self.missing_values, fill_value + ) + else: + self.statistics_ = self._dense_fit( + X, self.strategy, self.missing_values, fill_value + ) + + return self + + def _sparse_fit(self, X, strategy, missing_values, fill_value): + """Fit the transformer on sparse data.""" + missing_mask = _get_mask(X, missing_values) + mask_data = missing_mask.data + n_implicit_zeros = X.shape[0] - np.diff(X.indptr) + + statistics = np.empty(X.shape[1]) + + if strategy == "constant": + # TODO(1.8): Remove FutureWarning and add `np.nan` as a statistic + # for empty features to drop them later. + if not self.keep_empty_features and any( + [all(missing_mask[:, i].data) for i in range(missing_mask.shape[1])] + ): + warnings.warn( + "Currently, when `keep_empty_feature=False` and " + '`strategy="constant"`, empty features are not dropped. ' + "This behaviour will change in version 1.8. Set " + "`keep_empty_feature=True` to preserve this behaviour.", + FutureWarning, + ) + + # for constant strategy, self.statistics_ is used to store + # fill_value in each column + statistics.fill(fill_value) + else: + for i in range(X.shape[1]): + column = X.data[X.indptr[i] : X.indptr[i + 1]] + mask_column = mask_data[X.indptr[i] : X.indptr[i + 1]] + column = column[~mask_column] + + # combine explicit and implicit zeros + mask_zeros = _get_mask(column, 0) + column = column[~mask_zeros] + n_explicit_zeros = mask_zeros.sum() + n_zeros = n_implicit_zeros[i] + n_explicit_zeros + + if len(column) == 0 and self.keep_empty_features: + # in case we want to keep columns with only missing values. + statistics[i] = 0 + else: + if strategy == "mean": + s = column.size + n_zeros + statistics[i] = np.nan if s == 0 else column.sum() / s + + elif strategy == "median": + statistics[i] = _get_median(column, n_zeros) + + elif strategy == "most_frequent": + statistics[i] = _most_frequent(column, 0, n_zeros) + + elif isinstance(strategy, Callable): + statistics[i] = self.strategy(column) + + super()._fit_indicator(missing_mask) + + return statistics + + def _dense_fit(self, X, strategy, missing_values, fill_value): + """Fit the transformer on dense data.""" + missing_mask = _get_mask(X, missing_values) + masked_X = ma.masked_array(X, mask=missing_mask) + + super()._fit_indicator(missing_mask) + + # Mean + if strategy == "mean": + mean_masked = np.ma.mean(masked_X, axis=0) + # Avoid the warning "Warning: converting a masked element to nan." + mean = np.ma.getdata(mean_masked) + mean[np.ma.getmask(mean_masked)] = 0 if self.keep_empty_features else np.nan + + return mean + + # Median + elif strategy == "median": + median_masked = np.ma.median(masked_X, axis=0) + # Avoid the warning "Warning: converting a masked element to nan." + median = np.ma.getdata(median_masked) + median[np.ma.getmaskarray(median_masked)] = ( + 0 if self.keep_empty_features else np.nan + ) + + return median + + # Most frequent + elif strategy == "most_frequent": + # Avoid use of scipy.stats.mstats.mode due to the required + # additional overhead and slow benchmarking performance. + # See Issue 14325 and PR 14399 for full discussion. + + # To be able access the elements by columns + X = X.transpose() + mask = missing_mask.transpose() + + if X.dtype.kind == "O": + most_frequent = np.empty(X.shape[0], dtype=object) + else: + most_frequent = np.empty(X.shape[0]) + + for i, (row, row_mask) in enumerate(zip(X[:], mask[:])): + row_mask = np.logical_not(row_mask).astype(bool) + row = row[row_mask] + if len(row) == 0 and self.keep_empty_features: + most_frequent[i] = 0 + else: + most_frequent[i] = _most_frequent(row, np.nan, 0) + + return most_frequent + + # Constant + elif strategy == "constant": + # TODO(1.8): Remove FutureWarning and add `np.nan` as a statistic + # for empty features to drop them later. + if not self.keep_empty_features and ma.getmask(masked_X).all(axis=0).any(): + warnings.warn( + "Currently, when `keep_empty_feature=False` and " + '`strategy="constant"`, empty features are not dropped. ' + "This behaviour will change in version 1.8. Set " + "`keep_empty_feature=True` to preserve this behaviour.", + FutureWarning, + ) + + # for constant strategy, self.statistcs_ is used to store + # fill_value in each column + return np.full(X.shape[1], fill_value, dtype=X.dtype) + + # Custom + elif isinstance(strategy, Callable): + statistics = np.empty(masked_X.shape[1]) + for i in range(masked_X.shape[1]): + statistics[i] = self.strategy(masked_X[:, i].compressed()) + return statistics + + def transform(self, X): + """Impute all missing values in `X`. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + The input data to complete. + + Returns + ------- + X_imputed : {ndarray, sparse matrix} of shape \ + (n_samples, n_features_out) + `X` with imputed values. + """ + check_is_fitted(self) + + X = self._validate_input(X, in_fit=False) + statistics = self.statistics_ + + if X.shape[1] != statistics.shape[0]: + raise ValueError( + "X has %d features per sample, expected %d" + % (X.shape[1], self.statistics_.shape[0]) + ) + + # compute mask before eliminating invalid features + missing_mask = _get_mask(X, self.missing_values) + + # Decide whether to keep missing features + if self.strategy == "constant" or self.keep_empty_features: + valid_statistics = statistics + valid_statistics_indexes = None + else: + # same as np.isnan but also works for object dtypes + invalid_mask = _get_mask(statistics, np.nan) + valid_mask = np.logical_not(invalid_mask) + valid_statistics = statistics[valid_mask] + valid_statistics_indexes = np.flatnonzero(valid_mask) + + if invalid_mask.any(): + invalid_features = np.arange(X.shape[1])[invalid_mask] + # use feature names warning if features are provided + if hasattr(self, "feature_names_in_"): + invalid_features = self.feature_names_in_[invalid_features] + warnings.warn( + "Skipping features without any observed values:" + f" {invalid_features}. At least one non-missing value is needed" + f" for imputation with strategy='{self.strategy}'." + ) + X = X[:, valid_statistics_indexes] + + # Do actual imputation + if sp.issparse(X): + if self.missing_values == 0: + raise ValueError( + "Imputation not possible when missing_values " + "== 0 and input is sparse. Provide a dense " + "array instead." + ) + else: + # if no invalid statistics are found, use the mask computed + # before, else recompute mask + if valid_statistics_indexes is None: + mask = missing_mask.data + else: + mask = _get_mask(X.data, self.missing_values) + indexes = np.repeat( + np.arange(len(X.indptr) - 1, dtype=int), np.diff(X.indptr) + )[mask] + + X.data[mask] = valid_statistics[indexes].astype(X.dtype, copy=False) + else: + # use mask computed before eliminating invalid mask + if valid_statistics_indexes is None: + mask_valid_features = missing_mask + else: + mask_valid_features = missing_mask[:, valid_statistics_indexes] + n_missing = np.sum(mask_valid_features, axis=0) + values = np.repeat(valid_statistics, n_missing) + coordinates = np.where(mask_valid_features.transpose())[::-1] + + X[coordinates] = values + + X_indicator = super()._transform_indicator(missing_mask) + + return super()._concatenate_indicator(X, X_indicator) + + def inverse_transform(self, X): + """Convert the data back to the original representation. + + Inverts the `transform` operation performed on an array. + This operation can only be performed after :class:`SimpleImputer` is + instantiated with `add_indicator=True`. + + Note that `inverse_transform` can only invert the transform in + features that have binary indicators for missing values. If a feature + has no missing values at `fit` time, the feature won't have a binary + indicator, and the imputation done at `transform` time won't be + inverted. + + .. versionadded:: 0.24 + + Parameters + ---------- + X : array-like of shape \ + (n_samples, n_features + n_features_missing_indicator) + The imputed data to be reverted to original data. It has to be + an augmented array of imputed data and the missing indicator mask. + + Returns + ------- + X_original : ndarray of shape (n_samples, n_features) + The original `X` with missing values as it was prior + to imputation. + """ + check_is_fitted(self) + + if not self.add_indicator: + raise ValueError( + "'inverse_transform' works only when " + "'SimpleImputer' is instantiated with " + "'add_indicator=True'. " + f"Got 'add_indicator={self.add_indicator}' " + "instead." + ) + + n_features_missing = len(self.indicator_.features_) + non_empty_feature_count = X.shape[1] - n_features_missing + array_imputed = X[:, :non_empty_feature_count].copy() + missing_mask = X[:, non_empty_feature_count:].astype(bool) + + n_features_original = len(self.statistics_) + shape_original = (X.shape[0], n_features_original) + X_original = np.zeros(shape_original) + X_original[:, self.indicator_.features_] = missing_mask + full_mask = X_original.astype(bool) + + imputed_idx, original_idx = 0, 0 + while imputed_idx < len(array_imputed.T): + if not np.all(X_original[:, original_idx]): + X_original[:, original_idx] = array_imputed.T[imputed_idx] + imputed_idx += 1 + original_idx += 1 + else: + original_idx += 1 + + X_original[full_mask] = self.missing_values + return X_original + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.input_tags.allow_nan = is_pandas_na(self.missing_values) or is_scalar_nan( + self.missing_values + ) + return tags + + 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 the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - 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. + """ + check_is_fitted(self, "n_features_in_") + 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. + + Note that this component typically should not be used in a vanilla + :class:`~sklearn.pipeline.Pipeline` consisting of transformers and a + classifier, but rather could be added using a + :class:`~sklearn.pipeline.FeatureUnion` or + :class:`~sklearn.compose.ColumnTransformer`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + missing_values : int, float, str, np.nan or None, default=np.nan + The placeholder for the missing values. All occurrences of + `missing_values` will be imputed. For pandas' dataframes with + nullable integer dtypes with missing values, `missing_values` + should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`. + + features : {'missing-only', 'all'}, default='missing-only' + Whether the imputer mask should represent all or a subset of + features. + + - If `'missing-only'` (default), the imputer mask will only represent + features containing missing values during fit time. + - If `'all'`, the imputer mask will represent all features. + + sparse : bool or 'auto', default='auto' + Whether the imputer mask format should be sparse or dense. + + - If `'auto'` (default), the imputer mask will be of same type as + input. + - If `True`, the imputer mask will be a sparse matrix. + - If `False`, the imputer mask will be a numpy array. + + error_on_new : bool, default=True + If `True`, :meth:`transform` will raise an error when there are + features with missing values that have no missing values in + :meth:`fit`. This is applicable only when `features='missing-only'`. + + Attributes + ---------- + features_ : ndarray of shape (n_missing_features,) or (n_features,) + The features indices which will be returned when calling + :meth:`transform`. They are computed during :meth:`fit`. If + `features='all'`, `features_` is equal to `range(n_features)`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SimpleImputer : Univariate imputation of missing values. + IterativeImputer : Multivariate imputation of missing values. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.impute import MissingIndicator + >>> X1 = np.array([[np.nan, 1, 3], + ... [4, 0, np.nan], + ... [8, 1, 0]]) + >>> X2 = np.array([[5, 1, np.nan], + ... [np.nan, 2, 3], + ... [2, 4, 0]]) + >>> indicator = MissingIndicator() + >>> indicator.fit(X1) + MissingIndicator() + >>> X2_tr = indicator.transform(X2) + >>> X2_tr + array([[False, True], + [ True, False], + [False, False]]) + """ + + _parameter_constraints: dict = { + "missing_values": [MissingValues()], + "features": [StrOptions({"missing-only", "all"})], + "sparse": ["boolean", StrOptions({"auto"})], + "error_on_new": ["boolean"], + } + + def __init__( + self, + *, + missing_values=np.nan, + features="missing-only", + sparse="auto", + error_on_new=True, + ): + self.missing_values = missing_values + self.features = features + self.sparse = sparse + self.error_on_new = error_on_new + + def _get_missing_features_info(self, X): + """Compute the imputer mask and the indices of the features + containing missing values. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The input data with missing values. Note that `X` has been + checked in :meth:`fit` and :meth:`transform` before to call this + function. + + Returns + ------- + imputer_mask : {ndarray, sparse matrix} of shape \ + (n_samples, n_features) + The imputer mask of the original data. + + features_with_missing : ndarray of shape (n_features_with_missing) + The features containing missing values. + """ + if not self._precomputed: + imputer_mask = _get_mask(X, self.missing_values) + else: + imputer_mask = X + + if sp.issparse(X): + imputer_mask.eliminate_zeros() + + if self.features == "missing-only": + # count number of True values in each row. + n_missing = imputer_mask.sum(axis=0) + + if self.sparse is False: + imputer_mask = imputer_mask.toarray() + elif imputer_mask.format == "csr": + imputer_mask = imputer_mask.tocsc() + else: + if not self._precomputed: + imputer_mask = _get_mask(X, self.missing_values) + else: + imputer_mask = X + + if self.features == "missing-only": + n_missing = imputer_mask.sum(axis=0) + + if self.sparse is True: + imputer_mask = sp.csc_matrix(imputer_mask) + + if self.features == "all": + features_indices = np.arange(X.shape[1]) + else: + features_indices = np.flatnonzero(n_missing) + + return imputer_mask, features_indices + + def _validate_input(self, X, in_fit): + if not is_scalar_nan(self.missing_values): + ensure_all_finite = True + else: + ensure_all_finite = "allow-nan" + X = validate_data( + self, + X, + reset=in_fit, + accept_sparse=("csc", "csr"), + dtype=None, + ensure_all_finite=ensure_all_finite, + ) + _check_inputs_dtype(X, self.missing_values) + if X.dtype.kind not in ("i", "u", "f", "O"): + raise ValueError( + "MissingIndicator does not support data with " + "dtype {0}. Please provide either a numeric array" + " (with a floating point or integer dtype) or " + "categorical data represented either as an array " + "with integer dtype or an array of string values " + "with an object dtype.".format(X.dtype) + ) + + if sp.issparse(X) and self.missing_values == 0: + # missing_values = 0 not allowed with sparse data as it would + # force densification + raise ValueError( + "Sparse input with missing_values=0 is " + "not supported. Provide a dense " + "array instead." + ) + + return X + + def _fit(self, X, y=None, precomputed=False): + """Fit the transformer on `X`. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + If `precomputed=True`, then `X` is a mask of the input data. + + precomputed : bool + Whether the input data is a mask. + + Returns + ------- + imputer_mask : {ndarray, sparse matrix} of shape (n_samples, \ + n_features) + The imputer mask of the original data. + """ + if precomputed: + if not (hasattr(X, "dtype") and X.dtype.kind == "b"): + raise ValueError("precomputed is True but the input data is not a mask") + self._precomputed = True + else: + self._precomputed = False + + # Need not validate X again as it would have already been validated + # in the Imputer calling MissingIndicator + if not self._precomputed: + X = self._validate_input(X, in_fit=True) + else: + # only create `n_features_in_` in the precomputed case + _check_n_features(self, X, reset=True) + + self._n_features = X.shape[1] + + missing_features_info = self._get_missing_features_info(X) + self.features_ = missing_features_info[1] + + return missing_features_info[0] + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the transformer on `X`. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Fitted estimator. + """ + self._fit(X, y) + + return self + + def transform(self, X): + """Generate missing values indicator for `X`. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data to complete. + + Returns + ------- + Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) \ + or (n_samples, n_features_with_missing) + The missing indicator for input data. The data type of `Xt` + will be boolean. + """ + check_is_fitted(self) + + # Need not validate X again as it would have already been validated + # in the Imputer calling MissingIndicator + if not self._precomputed: + X = self._validate_input(X, in_fit=False) + else: + if not (hasattr(X, "dtype") and X.dtype.kind == "b"): + raise ValueError("precomputed is True but the input data is not a mask") + + imputer_mask, features = self._get_missing_features_info(X) + + if self.features == "missing-only": + features_diff_fit_trans = np.setdiff1d(features, self.features_) + if self.error_on_new and features_diff_fit_trans.size > 0: + raise ValueError( + "The features {} have missing values " + "in transform but have no missing values " + "in fit.".format(features_diff_fit_trans) + ) + + if self.features_.size < self._n_features: + imputer_mask = imputer_mask[:, self.features_] + + return imputer_mask + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y=None): + """Generate missing values indicator for `X`. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data to complete. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) \ + or (n_samples, n_features_with_missing) + The missing indicator for input data. The data type of `Xt` + will be boolean. + """ + imputer_mask = self._fit(X, y) + + if self.features_.size < self._n_features: + imputer_mask = imputer_mask[:, self.features_] + + 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 the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - 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. + """ + check_is_fitted(self, "n_features_in_") + 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 __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = True + tags.input_tags.string = True + tags.input_tags.sparse = True + tags.transformer_tags.preserves_dtype = [] + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_iterative.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_iterative.py new file mode 100644 index 0000000000000000000000000000000000000000..ddae5373c5460891467d50fd7105473031d957b4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_iterative.py @@ -0,0 +1,1030 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from collections import namedtuple +from numbers import Integral, Real +from time import time + +import numpy as np +from scipy import stats + +from ..base import _fit_context, clone +from ..exceptions import ConvergenceWarning +from ..preprocessing import normalize +from ..utils import _safe_indexing, check_array, check_random_state +from ..utils._indexing import _safe_assign +from ..utils._mask import _get_mask +from ..utils._missing import is_scalar_nan +from ..utils._param_validation import HasMethods, Interval, StrOptions +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + process_routing, +) +from ..utils.validation import ( + FLOAT_DTYPES, + _check_feature_names_in, + _num_samples, + check_is_fitted, + validate_data, +) +from ._base import SimpleImputer, _BaseImputer, _check_inputs_dtype + +_ImputerTriplet = namedtuple( + "_ImputerTriplet", ["feat_idx", "neighbor_feat_idx", "estimator"] +) + + +def _assign_where(X1, X2, cond): + """Assign X2 to X1 where cond is True. + + Parameters + ---------- + X1 : ndarray or dataframe of shape (n_samples, n_features) + Data. + + X2 : ndarray of shape (n_samples, n_features) + Data to be assigned. + + cond : ndarray of shape (n_samples, n_features) + Boolean mask to assign data. + """ + if hasattr(X1, "mask"): # pandas dataframes + X1.mask(cond=cond, other=X2, inplace=True) + else: # ndarrays + X1[cond] = X2[cond] + + +class IterativeImputer(_BaseImputer): + """Multivariate imputer that estimates each feature from all the others. + + A strategy for imputing missing values by modeling each feature with + missing values as a function of other features in a round-robin fashion. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.21 + + .. 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_iterative_imputer`:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_iterative_imputer # noqa + >>> # now you can import normally from sklearn.impute + >>> from sklearn.impute import IterativeImputer + + Parameters + ---------- + estimator : estimator object, default=BayesianRidge() + The estimator to use at each step of the round-robin imputation. + If `sample_posterior=True`, the estimator must support + `return_std` in its `predict` method. + + missing_values : int or np.nan, default=np.nan + The placeholder for the missing values. All occurrences of + `missing_values` will be imputed. For pandas' dataframes with + nullable integer dtypes with missing values, `missing_values` + should be set to `np.nan`, since `pd.NA` will be converted to `np.nan`. + + sample_posterior : bool, default=False + Whether to sample from the (Gaussian) predictive posterior of the + fitted estimator for each imputation. Estimator must support + `return_std` in its `predict` method if set to `True`. Set to + `True` if using `IterativeImputer` for multiple imputations. + + max_iter : int, default=10 + Maximum number of imputation rounds to perform before returning the + imputations computed during the final round. A round is a single + imputation of each feature with missing values. The stopping criterion + is met once `max(abs(X_t - X_{t-1}))/max(abs(X[known_vals])) < tol`, + where `X_t` is `X` at iteration `t`. Note that early stopping is only + applied if `sample_posterior=False`. + + tol : float, default=1e-3 + Tolerance of the stopping condition. + + n_nearest_features : int, default=None + Number of other features to use to estimate the missing values of + each feature column. Nearness between features is measured using + the absolute correlation coefficient between each feature pair (after + initial imputation). To ensure coverage of features throughout the + imputation process, the neighbor features are not necessarily nearest, + but are drawn with probability proportional to correlation for each + imputed target feature. Can provide significant speed-up when the + number of features is huge. If `None`, all features will be used. + + initial_strategy : {'mean', 'median', 'most_frequent', 'constant'}, \ + default='mean' + Which strategy to use to initialize the missing values. Same as the + `strategy` parameter in :class:`~sklearn.impute.SimpleImputer`. + + fill_value : str or numerical value, default=None + When `strategy="constant"`, `fill_value` is used to replace all + occurrences of missing_values. For string or object data types, + `fill_value` must be a string. + If `None`, `fill_value` will be 0 when imputing numerical + data and "missing_value" for strings or object data types. + + .. versionadded:: 1.3 + + imputation_order : {'ascending', 'descending', 'roman', 'arabic', \ + 'random'}, default='ascending' + The order in which the features will be imputed. Possible values: + + - `'ascending'`: From features with fewest missing values to most. + - `'descending'`: From features with most missing values to fewest. + - `'roman'`: Left to right. + - `'arabic'`: Right to left. + - `'random'`: A random order for each round. + + skip_complete : bool, default=False + If `True` then features with missing values during :meth:`transform` + which did not have any missing values during :meth:`fit` will be + imputed with the initial imputation method only. Set to `True` if you + have many features with no missing values at both :meth:`fit` and + :meth:`transform` time to save compute. + + min_value : float or array-like of shape (n_features,), default=-np.inf + Minimum possible imputed value. Broadcast to shape `(n_features,)` if + scalar. If array-like, expects shape `(n_features,)`, one min value for + each feature. The default is `-np.inf`. + + .. versionchanged:: 0.23 + Added support for array-like. + + max_value : float or array-like of shape (n_features,), default=np.inf + Maximum possible imputed value. Broadcast to shape `(n_features,)` if + scalar. If array-like, expects shape `(n_features,)`, one max value for + each feature. The default is `np.inf`. + + .. versionchanged:: 0.23 + Added support for array-like. + + verbose : int, default=0 + Verbosity flag, controls the debug messages that are issued + as functions are evaluated. The higher, the more verbose. Can be 0, 1, + or 2. + + random_state : int, RandomState instance or None, default=None + The seed of the pseudo random number generator to use. Randomizes + selection of estimator features if `n_nearest_features` is not `None`, + the `imputation_order` if `random`, and the sampling from posterior if + `sample_posterior=True`. Use an integer for determinism. + See :term:`the Glossary `. + + add_indicator : bool, default=False + If `True`, a :class:`MissingIndicator` transform will stack onto output + of the imputer's transform. This allows a predictive estimator + to account for missingness despite imputation. If a feature has no + missing values at fit/train time, the feature won't appear on + the missing indicator even if there are missing values at + transform/test time. + + keep_empty_features : bool, default=False + If True, features that consist exclusively of missing values when + `fit` is called are returned in results when `transform` is called. + The imputed value is always `0` except when + `initial_strategy="constant"` in which case `fill_value` will be + used instead. + + .. versionadded:: 1.2 + + Attributes + ---------- + initial_imputer_ : object of type :class:`~sklearn.impute.SimpleImputer` + Imputer used to initialize the missing values. + + imputation_sequence_ : list of tuples + Each tuple has `(feat_idx, neighbor_feat_idx, estimator)`, where + `feat_idx` is the current feature to be imputed, + `neighbor_feat_idx` is the array of other features used to impute the + current feature, and `estimator` is the trained estimator used for + the imputation. Length is `self.n_features_with_missing_ * + self.n_iter_`. + + n_iter_ : int + Number of iteration rounds that occurred. Will be less than + `self.max_iter` if early stopping criterion was reached. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_features_with_missing_ : int + Number of features with missing values. + + indicator_ : :class:`~sklearn.impute.MissingIndicator` + Indicator used to add binary indicators for missing values. + `None` if `add_indicator=False`. + + random_state_ : RandomState instance + RandomState instance that is generated either from a seed, the random + number generator or by `np.random`. + + See Also + -------- + SimpleImputer : Univariate imputer for completing missing values + with simple strategies. + KNNImputer : Multivariate imputer that estimates missing features using + nearest samples. + + Notes + ----- + To support imputation in inductive mode we store each feature's estimator + during the :meth:`fit` phase, and predict without refitting (in order) + during the :meth:`transform` phase. + + Features which contain all missing values at :meth:`fit` are discarded upon + :meth:`transform`. + + Using defaults, the imputer scales in :math:`\\mathcal{O}(knp^3\\min(n,p))` + where :math:`k` = `max_iter`, :math:`n` the number of samples and + :math:`p` the number of features. It thus becomes prohibitively costly when + the number of features increases. Setting + `n_nearest_features << n_features`, `skip_complete=True` or increasing `tol` + can help to reduce its computational cost. + + Depending on the nature of missing values, simple imputers can be + preferable in a prediction context. + + References + ---------- + .. [1] `Stef van Buuren, Karin Groothuis-Oudshoorn (2011). "mice: + Multivariate Imputation by Chained Equations in R". Journal of + Statistical Software 45: 1-67. + `_ + + .. [2] `S. F. Buck, (1960). "A Method of Estimation of Missing Values in + Multivariate Data Suitable for use with an Electronic Computer". + Journal of the Royal Statistical Society 22(2): 302-306. + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.experimental import enable_iterative_imputer + >>> from sklearn.impute import IterativeImputer + >>> imp_mean = IterativeImputer(random_state=0) + >>> imp_mean.fit([[7, 2, 3], [4, np.nan, 6], [10, 5, 9]]) + IterativeImputer(random_state=0) + >>> X = [[np.nan, 2, 3], [4, np.nan, 6], [10, np.nan, 9]] + >>> imp_mean.transform(X) + array([[ 6.9584, 2. , 3. ], + [ 4. , 2.6000, 6. ], + [10. , 4.9999, 9. ]]) + + For a more detailed example see + :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py` or + :ref:`sphx_glr_auto_examples_impute_plot_iterative_imputer_variants_comparison.py`. + """ + + _parameter_constraints: dict = { + **_BaseImputer._parameter_constraints, + "estimator": [None, HasMethods(["fit", "predict"])], + "sample_posterior": ["boolean"], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "n_nearest_features": [None, Interval(Integral, 1, None, closed="left")], + "initial_strategy": [ + StrOptions({"mean", "median", "most_frequent", "constant"}) + ], + "fill_value": "no_validation", # any object is valid + "imputation_order": [ + StrOptions({"ascending", "descending", "roman", "arabic", "random"}) + ], + "skip_complete": ["boolean"], + "min_value": [None, Interval(Real, None, None, closed="both"), "array-like"], + "max_value": [None, Interval(Real, None, None, closed="both"), "array-like"], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + estimator=None, + *, + missing_values=np.nan, + sample_posterior=False, + max_iter=10, + tol=1e-3, + n_nearest_features=None, + initial_strategy="mean", + fill_value=None, + imputation_order="ascending", + skip_complete=False, + min_value=-np.inf, + max_value=np.inf, + verbose=0, + random_state=None, + add_indicator=False, + keep_empty_features=False, + ): + super().__init__( + missing_values=missing_values, + add_indicator=add_indicator, + keep_empty_features=keep_empty_features, + ) + + self.estimator = estimator + self.sample_posterior = sample_posterior + self.max_iter = max_iter + self.tol = tol + self.n_nearest_features = n_nearest_features + self.initial_strategy = initial_strategy + self.fill_value = fill_value + self.imputation_order = imputation_order + self.skip_complete = skip_complete + self.min_value = min_value + self.max_value = max_value + self.verbose = verbose + self.random_state = random_state + + def _impute_one_feature( + self, + X_filled, + mask_missing_values, + feat_idx, + neighbor_feat_idx, + estimator=None, + fit_mode=True, + params=None, + ): + """Impute a single feature from the others provided. + + This function predicts the missing values of one of the features using + the current estimates of all the other features. The `estimator` must + support `return_std=True` in its `predict` method for this function + to work. + + Parameters + ---------- + X_filled : ndarray + Input data with the most recent imputations. + + mask_missing_values : ndarray + Input data's missing indicator matrix. + + feat_idx : int + Index of the feature currently being imputed. + + neighbor_feat_idx : ndarray + Indices of the features to be used in imputing `feat_idx`. + + estimator : object + The estimator to use at this step of the round-robin imputation. + If `sample_posterior=True`, the estimator must support + `return_std` in its `predict` method. + If None, it will be cloned from self._estimator. + + fit_mode : boolean, default=True + Whether to fit and predict with the estimator or just predict. + + params : dict + Additional params routed to the individual estimator. + + Returns + ------- + X_filled : ndarray + Input data with `X_filled[missing_row_mask, feat_idx]` updated. + + estimator : estimator with sklearn API + The fitted estimator used to impute + `X_filled[missing_row_mask, feat_idx]`. + """ + if estimator is None and fit_mode is False: + raise ValueError( + "If fit_mode is False, then an already-fitted " + "estimator should be passed in." + ) + + if estimator is None: + estimator = clone(self._estimator) + + missing_row_mask = mask_missing_values[:, feat_idx] + if fit_mode: + X_train = _safe_indexing( + _safe_indexing(X_filled, neighbor_feat_idx, axis=1), + ~missing_row_mask, + axis=0, + ) + y_train = _safe_indexing( + _safe_indexing(X_filled, feat_idx, axis=1), + ~missing_row_mask, + axis=0, + ) + estimator.fit(X_train, y_train, **params) + + # if no missing values, don't predict + if np.sum(missing_row_mask) == 0: + return X_filled, estimator + + # get posterior samples if there is at least one missing value + X_test = _safe_indexing( + _safe_indexing(X_filled, neighbor_feat_idx, axis=1), + missing_row_mask, + axis=0, + ) + if self.sample_posterior: + mus, sigmas = estimator.predict(X_test, return_std=True) + imputed_values = np.zeros(mus.shape, dtype=X_filled.dtype) + # two types of problems: (1) non-positive sigmas + # (2) mus outside legal range of min_value and max_value + # (results in inf sample) + positive_sigmas = sigmas > 0 + imputed_values[~positive_sigmas] = mus[~positive_sigmas] + mus_too_low = mus < self._min_value[feat_idx] + imputed_values[mus_too_low] = self._min_value[feat_idx] + mus_too_high = mus > self._max_value[feat_idx] + imputed_values[mus_too_high] = self._max_value[feat_idx] + # the rest can be sampled without statistical issues + inrange_mask = positive_sigmas & ~mus_too_low & ~mus_too_high + mus = mus[inrange_mask] + sigmas = sigmas[inrange_mask] + a = (self._min_value[feat_idx] - mus) / sigmas + b = (self._max_value[feat_idx] - mus) / sigmas + + truncated_normal = stats.truncnorm(a=a, b=b, loc=mus, scale=sigmas) + imputed_values[inrange_mask] = truncated_normal.rvs( + random_state=self.random_state_ + ) + else: + imputed_values = estimator.predict(X_test) + imputed_values = np.clip( + imputed_values, self._min_value[feat_idx], self._max_value[feat_idx] + ) + + # update the feature + _safe_assign( + X_filled, + imputed_values, + row_indexer=missing_row_mask, + column_indexer=feat_idx, + ) + return X_filled, estimator + + def _get_neighbor_feat_idx(self, n_features, feat_idx, abs_corr_mat): + """Get a list of other features to predict `feat_idx`. + + If `self.n_nearest_features` is less than or equal to the total + number of features, then use a probability proportional to the absolute + correlation between `feat_idx` and each other feature to randomly + choose a subsample of the other features (without replacement). + + Parameters + ---------- + n_features : int + Number of features in `X`. + + feat_idx : int + Index of the feature currently being imputed. + + abs_corr_mat : ndarray, shape (n_features, n_features) + Absolute correlation matrix of `X`. The diagonal has been zeroed + out and each feature has been normalized to sum to 1. Can be None. + + Returns + ------- + neighbor_feat_idx : array-like + The features to use to impute `feat_idx`. + """ + if self.n_nearest_features is not None and self.n_nearest_features < n_features: + p = abs_corr_mat[:, feat_idx] + neighbor_feat_idx = self.random_state_.choice( + np.arange(n_features), self.n_nearest_features, replace=False, p=p + ) + else: + inds_left = np.arange(feat_idx) + inds_right = np.arange(feat_idx + 1, n_features) + neighbor_feat_idx = np.concatenate((inds_left, inds_right)) + return neighbor_feat_idx + + def _get_ordered_idx(self, mask_missing_values): + """Decide in what order we will update the features. + + As a homage to the MICE R package, we will have 4 main options of + how to order the updates, and use a random order if anything else + is specified. + + Also, this function skips features which have no missing values. + + Parameters + ---------- + mask_missing_values : array-like, shape (n_samples, n_features) + Input data's missing indicator matrix, where `n_samples` is the + number of samples and `n_features` is the number of features. + + Returns + ------- + ordered_idx : ndarray, shape (n_features,) + The order in which to impute the features. + """ + frac_of_missing_values = mask_missing_values.mean(axis=0) + if self.skip_complete: + missing_values_idx = np.flatnonzero(frac_of_missing_values) + else: + missing_values_idx = np.arange(np.shape(frac_of_missing_values)[0]) + if self.imputation_order == "roman": + ordered_idx = missing_values_idx + elif self.imputation_order == "arabic": + ordered_idx = missing_values_idx[::-1] + elif self.imputation_order == "ascending": + n = len(frac_of_missing_values) - len(missing_values_idx) + ordered_idx = np.argsort(frac_of_missing_values, kind="mergesort")[n:] + elif self.imputation_order == "descending": + n = len(frac_of_missing_values) - len(missing_values_idx) + ordered_idx = np.argsort(frac_of_missing_values, kind="mergesort")[n:][::-1] + elif self.imputation_order == "random": + ordered_idx = missing_values_idx + self.random_state_.shuffle(ordered_idx) + return ordered_idx + + def _get_abs_corr_mat(self, X_filled, tolerance=1e-6): + """Get absolute correlation matrix between features. + + Parameters + ---------- + X_filled : ndarray, shape (n_samples, n_features) + Input data with the most recent imputations. + + tolerance : float, default=1e-6 + `abs_corr_mat` can have nans, which will be replaced + with `tolerance`. + + Returns + ------- + abs_corr_mat : ndarray, shape (n_features, n_features) + Absolute correlation matrix of `X` at the beginning of the + current round. The diagonal has been zeroed out and each feature's + absolute correlations with all others have been normalized to sum + to 1. + """ + n_features = X_filled.shape[1] + if self.n_nearest_features is None or self.n_nearest_features >= n_features: + return None + with np.errstate(invalid="ignore"): + # if a feature in the neighborhood has only a single value + # (e.g., categorical feature), the std. dev. will be null and + # np.corrcoef will raise a warning due to a division by zero + abs_corr_mat = np.abs(np.corrcoef(X_filled.T)) + # np.corrcoef is not defined for features with zero std + abs_corr_mat[np.isnan(abs_corr_mat)] = tolerance + # ensures exploration, i.e. at least some probability of sampling + np.clip(abs_corr_mat, tolerance, None, out=abs_corr_mat) + # features are not their own neighbors + np.fill_diagonal(abs_corr_mat, 0) + # needs to sum to 1 for np.random.choice sampling + abs_corr_mat = normalize(abs_corr_mat, norm="l1", axis=0, copy=False) + return abs_corr_mat + + def _initial_imputation(self, X, in_fit=False): + """Perform initial imputation for input `X`. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + in_fit : bool, default=False + Whether function is called in :meth:`fit`. + + Returns + ------- + Xt : ndarray of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + X_filled : ndarray of shape (n_samples, n_features) + Input data with the most recent imputations. + + mask_missing_values : ndarray of shape (n_samples, n_features) + Input data's missing indicator matrix, where `n_samples` is the + number of samples and `n_features` is the number of features, + masked by non-missing features. + + X_missing_mask : ndarray, shape (n_samples, n_features) + Input data's mask matrix indicating missing datapoints, where + `n_samples` is the number of samples and `n_features` is the + number of features. + """ + if is_scalar_nan(self.missing_values): + ensure_all_finite = "allow-nan" + else: + ensure_all_finite = True + + X = validate_data( + self, + X, + dtype=FLOAT_DTYPES, + order="F", + reset=in_fit, + ensure_all_finite=ensure_all_finite, + ) + _check_inputs_dtype(X, self.missing_values) + + X_missing_mask = _get_mask(X, self.missing_values) + mask_missing_values = X_missing_mask.copy() + + # TODO (1.8): remove this once the deprecation is removed. In the meantime, + # we need to catch the warning to avoid false positives. + catch_warning = ( + self.initial_strategy == "constant" and not self.keep_empty_features + ) + + if self.initial_imputer_ is None: + self.initial_imputer_ = SimpleImputer( + missing_values=self.missing_values, + strategy=self.initial_strategy, + fill_value=self.fill_value, + keep_empty_features=self.keep_empty_features, + ).set_output(transform="default") + + # TODO (1.8): remove this once the deprecation is removed to keep only + # the code in the else case. + if catch_warning: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + X_filled = self.initial_imputer_.fit_transform(X) + else: + X_filled = self.initial_imputer_.fit_transform(X) + else: + # TODO (1.8): remove this once the deprecation is removed to keep only + # the code in the else case. + if catch_warning: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + X_filled = self.initial_imputer_.transform(X) + else: + X_filled = self.initial_imputer_.transform(X) + + if in_fit: + self._is_empty_feature = np.all(mask_missing_values, axis=0) + + if not self.keep_empty_features: + # drop empty features + Xt = X[:, ~self._is_empty_feature] + mask_missing_values = mask_missing_values[:, ~self._is_empty_feature] + + if self.initial_imputer_.get_params()["strategy"] == "constant": + # The constant strategy has a specific behavior and preserve empty + # features even with ``keep_empty_features=False``. We need to drop + # the column for consistency. + # TODO (1.8): remove this `if` branch once the following issue is + # addressed: + # https://github.com/scikit-learn/scikit-learn/issues/29827 + X_filled = X_filled[:, ~self._is_empty_feature] + + else: + # mark empty features as not missing and keep the original + # imputation + mask_missing_values[:, self._is_empty_feature] = False + Xt = X + Xt[:, self._is_empty_feature] = X_filled[:, self._is_empty_feature] + + return Xt, X_filled, mask_missing_values, X_missing_mask + + @staticmethod + def _validate_limit( + limit, limit_type, n_features, is_empty_feature, keep_empty_feature + ): + """Validate the limits (min/max) of the feature values. + + Converts scalar min/max limits to vectors of shape `(n_features,)`. + + Parameters + ---------- + limit: scalar or array-like + The user-specified limit (i.e, min_value or max_value). + limit_type: {'max', 'min'} + Type of limit to validate. + n_features: int + Number of features in the dataset. + is_empty_feature: ndarray, shape (n_features, ) + Mask array indicating empty feature imputer has seen during fit. + keep_empty_feature: bool + If False, remove empty-feature indices from the limit. + + Returns + ------- + limit: ndarray, shape(n_features,) + Array of limits, one for each feature. + """ + n_features_in = _num_samples(is_empty_feature) + if ( + limit is not None + and not np.isscalar(limit) + and _num_samples(limit) != n_features_in + ): + raise ValueError( + f"'{limit_type}_value' should be of shape ({n_features_in},) when an" + f" array-like is provided. Got {len(limit)}, instead." + ) + + limit_bound = np.inf if limit_type == "max" else -np.inf + limit = limit_bound if limit is None else limit + if np.isscalar(limit): + limit = np.full(n_features, limit) + limit = check_array(limit, ensure_all_finite=False, copy=False, ensure_2d=False) + + # Make sure to remove the empty feature elements from the bounds + if not keep_empty_feature and len(limit) == len(is_empty_feature): + limit = limit[~is_empty_feature] + + return limit + + @_fit_context( + # IterativeImputer.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit_transform(self, X, y=None, **params): + """Fit the imputer on `X` and return the transformed `X`. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + **params : dict + Parameters routed to the `fit` method of the sub-estimator via the + metadata routing API. + + .. versionadded:: 1.5 + Only available if + `sklearn.set_config(enable_metadata_routing=True)` is set. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + Xt : array-like, shape (n_samples, n_features) + The imputed input data. + """ + _raise_for_params(params, self, "fit") + + routed_params = process_routing( + self, + "fit", + **params, + ) + + self.random_state_ = getattr( + self, "random_state_", check_random_state(self.random_state) + ) + + if self.estimator is None: + from ..linear_model import BayesianRidge + + self._estimator = BayesianRidge() + else: + self._estimator = clone(self.estimator) + + self.imputation_sequence_ = [] + + self.initial_imputer_ = None + + X, Xt, mask_missing_values, complete_mask = self._initial_imputation( + X, in_fit=True + ) + + super()._fit_indicator(complete_mask) + X_indicator = super()._transform_indicator(complete_mask) + + if self.max_iter == 0 or np.all(mask_missing_values): + self.n_iter_ = 0 + return super()._concatenate_indicator(Xt, X_indicator) + + # Edge case: a single feature, we return the initial imputation. + if Xt.shape[1] == 1: + self.n_iter_ = 0 + return super()._concatenate_indicator(Xt, X_indicator) + + self._min_value = self._validate_limit( + self.min_value, + "min", + X.shape[1], + self._is_empty_feature, + self.keep_empty_features, + ) + self._max_value = self._validate_limit( + self.max_value, + "max", + X.shape[1], + self._is_empty_feature, + self.keep_empty_features, + ) + + if not np.all(np.greater(self._max_value, self._min_value)): + raise ValueError("One (or more) features have min_value >= max_value.") + + # order in which to impute + # note this is probably too slow for large feature data (d > 100000) + # and a better way would be good. + # see: https://goo.gl/KyCNwj and subsequent comments + ordered_idx = self._get_ordered_idx(mask_missing_values) + self.n_features_with_missing_ = len(ordered_idx) + + abs_corr_mat = self._get_abs_corr_mat(Xt) + + n_samples, n_features = Xt.shape + if self.verbose > 0: + print("[IterativeImputer] Completing matrix with shape %s" % (X.shape,)) + start_t = time() + if not self.sample_posterior: + Xt_previous = Xt.copy() + normalized_tol = self.tol * np.max(np.abs(X[~mask_missing_values])) + for self.n_iter_ in range(1, self.max_iter + 1): + if self.imputation_order == "random": + ordered_idx = self._get_ordered_idx(mask_missing_values) + + for feat_idx in ordered_idx: + neighbor_feat_idx = self._get_neighbor_feat_idx( + n_features, feat_idx, abs_corr_mat + ) + Xt, estimator = self._impute_one_feature( + Xt, + mask_missing_values, + feat_idx, + neighbor_feat_idx, + estimator=None, + fit_mode=True, + params=routed_params.estimator.fit, + ) + estimator_triplet = _ImputerTriplet( + feat_idx, neighbor_feat_idx, estimator + ) + self.imputation_sequence_.append(estimator_triplet) + + if self.verbose > 1: + print( + "[IterativeImputer] Ending imputation round " + "%d/%d, elapsed time %0.2f" + % (self.n_iter_, self.max_iter, time() - start_t) + ) + + if not self.sample_posterior: + inf_norm = np.linalg.norm(Xt - Xt_previous, ord=np.inf, axis=None) + if self.verbose > 0: + print( + "[IterativeImputer] Change: {}, scaled tolerance: {} ".format( + inf_norm, normalized_tol + ) + ) + if inf_norm < normalized_tol: + if self.verbose > 0: + print("[IterativeImputer] Early stopping criterion reached.") + break + Xt_previous = Xt.copy() + else: + if not self.sample_posterior: + warnings.warn( + "[IterativeImputer] Early stopping criterion not reached.", + ConvergenceWarning, + ) + _assign_where(Xt, X, cond=~mask_missing_values) + + return super()._concatenate_indicator(Xt, X_indicator) + + def transform(self, X): + """Impute all missing values in `X`. + + Note that this is stochastic, and that if `random_state` is not fixed, + repeated calls, or permuted input, results will differ. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data to complete. + + Returns + ------- + Xt : array-like, shape (n_samples, n_features) + The imputed input data. + """ + check_is_fitted(self) + + X, Xt, mask_missing_values, complete_mask = self._initial_imputation( + X, in_fit=False + ) + + X_indicator = super()._transform_indicator(complete_mask) + + if self.n_iter_ == 0 or np.all(mask_missing_values): + return super()._concatenate_indicator(Xt, X_indicator) + + imputations_per_round = len(self.imputation_sequence_) // self.n_iter_ + i_rnd = 0 + if self.verbose > 0: + print("[IterativeImputer] Completing matrix with shape %s" % (X.shape,)) + start_t = time() + for it, estimator_triplet in enumerate(self.imputation_sequence_): + Xt, _ = self._impute_one_feature( + Xt, + mask_missing_values, + estimator_triplet.feat_idx, + estimator_triplet.neighbor_feat_idx, + estimator=estimator_triplet.estimator, + fit_mode=False, + ) + if not (it + 1) % imputations_per_round: + if self.verbose > 1: + print( + "[IterativeImputer] Ending imputation round " + "%d/%d, elapsed time %0.2f" + % (i_rnd + 1, self.n_iter_, time() - start_t) + ) + i_rnd += 1 + + _assign_where(Xt, X, cond=~mask_missing_values) + + return super()._concatenate_indicator(Xt, X_indicator) + + def fit(self, X, y=None, **fit_params): + """Fit the imputer on `X` and return self. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + **fit_params : dict + Parameters routed to the `fit` method of the sub-estimator via the + metadata routing API. + + .. versionadded:: 1.5 + Only available if + `sklearn.set_config(enable_metadata_routing=True)` is set. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + self : object + Fitted estimator. + """ + self.fit_transform(X, **fit_params) + 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 the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - 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. + """ + check_is_fitted(self, "n_features_in_") + 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) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.5 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + estimator=self.estimator, + method_mapping=MethodMapping().add(callee="fit", caller="fit"), + ) + return router diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_knn.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_knn.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7ef06edc256372890cbd9cb85123239b37e3e9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/_knn.py @@ -0,0 +1,411 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral + +import numpy as np + +from ..base import _fit_context +from ..metrics import pairwise_distances_chunked +from ..metrics.pairwise import _NAN_METRICS +from ..neighbors._base import _get_weights +from ..utils._mask import _get_mask +from ..utils._missing import is_scalar_nan +from ..utils._param_validation import Hidden, Interval, StrOptions +from ..utils.validation import ( + FLOAT_DTYPES, + _check_feature_names_in, + check_is_fitted, + validate_data, +) +from ._base import _BaseImputer + + +class KNNImputer(_BaseImputer): + """Imputation for completing missing values using k-Nearest Neighbors. + + Each sample's missing values are imputed using the mean value from + `n_neighbors` nearest neighbors found in the training set. Two samples are + close if the features that neither is missing are close. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.22 + + Parameters + ---------- + missing_values : int, float, str, np.nan or None, default=np.nan + The placeholder for the missing values. All occurrences of + `missing_values` will be imputed. For pandas' dataframes with + nullable integer dtypes with missing values, `missing_values` + should be set to np.nan, since `pd.NA` will be converted to np.nan. + + n_neighbors : int, default=5 + Number of neighboring samples to use for imputation. + + weights : {'uniform', 'distance'} or callable, default='uniform' + Weight function used in prediction. Possible values: + + - 'uniform' : uniform weights. All points in each neighborhood are + weighted equally. + - 'distance' : weight points by the inverse of their distance. + in this case, closer neighbors of a query point will have a + greater influence than neighbors which are further away. + - callable : a user-defined function which accepts an + array of distances, and returns an array of the same shape + containing the weights. + + metric : {'nan_euclidean'} or callable, default='nan_euclidean' + Distance metric for searching neighbors. Possible values: + + - 'nan_euclidean' + - callable : a user-defined function which conforms to the definition + of ``func_metric(x, y, *, missing_values=np.nan)``. `x` and `y` + corresponds to a row (i.e. 1-D arrays) of `X` and `Y`, respectively. + The callable should returns a scalar distance value. + + copy : bool, default=True + If True, a copy of X will be created. If False, imputation will + be done in-place whenever possible. + + add_indicator : bool, default=False + If True, a :class:`MissingIndicator` transform will stack onto the + output of the imputer's transform. This allows a predictive estimator + to account for missingness despite imputation. If a feature has no + missing values at fit/train time, the feature won't appear on the + missing indicator even if there are missing values at transform/test + time. + + keep_empty_features : bool, default=False + If True, features that consist exclusively of missing values when + `fit` is called are returned in results when `transform` is called. + The imputed value is always `0`. + + .. versionadded:: 1.2 + + Attributes + ---------- + indicator_ : :class:`~sklearn.impute.MissingIndicator` + Indicator used to add binary indicators for missing values. + ``None`` if add_indicator is False. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + SimpleImputer : Univariate imputer for completing missing values + with simple strategies. + IterativeImputer : Multivariate imputer that estimates values to impute for + each feature with missing values from all the others. + + References + ---------- + * `Olga Troyanskaya, Michael Cantor, Gavin Sherlock, Pat Brown, Trevor + Hastie, Robert Tibshirani, David Botstein and Russ B. Altman, Missing + value estimation methods for DNA microarrays, BIOINFORMATICS Vol. 17 + no. 6, 2001 Pages 520-525. + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.impute import KNNImputer + >>> X = [[1, 2, np.nan], [3, 4, 3], [np.nan, 6, 5], [8, 8, 7]] + >>> imputer = KNNImputer(n_neighbors=2) + >>> imputer.fit_transform(X) + array([[1. , 2. , 4. ], + [3. , 4. , 3. ], + [5.5, 6. , 5. ], + [8. , 8. , 7. ]]) + + For a more detailed example see + :ref:`sphx_glr_auto_examples_impute_plot_missing_values.py`. + """ + + _parameter_constraints: dict = { + **_BaseImputer._parameter_constraints, + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "weights": [StrOptions({"uniform", "distance"}), callable, Hidden(None)], + "metric": [StrOptions(set(_NAN_METRICS)), callable], + "copy": ["boolean"], + } + + def __init__( + self, + *, + missing_values=np.nan, + n_neighbors=5, + weights="uniform", + metric="nan_euclidean", + copy=True, + add_indicator=False, + keep_empty_features=False, + ): + super().__init__( + missing_values=missing_values, + add_indicator=add_indicator, + keep_empty_features=keep_empty_features, + ) + self.n_neighbors = n_neighbors + self.weights = weights + self.metric = metric + self.copy = copy + + def _calc_impute(self, dist_pot_donors, n_neighbors, fit_X_col, mask_fit_X_col): + """Helper function to impute a single column. + + Parameters + ---------- + dist_pot_donors : ndarray of shape (n_receivers, n_potential_donors) + Distance matrix between the receivers and potential donors from + training set. There must be at least one non-nan distance between + a receiver and a potential donor. + + n_neighbors : int + Number of neighbors to consider. + + fit_X_col : ndarray of shape (n_potential_donors,) + Column of potential donors from training set. + + mask_fit_X_col : ndarray of shape (n_potential_donors,) + Missing mask for fit_X_col. + + Returns + ------- + imputed_values: ndarray of shape (n_receivers,) + Imputed values for receiver. + """ + # Get donors + donors_idx = np.argpartition(dist_pot_donors, n_neighbors - 1, axis=1)[ + :, :n_neighbors + ] + + # Get weight matrix from distance matrix + donors_dist = dist_pot_donors[ + np.arange(donors_idx.shape[0])[:, None], donors_idx + ] + + weight_matrix = _get_weights(donors_dist, self.weights) + + # fill nans with zeros + if weight_matrix is not None: + weight_matrix[np.isnan(weight_matrix)] = 0.0 + else: + weight_matrix = np.ones_like(donors_dist) + weight_matrix[np.isnan(donors_dist)] = 0.0 + + # Retrieve donor values and calculate kNN average + donors = fit_X_col.take(donors_idx) + donors_mask = mask_fit_X_col.take(donors_idx) + donors = np.ma.array(donors, mask=donors_mask) + + return np.ma.average(donors, axis=1, weights=weight_matrix).data + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the imputer on X. + + Parameters + ---------- + X : array-like shape of (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + The fitted `KNNImputer` class instance. + """ + # Check data integrity and calling arguments + if not is_scalar_nan(self.missing_values): + ensure_all_finite = True + else: + ensure_all_finite = "allow-nan" + + X = validate_data( + self, + X, + accept_sparse=False, + dtype=FLOAT_DTYPES, + ensure_all_finite=ensure_all_finite, + copy=self.copy, + ) + + 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) + + return self + + def transform(self, X): + """Impute all missing values in X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data to complete. + + Returns + ------- + X : array-like of shape (n_samples, n_output_features) + The imputed dataset. `n_output_features` is the number of features + that is not always missing during `fit`. + """ + + check_is_fitted(self) + if not is_scalar_nan(self.missing_values): + ensure_all_finite = True + else: + ensure_all_finite = "allow-nan" + X = validate_data( + self, + X, + accept_sparse=False, + dtype=FLOAT_DTYPES, + force_writeable=True, + ensure_all_finite=ensure_all_finite, + copy=self.copy, + reset=False, + ) + + mask = _get_mask(X, self.missing_values) + mask_fit_X = self._mask_fit_X + valid_mask = self._valid_mask + + X_indicator = super()._transform_indicator(mask) + + # Removes columns where the training data is all nan + if not np.any(mask[:, valid_mask]): + # No missing values in X + if self.keep_empty_features: + Xc = X + Xc[:, ~valid_mask] = 0 + else: + Xc = X[:, valid_mask] + + # Even if there are no missing values in X, we still concatenate Xc + # with the missing value indicator matrix, X_indicator. + # This is to ensure that the output maintains consistency in terms + # of columns, regardless of whether missing values exist in X or not. + return super()._concatenate_indicator(Xc, X_indicator) + + row_missing_idx = np.flatnonzero(mask[:, valid_mask].any(axis=1)) + + non_missing_fix_X = np.logical_not(mask_fit_X) + + # Maps from indices from X to indices in dist matrix + dist_idx_map = np.zeros(X.shape[0], dtype=int) + dist_idx_map[row_missing_idx] = np.arange(row_missing_idx.shape[0]) + + def process_chunk(dist_chunk, start): + row_missing_chunk = row_missing_idx[start : start + len(dist_chunk)] + + # Find and impute missing by column + for col in range(X.shape[1]): + if not valid_mask[col]: + # column was all missing during training + continue + + col_mask = mask[row_missing_chunk, col] + if not np.any(col_mask): + # column has no missing values + continue + + (potential_donors_idx,) = np.nonzero(non_missing_fix_X[:, col]) + + # receivers_idx are indices in X + receivers_idx = row_missing_chunk[np.flatnonzero(col_mask)] + + # distances for samples that needed imputation for column + dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][ + :, potential_donors_idx + ] + + # receivers with all nan distances impute with mean + all_nan_dist_mask = np.isnan(dist_subset).all(axis=1) + all_nan_receivers_idx = receivers_idx[all_nan_dist_mask] + + if all_nan_receivers_idx.size: + col_mean = np.ma.array( + self._fit_X[:, col], mask=mask_fit_X[:, col] + ).mean() + X[all_nan_receivers_idx, col] = col_mean + + if len(all_nan_receivers_idx) == len(receivers_idx): + # all receivers imputed with mean + continue + + # receivers with at least one defined distance + receivers_idx = receivers_idx[~all_nan_dist_mask] + dist_subset = dist_chunk[dist_idx_map[receivers_idx] - start][ + :, potential_donors_idx + ] + + n_neighbors = min(self.n_neighbors, len(potential_donors_idx)) + value = self._calc_impute( + dist_subset, + n_neighbors, + self._fit_X[potential_donors_idx, col], + mask_fit_X[potential_donors_idx, col], + ) + X[receivers_idx, col] = value + + # process in fixed-memory chunks + gen = pairwise_distances_chunked( + X[row_missing_idx, :], + self._fit_X, + metric=self.metric, + missing_values=self.missing_values, + ensure_all_finite=ensure_all_finite, + reduce_func=process_chunk, + ) + for chunk in gen: + # process_chunk modifies X in place. No return value. + pass + + if self.keep_empty_features: + Xc = X + Xc[:, ~valid_mask] = 0 + else: + Xc = X[:, valid_mask] + + return super()._concatenate_indicator(Xc, 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 the following input feature names are generated: + `["x0", "x1", ..., "x(n_features_in_ - 1)"]`. + - 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. + """ + check_is_fitted(self, "n_features_in_") + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..0c1bd83f7ca9ea8adde76940e2f7fdd86d89ea5c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_base.py @@ -0,0 +1,107 @@ +import numpy as np +import pytest + +from sklearn.impute._base import _BaseImputer +from sklearn.impute._iterative import _assign_where +from sklearn.utils._mask import _get_mask +from sklearn.utils._testing import _convert_container, assert_allclose + + +@pytest.fixture +def data(): + X = np.random.randn(10, 2) + X[::2] = np.nan + return X + + +class NoFitIndicatorImputer(_BaseImputer): + def fit(self, X, y=None): + return self + + def transform(self, X, y=None): + return self._concatenate_indicator(X, self._transform_indicator(X)) + + +class NoTransformIndicatorImputer(_BaseImputer): + def fit(self, X, y=None): + mask = _get_mask(X, value_to_mask=np.nan) + super()._fit_indicator(mask) + return self + + def transform(self, X, y=None): + return self._concatenate_indicator(X, None) + + +class NoPrecomputedMaskFit(_BaseImputer): + def fit(self, X, y=None): + self._fit_indicator(X) + return self + + def transform(self, X): + return self._concatenate_indicator(X, self._transform_indicator(X)) + + +class NoPrecomputedMaskTransform(_BaseImputer): + def fit(self, X, y=None): + mask = _get_mask(X, value_to_mask=np.nan) + self._fit_indicator(mask) + return self + + def transform(self, X): + return self._concatenate_indicator(X, self._transform_indicator(X)) + + +def test_base_imputer_not_fit(data): + imputer = NoFitIndicatorImputer(add_indicator=True) + err_msg = "Make sure to call _fit_indicator before _transform_indicator" + with pytest.raises(ValueError, match=err_msg): + imputer.fit(data).transform(data) + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(data) + + +def test_base_imputer_not_transform(data): + imputer = NoTransformIndicatorImputer(add_indicator=True) + err_msg = ( + "Call _fit_indicator and _transform_indicator in the imputer implementation" + ) + with pytest.raises(ValueError, match=err_msg): + imputer.fit(data).transform(data) + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(data) + + +def test_base_no_precomputed_mask_fit(data): + imputer = NoPrecomputedMaskFit(add_indicator=True) + err_msg = "precomputed is True but the input data is not a mask" + with pytest.raises(ValueError, match=err_msg): + imputer.fit(data) + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(data) + + +def test_base_no_precomputed_mask_transform(data): + imputer = NoPrecomputedMaskTransform(add_indicator=True) + err_msg = "precomputed is True but the input data is not a mask" + imputer.fit(data) + with pytest.raises(ValueError, match=err_msg): + imputer.transform(data) + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(data) + + +@pytest.mark.parametrize("X1_type", ["array", "dataframe"]) +def test_assign_where(X1_type): + """Check the behaviour of the private helpers `_assign_where`.""" + rng = np.random.RandomState(0) + + n_samples, n_features = 10, 5 + X1 = _convert_container(rng.randn(n_samples, n_features), constructor_name=X1_type) + X2 = rng.randn(n_samples, n_features) + mask = rng.randint(0, 2, size=(n_samples, n_features)).astype(bool) + + _assign_where(X1, X2, mask) + + if X1_type == "dataframe": + X1 = X1.to_numpy() + assert_allclose(X1[mask], X2[mask]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..afebc96ac035c4945c4084dc968323a602072066 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_common.py @@ -0,0 +1,220 @@ +import numpy as np +import pytest + +from sklearn.experimental import enable_iterative_imputer # noqa: F401 +from sklearn.impute import IterativeImputer, KNNImputer, SimpleImputer +from sklearn.utils._testing import ( + assert_allclose, + assert_allclose_dense_sparse, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +def imputers(): + return [IterativeImputer(tol=0.1), KNNImputer(), SimpleImputer()] + + +def sparse_imputers(): + return [SimpleImputer()] + + +# ConvergenceWarning will be raised by the IterativeImputer +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +def test_imputation_missing_value_in_test_array(imputer): + # [Non Regression Test for issue #13968] Missing value in test set should + # not throw an error and return a finite dataset + train = [[1], [2]] + test = [[3], [np.nan]] + imputer.set_params(add_indicator=True) + imputer.fit(train).transform(test) + + +# ConvergenceWarning will be raised by the IterativeImputer +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize("marker", [np.nan, -1, 0]) +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +def test_imputers_add_indicator(marker, imputer): + X = np.array( + [ + [marker, 1, 5, marker, 1], + [2, marker, 1, marker, 2], + [6, 3, marker, marker, 3], + [1, 2, 9, marker, 4], + ] + ) + X_true_indicator = np.array( + [ + [1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0], + ] + ) + imputer.set_params(missing_values=marker, add_indicator=True) + + X_trans = imputer.fit_transform(X) + assert_allclose(X_trans[:, -4:], X_true_indicator) + assert_array_equal(imputer.indicator_.features_, np.array([0, 1, 2, 3])) + + imputer.set_params(add_indicator=False) + X_trans_no_indicator = imputer.fit_transform(X) + assert_allclose(X_trans[:, :-4], X_trans_no_indicator) + + +# ConvergenceWarning will be raised by the IterativeImputer +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize("marker", [np.nan, -1]) +@pytest.mark.parametrize( + "imputer", sparse_imputers(), ids=lambda x: x.__class__.__name__ +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_imputers_add_indicator_sparse(imputer, marker, csr_container): + X = csr_container( + [ + [marker, 1, 5, marker, 1], + [2, marker, 1, marker, 2], + [6, 3, marker, marker, 3], + [1, 2, 9, marker, 4], + ] + ) + X_true_indicator = csr_container( + [ + [1.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 1.0], + [0.0, 0.0, 1.0, 1.0], + [0.0, 0.0, 0.0, 1.0], + ] + ) + imputer.set_params(missing_values=marker, add_indicator=True) + + X_trans = imputer.fit_transform(X) + assert_allclose_dense_sparse(X_trans[:, -4:], X_true_indicator) + assert_array_equal(imputer.indicator_.features_, np.array([0, 1, 2, 3])) + + imputer.set_params(add_indicator=False) + X_trans_no_indicator = imputer.fit_transform(X) + assert_allclose_dense_sparse(X_trans[:, :-4], X_trans_no_indicator) + + +# ConvergenceWarning will be raised by the IterativeImputer +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +@pytest.mark.parametrize("add_indicator", [True, False]) +def test_imputers_pandas_na_integer_array_support(imputer, add_indicator): + # Test pandas IntegerArray with pd.NA + pd = pytest.importorskip("pandas") + marker = np.nan + imputer = imputer.set_params(add_indicator=add_indicator, missing_values=marker) + + X = np.array( + [ + [marker, 1, 5, marker, 1], + [2, marker, 1, marker, 2], + [6, 3, marker, marker, 3], + [1, 2, 9, marker, 4], + ] + ) + # fit on numpy array + X_trans_expected = imputer.fit_transform(X) + + # Creates dataframe with IntegerArrays with pd.NA + X_df = pd.DataFrame(X, dtype="Int16", columns=["a", "b", "c", "d", "e"]) + + # fit on pandas dataframe with IntegerArrays + X_trans = imputer.fit_transform(X_df) + + assert_allclose(X_trans_expected, X_trans) + + +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize("keep_empty_features", [True, False]) +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +def test_keep_empty_features(imputer, keep_empty_features): + """Check that the imputer keeps features with only missing values.""" + X = np.array([[np.nan, 1], [np.nan, 2], [np.nan, 3]]) + imputer = imputer.set_params( + add_indicator=False, keep_empty_features=keep_empty_features + ) + + for method in ["fit_transform", "transform"]: + X_imputed = getattr(imputer, method)(X) + if keep_empty_features: + assert X_imputed.shape == X.shape + else: + assert X_imputed.shape == (X.shape[0], X.shape[1] - 1) + + +@pytest.mark.parametrize("imputer", imputers(), ids=lambda x: x.__class__.__name__) +@pytest.mark.parametrize("missing_value_test", [np.nan, 1]) +def test_imputation_adds_missing_indicator_if_add_indicator_is_true( + imputer, missing_value_test +): + """Check that missing indicator always exists when add_indicator=True. + + Non-regression test for gh-26590. + """ + X_train = np.array([[0, np.nan], [1, 2]]) + + # Test data where missing_value_test variable can be set to np.nan or 1. + X_test = np.array([[0, missing_value_test], [1, 2]]) + + imputer.set_params(add_indicator=True) + imputer.fit(X_train) + + X_test_imputed_with_indicator = imputer.transform(X_test) + assert X_test_imputed_with_indicator.shape == (2, 3) + + imputer.set_params(add_indicator=False) + imputer.fit(X_train) + X_test_imputed_without_indicator = imputer.transform(X_test) + assert X_test_imputed_without_indicator.shape == (2, 2) + + assert_allclose( + X_test_imputed_with_indicator[:, :-1], X_test_imputed_without_indicator + ) + if np.isnan(missing_value_test): + expected_missing_indicator = [1, 0] + else: + expected_missing_indicator = [0, 0] + + assert_allclose(X_test_imputed_with_indicator[:, -1], expected_missing_indicator) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_impute.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_impute.py new file mode 100644 index 0000000000000000000000000000000000000000..4116964c49a7a3be21771593e60e24515a7b475c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_impute.py @@ -0,0 +1,1955 @@ +import io +import re +import warnings +from itertools import product + +import numpy as np +import pytest +from scipy import sparse +from scipy.stats import kstest + +from sklearn import tree +from sklearn.datasets import load_diabetes +from sklearn.dummy import DummyRegressor +from sklearn.exceptions import ConvergenceWarning + +# make IterativeImputer available +from sklearn.experimental import enable_iterative_imputer # noqa: F401 +from sklearn.impute import IterativeImputer, KNNImputer, MissingIndicator, SimpleImputer +from sklearn.impute._base import _most_frequent +from sklearn.linear_model import ARDRegression, BayesianRidge, RidgeCV +from sklearn.model_selection import GridSearchCV +from sklearn.pipeline import Pipeline, make_union +from sklearn.random_projection import _sparse_random_matrix +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_allclose_dense_sparse, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import ( + BSR_CONTAINERS, + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + LIL_CONTAINERS, +) + + +def _assert_array_equal_and_same_dtype(x, y): + assert_array_equal(x, y) + assert x.dtype == y.dtype + + +def _assert_allclose_and_same_dtype(x, y): + assert_allclose(x, y) + assert x.dtype == y.dtype + + +def _check_statistics( + X, X_true, strategy, statistics, missing_values, sparse_container +): + """Utility function for testing imputation for a given strategy. + + Test with dense and sparse arrays + + Check that: + - the statistics (mean, median, mode) are correct + - the missing values are imputed correctly""" + + err_msg = "Parameters: strategy = %s, missing_values = %s, sparse = {0}" % ( + strategy, + missing_values, + ) + + assert_ae = assert_array_equal + + if X.dtype.kind == "f" or X_true.dtype.kind == "f": + assert_ae = assert_array_almost_equal + + # Normal matrix + imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) + X_trans = imputer.fit(X).transform(X.copy()) + assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(False)) + assert_ae(X_trans, X_true, err_msg=err_msg.format(False)) + + # Sparse matrix + imputer = SimpleImputer(missing_values=missing_values, strategy=strategy) + imputer.fit(sparse_container(X)) + X_trans = imputer.transform(sparse_container(X.copy())) + + if sparse.issparse(X_trans): + X_trans = X_trans.toarray() + + assert_ae(imputer.statistics_, statistics, err_msg=err_msg.format(True)) + assert_ae(X_trans, X_true, err_msg=err_msg.format(True)) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_imputation_shape(strategy, csr_container): + # Verify the shapes of the imputed matrix for different strategies. + X = np.random.randn(10, 2) + X[::2] = np.nan + + imputer = SimpleImputer(strategy=strategy) + X_imputed = imputer.fit_transform(csr_container(X)) + assert X_imputed.shape == (10, 2) + X_imputed = imputer.fit_transform(X) + assert X_imputed.shape == (10, 2) + + iterative_imputer = IterativeImputer(initial_strategy=strategy) + X_imputed = iterative_imputer.fit_transform(X) + assert X_imputed.shape == (10, 2) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_imputation_deletion_warning(strategy): + X = np.ones((3, 5)) + X[:, 0] = np.nan + imputer = SimpleImputer(strategy=strategy).fit(X) + + with pytest.warns(UserWarning, match="Skipping"): + imputer.transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_imputation_deletion_warning_feature_names(strategy): + pd = pytest.importorskip("pandas") + + missing_values = np.nan + feature_names = np.array(["a", "b", "c", "d"], dtype=object) + X = pd.DataFrame( + [ + [missing_values, missing_values, 1, missing_values], + [4, missing_values, 2, 10], + ], + columns=feature_names, + ) + + imputer = SimpleImputer(strategy=strategy).fit(X) + + # check SimpleImputer returning feature name attribute correctly + assert_array_equal(imputer.feature_names_in_, feature_names) + + # ensure that skipped feature warning includes feature name + with pytest.warns( + UserWarning, match=r"Skipping features without any observed values: \['b'\]" + ): + imputer.transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_error_sparse_0(strategy, csc_container): + # check that error are raised when missing_values = 0 and input is sparse + X = np.ones((3, 5)) + X[0] = 0 + X = csc_container(X) + + imputer = SimpleImputer(strategy=strategy, missing_values=0) + with pytest.raises(ValueError, match="Provide a dense array"): + imputer.fit(X) + + imputer.fit(X.toarray()) + with pytest.raises(ValueError, match="Provide a dense array"): + imputer.transform(X) + + +def safe_median(arr, *args, **kwargs): + # np.median([]) raises a TypeError for numpy >= 1.10.1 + length = arr.size if hasattr(arr, "size") else len(arr) + return np.nan if length == 0 else np.median(arr, *args, **kwargs) + + +def safe_mean(arr, *args, **kwargs): + # np.mean([]) raises a RuntimeWarning for numpy >= 1.10.1 + length = arr.size if hasattr(arr, "size") else len(arr) + return np.nan if length == 0 else np.mean(arr, *args, **kwargs) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_mean_median(csc_container): + # Test imputation using the mean and median strategies, when + # missing_values != 0. + rng = np.random.RandomState(0) + + dim = 10 + dec = 10 + shape = (dim * dim, dim + dec) + + zeros = np.zeros(shape[0]) + values = np.arange(1, shape[0] + 1) + values[4::2] = -values[4::2] + + tests = [ + ("mean", np.nan, lambda z, v, p: safe_mean(np.hstack((z, v)))), + ("median", np.nan, lambda z, v, p: safe_median(np.hstack((z, v)))), + ] + + for strategy, test_missing_values, true_value_fun in tests: + X = np.empty(shape) + X_true = np.empty(shape) + true_statistics = np.empty(shape[1]) + + # Create a matrix X with columns + # - with only zeros, + # - with only missing values + # - with zeros, missing values and values + # And a matrix X_true containing all true values + for j in range(shape[1]): + nb_zeros = (j - dec + 1 > 0) * (j - dec + 1) * (j - dec + 1) + nb_missing_values = max(shape[0] + dec * dec - (j + dec) * (j + dec), 0) + nb_values = shape[0] - nb_zeros - nb_missing_values + + z = zeros[:nb_zeros] + p = np.repeat(test_missing_values, nb_missing_values) + v = values[rng.permutation(len(values))[:nb_values]] + + true_statistics[j] = true_value_fun(z, v, p) + + # Create the columns + X[:, j] = np.hstack((v, z, p)) + + if 0 == test_missing_values: + # XXX unreached code as of v0.22 + X_true[:, j] = np.hstack( + (v, np.repeat(true_statistics[j], nb_missing_values + nb_zeros)) + ) + else: + X_true[:, j] = np.hstack( + (v, z, np.repeat(true_statistics[j], nb_missing_values)) + ) + + # Shuffle them the same way + np.random.RandomState(j).shuffle(X[:, j]) + np.random.RandomState(j).shuffle(X_true[:, j]) + + # Mean doesn't support columns containing NaNs, median does + if strategy == "median": + cols_to_keep = ~np.isnan(X_true).any(axis=0) + else: + cols_to_keep = ~np.isnan(X_true).all(axis=0) + + X_true = X_true[:, cols_to_keep] + + _check_statistics( + X, X_true, strategy, true_statistics, test_missing_values, csc_container + ) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_median_special_cases(csc_container): + # Test median imputation with sparse boundary cases + X = np.array( + [ + [0, np.nan, np.nan], # odd: implicit zero + [5, np.nan, np.nan], # odd: explicit nonzero + [0, 0, np.nan], # even: average two zeros + [-5, 0, np.nan], # even: avg zero and neg + [0, 5, np.nan], # even: avg zero and pos + [4, 5, np.nan], # even: avg nonzeros + [-4, -5, np.nan], # even: avg negatives + [-1, 2, np.nan], # even: crossing neg and pos + ] + ).transpose() + + X_imputed_median = np.array( + [ + [0, 0, 0], + [5, 5, 5], + [0, 0, 0], + [-5, 0, -2.5], + [0, 5, 2.5], + [4, 5, 4.5], + [-4, -5, -4.5], + [-1, 2, 0.5], + ] + ).transpose() + statistics_median = [0, 5, 0, -2.5, 2.5, 4.5, -4.5, 0.5] + + _check_statistics( + X, X_imputed_median, "median", statistics_median, np.nan, csc_container + ) + + +@pytest.mark.parametrize("strategy", ["mean", "median"]) +@pytest.mark.parametrize("dtype", [None, object, str]) +def test_imputation_mean_median_error_invalid_type(strategy, dtype): + X = np.array([["a", "b", 3], [4, "e", 6], ["g", "h", 9]], dtype=dtype) + msg = "non-numeric data:\ncould not convert string to float:" + with pytest.raises(ValueError, match=msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit_transform(X) + + +@pytest.mark.parametrize("strategy", ["mean", "median"]) +@pytest.mark.parametrize("type", ["list", "dataframe"]) +def test_imputation_mean_median_error_invalid_type_list_pandas(strategy, type): + X = [["a", "b", 3], [4, "e", 6], ["g", "h", 9]] + if type == "dataframe": + pd = pytest.importorskip("pandas") + X = pd.DataFrame(X) + msg = "non-numeric data:\ncould not convert string to float:" + with pytest.raises(ValueError, match=msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit_transform(X) + + +@pytest.mark.parametrize("strategy", ["constant", "most_frequent"]) +@pytest.mark.parametrize("dtype", [str, np.dtype("U"), np.dtype("S")]) +def test_imputation_const_mostf_error_invalid_types(strategy, dtype): + # Test imputation on non-numeric data using "most_frequent" and "constant" + # strategy + X = np.array( + [ + [np.nan, np.nan, "a", "f"], + [np.nan, "c", np.nan, "d"], + [np.nan, "b", "d", np.nan], + [np.nan, "c", "d", "h"], + ], + dtype=dtype, + ) + + err_msg = "SimpleImputer does not support data" + with pytest.raises(ValueError, match=err_msg): + imputer = SimpleImputer(strategy=strategy) + imputer.fit(X).transform(X) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_most_frequent(csc_container): + # Test imputation using the most-frequent strategy. + X = np.array( + [ + [-1, -1, 0, 5], + [-1, 2, -1, 3], + [-1, 1, 3, -1], + [-1, 2, 3, 7], + ] + ) + + X_true = np.array( + [ + [2, 0, 5], + [2, 3, 3], + [1, 3, 3], + [2, 3, 7], + ] + ) + + # scipy.stats.mode, used in SimpleImputer, doesn't return the first most + # frequent as promised in the doc but the lowest most frequent. When this + # test will fail after an update of scipy, SimpleImputer will need to be + # updated to be consistent with the new (correct) behaviour + _check_statistics(X, X_true, "most_frequent", [np.nan, 2, 3, 3], -1, csc_container) + + +@pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) +def test_imputation_most_frequent_objects(marker): + # Test imputation using the most-frequent strategy. + X = np.array( + [ + [marker, marker, "a", "f"], + [marker, "c", marker, "d"], + [marker, "b", "d", marker], + [marker, "c", "d", "h"], + ], + dtype=object, + ) + + X_true = np.array( + [ + ["c", "a", "f"], + ["c", "d", "d"], + ["b", "d", "d"], + ["c", "d", "h"], + ], + dtype=object, + ) + + imputer = SimpleImputer(missing_values=marker, strategy="most_frequent") + X_trans = imputer.fit(X).transform(X) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("dtype", [object, "category"]) +def test_imputation_most_frequent_pandas(dtype): + # Test imputation using the most frequent strategy on pandas df + pd = pytest.importorskip("pandas") + + f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,") + + df = pd.read_csv(f, dtype=dtype) + + X_true = np.array( + [["a", "i", "x"], ["a", "j", "y"], ["a", "j", "x"], ["b", "j", "x"]], + dtype=object, + ) + + imputer = SimpleImputer(strategy="most_frequent") + X_trans = imputer.fit_transform(df) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("X_data, missing_value", [(1, 0), (1.0, np.nan)]) +def test_imputation_constant_error_invalid_type(X_data, missing_value): + # Verify that exceptions are raised on invalid fill_value type + X = np.full((3, 5), X_data, dtype=float) + X[0, 0] = missing_value + + fill_value = "x" + err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast" + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer = SimpleImputer( + missing_values=missing_value, strategy="constant", fill_value=fill_value + ) + imputer.fit_transform(X) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +def test_imputation_constant_integer(): + # Test imputation using the constant strategy on integers + X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]]) + + X_true = np.array([[0, 2, 3, 0], [4, 0, 5, 0], [6, 7, 0, 0], [8, 9, 0, 0]]) + + imputer = SimpleImputer( + missing_values=-1, strategy="constant", fill_value=0, keep_empty_features=True + ) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("array_constructor", CSR_CONTAINERS + [np.asarray]) +def test_imputation_constant_float(array_constructor): + # Test imputation using the constant strategy on floats + X = np.array( + [ + [np.nan, 1.1, 0, np.nan], + [1.2, np.nan, 1.3, np.nan], + [0, 0, np.nan, np.nan], + [1.4, 1.5, 0, np.nan], + ] + ) + + X_true = np.array( + [[-1, 1.1, 0, -1], [1.2, -1, 1.3, -1], [0, 0, -1, -1], [1.4, 1.5, 0, -1]] + ) + + X = array_constructor(X) + + X_true = array_constructor(X_true) + + imputer = SimpleImputer( + strategy="constant", fill_value=-1, keep_empty_features=True + ) + X_trans = imputer.fit_transform(X) + + assert_allclose_dense_sparse(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("marker", [None, np.nan, "NAN", "", 0]) +def test_imputation_constant_object(marker): + # Test imputation using the constant strategy on objects + X = np.array( + [ + [marker, "a", "b", marker], + ["c", marker, "d", marker], + ["e", "f", marker, marker], + ["g", "h", "i", marker], + ], + dtype=object, + ) + + X_true = np.array( + [ + ["missing", "a", "b", "missing"], + ["c", "missing", "d", "missing"], + ["e", "f", "missing", "missing"], + ["g", "h", "i", "missing"], + ], + dtype=object, + ) + + imputer = SimpleImputer( + missing_values=marker, + strategy="constant", + fill_value="missing", + keep_empty_features=True, + ) + X_trans = imputer.fit_transform(X) + + assert_array_equal(X_trans, X_true) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +@pytest.mark.parametrize("dtype", [object, "category"]) +def test_imputation_constant_pandas(dtype): + # Test imputation using the constant strategy on pandas df + pd = pytest.importorskip("pandas") + + f = io.StringIO("Cat1,Cat2,Cat3,Cat4\n,i,x,\na,,y,\na,j,,\nb,j,x,") + + df = pd.read_csv(f, dtype=dtype) + + X_true = np.array( + [ + ["missing_value", "i", "x", "missing_value"], + ["a", "missing_value", "y", "missing_value"], + ["a", "j", "missing_value", "missing_value"], + ["b", "j", "x", "missing_value"], + ], + dtype=object, + ) + + imputer = SimpleImputer(strategy="constant", keep_empty_features=True) + X_trans = imputer.fit_transform(df) + + assert_array_equal(X_trans, X_true) + + +@pytest.mark.parametrize("X", [[[1], [2]], [[1], [np.nan]]]) +def test_iterative_imputer_one_feature(X): + # check we exit early when there is a single feature + imputer = IterativeImputer().fit(X) + assert imputer.n_iter_ == 0 + imputer = IterativeImputer() + imputer.fit([[1], [2]]) + assert imputer.n_iter_ == 0 + imputer.fit([[1], [np.nan]]) + assert imputer.n_iter_ == 0 + + +def test_imputation_pipeline_grid_search(): + # Test imputation within a pipeline + gridsearch. + X = _sparse_random_matrix(100, 100, density=0.10) + missing_values = X.data[0] + + pipeline = Pipeline( + [ + ("imputer", SimpleImputer(missing_values=missing_values)), + ("tree", tree.DecisionTreeRegressor(random_state=0)), + ] + ) + + parameters = {"imputer__strategy": ["mean", "median", "most_frequent"]} + + Y = _sparse_random_matrix(100, 1, density=0.10).toarray() + gs = GridSearchCV(pipeline, parameters) + gs.fit(X, Y) + + +def test_imputation_copy(): + # Test imputation with copy + X_orig = _sparse_random_matrix(5, 5, density=0.75, random_state=0) + + # copy=True, dense => copy + X = X_orig.copy().toarray() + imputer = SimpleImputer(missing_values=0, strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert not np.all(X == Xt) + + # copy=True, sparse csr => copy + X = X_orig.copy() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=True) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert not np.all(X.data == Xt.data) + + # copy=False, dense => no copy + X = X_orig.copy().toarray() + imputer = SimpleImputer(missing_values=0, strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt[0, 0] = -1 + assert_array_almost_equal(X, Xt) + + # copy=False, sparse csc => no copy + X = X_orig.copy().tocsc() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert_array_almost_equal(X.data, Xt.data) + + # copy=False, sparse csr => copy + X = X_orig.copy() + imputer = SimpleImputer(missing_values=X.data[0], strategy="mean", copy=False) + Xt = imputer.fit(X).transform(X) + Xt.data[0] = -1 + assert not np.all(X.data == Xt.data) + + # Note: If X is sparse and if missing_values=0, then a (dense) copy of X is + # made, even if copy=False. + + +def test_iterative_imputer_zero_iters(): + rng = np.random.RandomState(0) + + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + missing_flag = X == 0 + X[missing_flag] = np.nan + + imputer = IterativeImputer(max_iter=0) + X_imputed = imputer.fit_transform(X) + # with max_iter=0, only initial imputation is performed + assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) + + # repeat but force n_iter_ to 0 + imputer = IterativeImputer(max_iter=5).fit(X) + # transformed should not be equal to initial imputation + assert not np.all(imputer.transform(X) == imputer.initial_imputer_.transform(X)) + + imputer.n_iter_ = 0 + # now they should be equal as only initial imputation is done + assert_allclose(imputer.transform(X), imputer.initial_imputer_.transform(X)) + + +def test_iterative_imputer_verbose(): + rng = np.random.RandomState(0) + + n = 100 + d = 3 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=1) + imputer.fit(X) + imputer.transform(X) + imputer = IterativeImputer(missing_values=0, max_iter=1, verbose=2) + imputer.fit(X) + imputer.transform(X) + + +def test_iterative_imputer_all_missing(): + n = 100 + d = 3 + X = np.zeros((n, d)) + imputer = IterativeImputer(missing_values=0, max_iter=1) + X_imputed = imputer.fit_transform(X) + assert_allclose(X_imputed, imputer.initial_imputer_.transform(X)) + + +@pytest.mark.parametrize( + "imputation_order", ["random", "roman", "ascending", "descending", "arabic"] +) +def test_iterative_imputer_imputation_order(imputation_order): + rng = np.random.RandomState(0) + n = 100 + d = 10 + max_iter = 2 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + X[:, 0] = 1 # this column should not be discarded by IterativeImputer + + imputer = IterativeImputer( + missing_values=0, + max_iter=max_iter, + n_nearest_features=5, + sample_posterior=False, + skip_complete=True, + min_value=0, + max_value=1, + verbose=1, + imputation_order=imputation_order, + random_state=rng, + ) + imputer.fit_transform(X) + ordered_idx = [i.feat_idx for i in imputer.imputation_sequence_] + + assert len(ordered_idx) // imputer.n_iter_ == imputer.n_features_with_missing_ + + if imputation_order == "roman": + assert np.all(ordered_idx[: d - 1] == np.arange(1, d)) + elif imputation_order == "arabic": + assert np.all(ordered_idx[: d - 1] == np.arange(d - 1, 0, -1)) + elif imputation_order == "random": + ordered_idx_round_1 = ordered_idx[: d - 1] + ordered_idx_round_2 = ordered_idx[d - 1 :] + assert ordered_idx_round_1 != ordered_idx_round_2 + elif "ending" in imputation_order: + assert len(ordered_idx) == max_iter * (d - 1) + + +@pytest.mark.parametrize( + "estimator", [None, DummyRegressor(), BayesianRidge(), ARDRegression(), RidgeCV()] +) +def test_iterative_imputer_estimators(estimator): + rng = np.random.RandomState(0) + + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + + imputer = IterativeImputer( + missing_values=0, max_iter=1, estimator=estimator, random_state=rng + ) + imputer.fit_transform(X) + + # check that types are correct for estimators + hashes = [] + for triplet in imputer.imputation_sequence_: + expected_type = ( + type(estimator) if estimator is not None else type(BayesianRidge()) + ) + assert isinstance(triplet.estimator, expected_type) + hashes.append(id(triplet.estimator)) + + # check that each estimator is unique + assert len(set(hashes)) == len(hashes) + + +def test_iterative_imputer_clip(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + + imputer = IterativeImputer( + missing_values=0, max_iter=1, min_value=0.1, max_value=0.2, random_state=rng + ) + + Xt = imputer.fit_transform(X) + assert_allclose(np.min(Xt[X == 0]), 0.1) + assert_allclose(np.max(Xt[X == 0]), 0.2) + assert_allclose(Xt[X != 0], X[X != 0]) + + +def test_iterative_imputer_clip_truncnorm(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng).toarray() + X[:, 0] = 1 + + imputer = IterativeImputer( + missing_values=0, + max_iter=2, + n_nearest_features=5, + sample_posterior=True, + min_value=0.1, + max_value=0.2, + verbose=1, + imputation_order="random", + random_state=rng, + ) + Xt = imputer.fit_transform(X) + assert_allclose(np.min(Xt[X == 0]), 0.1) + assert_allclose(np.max(Xt[X == 0]), 0.2) + assert_allclose(Xt[X != 0], X[X != 0]) + + +def test_iterative_imputer_truncated_normal_posterior(): + # test that the values that are imputed using `sample_posterior=True` + # with boundaries (`min_value` and `max_value` are not None) are drawn + # from a distribution that looks gaussian via the Kolmogorov Smirnov test. + # note that starting from the wrong random seed will make this test fail + # because random sampling doesn't occur at all when the imputation + # is outside of the (min_value, max_value) range + rng = np.random.RandomState(42) + + X = rng.normal(size=(5, 5)) + X[0][0] = np.nan + + imputer = IterativeImputer( + min_value=0, max_value=0.5, sample_posterior=True, random_state=rng + ) + + imputer.fit_transform(X) + # generate multiple imputations for the single missing value + imputations = np.array([imputer.transform(X)[0][0] for _ in range(100)]) + + assert all(imputations >= 0) + assert all(imputations <= 0.5) + + mu, sigma = imputations.mean(), imputations.std() + ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm") + if sigma == 0: + sigma += 1e-12 + ks_statistic, p_value = kstest((imputations - mu) / sigma, "norm") + # we want to fail to reject null hypothesis + # null hypothesis: distributions are the same + assert ks_statistic < 0.2 or p_value > 0.1, "The posterior does appear to be normal" + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +def test_iterative_imputer_missing_at_transform(strategy): + rng = np.random.RandomState(0) + n = 100 + d = 10 + X_train = rng.randint(low=0, high=3, size=(n, d)) + X_test = rng.randint(low=0, high=3, size=(n, d)) + + X_train[:, 0] = 1 # definitely no missing values in 0th column + X_test[0, 0] = 0 # definitely missing value in 0th column + + imputer = IterativeImputer( + missing_values=0, max_iter=1, initial_strategy=strategy, random_state=rng + ).fit(X_train) + initial_imputer = SimpleImputer(missing_values=0, strategy=strategy).fit(X_train) + + # if there were no missing values at time of fit, then imputer will + # only use the initial imputer for that feature at transform + assert_allclose( + imputer.transform(X_test)[:, 0], initial_imputer.transform(X_test)[:, 0] + ) + + +def test_iterative_imputer_transform_stochasticity(): + rng1 = np.random.RandomState(0) + rng2 = np.random.RandomState(1) + n = 100 + d = 10 + X = _sparse_random_matrix(n, d, density=0.10, random_state=rng1).toarray() + + # when sample_posterior=True, two transforms shouldn't be equal + imputer = IterativeImputer( + missing_values=0, max_iter=1, sample_posterior=True, random_state=rng1 + ) + imputer.fit(X) + + X_fitted_1 = imputer.transform(X) + X_fitted_2 = imputer.transform(X) + + # sufficient to assert that the means are not the same + assert np.mean(X_fitted_1) != pytest.approx(np.mean(X_fitted_2)) + + # when sample_posterior=False, and n_nearest_features=None + # and imputation_order is not random + # the two transforms should be identical even if rng are different + imputer1 = IterativeImputer( + missing_values=0, + max_iter=1, + sample_posterior=False, + n_nearest_features=None, + imputation_order="ascending", + random_state=rng1, + ) + + imputer2 = IterativeImputer( + missing_values=0, + max_iter=1, + sample_posterior=False, + n_nearest_features=None, + imputation_order="ascending", + random_state=rng2, + ) + imputer1.fit(X) + imputer2.fit(X) + + X_fitted_1a = imputer1.transform(X) + X_fitted_1b = imputer1.transform(X) + X_fitted_2 = imputer2.transform(X) + + assert_allclose(X_fitted_1a, X_fitted_1b) + assert_allclose(X_fitted_1a, X_fitted_2) + + +def test_iterative_imputer_no_missing(): + rng = np.random.RandomState(0) + X = rng.rand(100, 100) + X[:, 0] = np.nan + m1 = IterativeImputer(max_iter=10, random_state=rng) + m2 = IterativeImputer(max_iter=10, random_state=rng) + pred1 = m1.fit(X).transform(X) + pred2 = m2.fit_transform(X) + # should exclude the first column entirely + assert_allclose(X[:, 1:], pred1) + # fit and fit_transform should both be identical + assert_allclose(pred1, pred2) + + +def test_iterative_imputer_rank_one(): + rng = np.random.RandomState(0) + d = 50 + A = rng.rand(d, 1) + B = rng.rand(1, d) + X = np.dot(A, B) + nan_mask = rng.rand(d, d) < 0.5 + X_missing = X.copy() + X_missing[nan_mask] = np.nan + + imputer = IterativeImputer(max_iter=5, verbose=1, random_state=rng) + X_filled = imputer.fit_transform(X_missing) + assert_allclose(X_filled, X, atol=0.02) + + +@pytest.mark.parametrize("rank", [3, 5]) +def test_iterative_imputer_transform_recovery(rank): + rng = np.random.RandomState(0) + n = 70 + d = 70 + A = rng.rand(n, rank) + B = rng.rand(rank, d) + X_filled = np.dot(A, B) + nan_mask = rng.rand(n, d) < 0.5 + X_missing = X_filled.copy() + X_missing[nan_mask] = np.nan + + # split up data in half + n = n // 2 + X_train = X_missing[:n] + X_test_filled = X_filled[n:] + X_test = X_missing[n:] + + imputer = IterativeImputer( + max_iter=5, imputation_order="descending", verbose=1, random_state=rng + ).fit(X_train) + X_test_est = imputer.transform(X_test) + assert_allclose(X_test_filled, X_test_est, atol=0.1) + + +def test_iterative_imputer_additive_matrix(): + rng = np.random.RandomState(0) + n = 100 + d = 10 + A = rng.randn(n, d) + B = rng.randn(n, d) + X_filled = np.zeros(A.shape) + for i in range(d): + for j in range(d): + X_filled[:, (i + j) % d] += (A[:, i] + B[:, j]) / 2 + # a quarter is randomly missing + nan_mask = rng.rand(n, d) < 0.25 + X_missing = X_filled.copy() + X_missing[nan_mask] = np.nan + + # split up data + n = n // 2 + X_train = X_missing[:n] + X_test_filled = X_filled[n:] + X_test = X_missing[n:] + + imputer = IterativeImputer(max_iter=10, verbose=1, random_state=rng).fit(X_train) + X_test_est = imputer.transform(X_test) + assert_allclose(X_test_filled, X_test_est, rtol=1e-3, atol=0.01) + + +def test_iterative_imputer_early_stopping(): + rng = np.random.RandomState(0) + n = 50 + d = 5 + A = rng.rand(n, 1) + B = rng.rand(1, d) + X = np.dot(A, B) + nan_mask = rng.rand(n, d) < 0.5 + X_missing = X.copy() + X_missing[nan_mask] = np.nan + + imputer = IterativeImputer( + max_iter=100, tol=1e-2, sample_posterior=False, verbose=1, random_state=rng + ) + X_filled_100 = imputer.fit_transform(X_missing) + assert len(imputer.imputation_sequence_) == d * imputer.n_iter_ + + imputer = IterativeImputer( + max_iter=imputer.n_iter_, sample_posterior=False, verbose=1, random_state=rng + ) + X_filled_early = imputer.fit_transform(X_missing) + assert_allclose(X_filled_100, X_filled_early, atol=1e-7) + + imputer = IterativeImputer( + max_iter=100, tol=0, sample_posterior=False, verbose=1, random_state=rng + ) + imputer.fit(X_missing) + assert imputer.n_iter_ == imputer.max_iter + + +def test_iterative_imputer_catch_warning(): + # check that we catch a RuntimeWarning due to a division by zero when a + # feature is constant in the dataset + X, y = load_diabetes(return_X_y=True) + n_samples, n_features = X.shape + + # simulate that a feature only contain one category during fit + X[:, 3] = 1 + + # add some missing values + rng = np.random.RandomState(0) + missing_rate = 0.15 + for feat in range(n_features): + sample_idx = rng.choice( + np.arange(n_samples), size=int(n_samples * missing_rate), replace=False + ) + X[sample_idx, feat] = np.nan + + imputer = IterativeImputer(n_nearest_features=5, sample_posterior=True) + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + X_fill = imputer.fit_transform(X, y) + assert not np.any(np.isnan(X_fill)) + + +@pytest.mark.parametrize( + "min_value, max_value, correct_output", + [ + (0, 100, np.array([[0] * 3, [100] * 3])), + (None, None, np.array([[-np.inf] * 3, [np.inf] * 3])), + (-np.inf, np.inf, np.array([[-np.inf] * 3, [np.inf] * 3])), + ([-5, 5, 10], [100, 200, 300], np.array([[-5, 5, 10], [100, 200, 300]])), + ( + [-5, -np.inf, 10], + [100, 200, np.inf], + np.array([[-5, -np.inf, 10], [100, 200, np.inf]]), + ), + ], + ids=["scalars", "None-default", "inf", "lists", "lists-with-inf"], +) +def test_iterative_imputer_min_max_array_like(min_value, max_value, correct_output): + # check that passing scalar or array-like + # for min_value and max_value in IterativeImputer works + X = np.random.RandomState(0).randn(10, 3) + imputer = IterativeImputer(min_value=min_value, max_value=max_value) + imputer.fit(X) + + assert isinstance(imputer._min_value, np.ndarray) and isinstance( + imputer._max_value, np.ndarray + ) + assert (imputer._min_value.shape[0] == X.shape[1]) and ( + imputer._max_value.shape[0] == X.shape[1] + ) + + assert_allclose(correct_output[0, :], imputer._min_value) + assert_allclose(correct_output[1, :], imputer._max_value) + + +@pytest.mark.parametrize( + "min_value, max_value, err_msg", + [ + (100, 0, "min_value >= max_value."), + (np.inf, -np.inf, "min_value >= max_value."), + ([-5, 5], [100, 200, 0], "_value' should be of shape"), + ([-5, 5, 5], [100, 200], "_value' should be of shape"), + ], +) +def test_iterative_imputer_catch_min_max_error(min_value, max_value, err_msg): + # check that passing scalar or array-like + # for min_value and max_value in IterativeImputer works + X = np.random.random((10, 3)) + imputer = IterativeImputer(min_value=min_value, max_value=max_value) + with pytest.raises(ValueError, match=err_msg): + imputer.fit(X) + + +@pytest.mark.parametrize( + "min_max_1, min_max_2", + [([None, None], [-np.inf, np.inf]), ([-10, 10], [[-10] * 4, [10] * 4])], + ids=["None-vs-inf", "Scalar-vs-vector"], +) +def test_iterative_imputer_min_max_array_like_imputation(min_max_1, min_max_2): + # Test that None/inf and scalar/vector give the same imputation + X_train = np.array( + [ + [np.nan, 2, 2, 1], + [10, np.nan, np.nan, 7], + [3, 1, np.nan, 1], + [np.nan, 4, 2, np.nan], + ] + ) + X_test = np.array( + [[np.nan, 2, np.nan, 5], [2, 4, np.nan, np.nan], [np.nan, 1, 10, 1]] + ) + imputer1 = IterativeImputer( + min_value=min_max_1[0], max_value=min_max_1[1], random_state=0 + ) + imputer2 = IterativeImputer( + min_value=min_max_2[0], max_value=min_max_2[1], random_state=0 + ) + X_test_imputed1 = imputer1.fit(X_train).transform(X_test) + X_test_imputed2 = imputer2.fit(X_train).transform(X_test) + assert_allclose(X_test_imputed1[:, 0], X_test_imputed2[:, 0]) + + +@pytest.mark.parametrize("skip_complete", [True, False]) +def test_iterative_imputer_skip_non_missing(skip_complete): + # check the imputing strategy when missing data are present in the + # testing set only. + # taken from: https://github.com/scikit-learn/scikit-learn/issues/14383 + rng = np.random.RandomState(0) + X_train = np.array([[5, 2, 2, 1], [10, 1, 2, 7], [3, 1, 1, 1], [8, 4, 2, 2]]) + X_test = np.array([[np.nan, 2, 4, 5], [np.nan, 4, 1, 2], [np.nan, 1, 10, 1]]) + imputer = IterativeImputer( + initial_strategy="mean", skip_complete=skip_complete, random_state=rng + ) + X_test_est = imputer.fit(X_train).transform(X_test) + if skip_complete: + # impute with the initial strategy: 'mean' + assert_allclose(X_test_est[:, 0], np.mean(X_train[:, 0])) + else: + assert_allclose(X_test_est[:, 0], [11, 7, 12], rtol=1e-4) + + +@pytest.mark.parametrize("rs_imputer", [None, 1, np.random.RandomState(seed=1)]) +@pytest.mark.parametrize("rs_estimator", [None, 1, np.random.RandomState(seed=1)]) +def test_iterative_imputer_dont_set_random_state(rs_imputer, rs_estimator): + class ZeroEstimator: + def __init__(self, random_state): + self.random_state = random_state + + def fit(self, *args, **kgards): + return self + + def predict(self, X): + return np.zeros(X.shape[0]) + + estimator = ZeroEstimator(random_state=rs_estimator) + imputer = IterativeImputer(random_state=rs_imputer) + X_train = np.zeros((10, 3)) + imputer.fit(X_train) + assert estimator.random_state == rs_estimator + + +@pytest.mark.parametrize( + "X_fit, X_trans, params, msg_err", + [ + ( + np.array([[-1, 1], [1, 2]]), + np.array([[-1, 1], [1, -1]]), + {"features": "missing-only", "sparse": "auto"}, + "have missing values in transform but have no missing values in fit", + ), + ( + np.array([["a", "b"], ["c", "a"]], dtype=str), + np.array([["a", "b"], ["c", "a"]], dtype=str), + {}, + "MissingIndicator does not support data with dtype", + ), + ], +) +def test_missing_indicator_error(X_fit, X_trans, params, msg_err): + indicator = MissingIndicator(missing_values=-1) + indicator.set_params(**params) + with pytest.raises(ValueError, match=msg_err): + indicator.fit(X_fit).transform(X_trans) + + +def _generate_missing_indicator_cases(): + missing_values_dtypes = [(0, np.int32), (np.nan, np.float64), (-1, np.int32)] + arr_types = ( + [np.array] + + CSC_CONTAINERS + + CSR_CONTAINERS + + COO_CONTAINERS + + LIL_CONTAINERS + + BSR_CONTAINERS + ) + return [ + (arr_type, missing_values, dtype) + for arr_type, (missing_values, dtype) in product( + arr_types, missing_values_dtypes + ) + if not (missing_values == 0 and arr_type is not np.array) + ] + + +@pytest.mark.parametrize( + "arr_type, missing_values, dtype", _generate_missing_indicator_cases() +) +@pytest.mark.parametrize( + "param_features, n_features, features_indices", + [("missing-only", 3, np.array([0, 1, 2])), ("all", 3, np.array([0, 1, 2]))], +) +def test_missing_indicator_new( + missing_values, arr_type, dtype, param_features, n_features, features_indices +): + X_fit = np.array([[missing_values, missing_values, 1], [4, 2, missing_values]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + X_fit_expected = np.array([[1, 1, 0], [0, 0, 1]]) + X_trans_expected = np.array([[1, 1, 0], [0, 0, 0]]) + + # convert the input to the right array format and right dtype + X_fit = arr_type(X_fit).astype(dtype) + X_trans = arr_type(X_trans).astype(dtype) + X_fit_expected = X_fit_expected.astype(dtype) + X_trans_expected = X_trans_expected.astype(dtype) + + indicator = MissingIndicator( + missing_values=missing_values, features=param_features, sparse=False + ) + X_fit_mask = indicator.fit_transform(X_fit) + X_trans_mask = indicator.transform(X_trans) + + assert X_fit_mask.shape[1] == n_features + assert X_trans_mask.shape[1] == n_features + + assert_array_equal(indicator.features_, features_indices) + assert_allclose(X_fit_mask, X_fit_expected[:, features_indices]) + assert_allclose(X_trans_mask, X_trans_expected[:, features_indices]) + + assert X_fit_mask.dtype == bool + assert X_trans_mask.dtype == bool + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + + indicator.set_params(sparse=True) + X_fit_mask_sparse = indicator.fit_transform(X_fit) + X_trans_mask_sparse = indicator.transform(X_trans) + + assert X_fit_mask_sparse.dtype == bool + assert X_trans_mask_sparse.dtype == bool + assert X_fit_mask_sparse.format == "csc" + assert X_trans_mask_sparse.format == "csc" + assert_allclose(X_fit_mask_sparse.toarray(), X_fit_mask) + assert_allclose(X_trans_mask_sparse.toarray(), X_trans_mask) + + +@pytest.mark.parametrize( + "arr_type", + CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS, +) +def test_missing_indicator_raise_on_sparse_with_missing_0(arr_type): + # test for sparse input and missing_value == 0 + + missing_values = 0 + X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + + # convert the input to the right array format + X_fit_sparse = arr_type(X_fit) + X_trans_sparse = arr_type(X_trans) + + indicator = MissingIndicator(missing_values=missing_values) + + with pytest.raises(ValueError, match="Sparse input with missing_values=0"): + indicator.fit_transform(X_fit_sparse) + + indicator.fit_transform(X_fit) + with pytest.raises(ValueError, match="Sparse input with missing_values=0"): + indicator.transform(X_trans_sparse) + + +@pytest.mark.parametrize("param_sparse", [True, False, "auto"]) +@pytest.mark.parametrize( + "arr_type, missing_values", + [(np.array, 0)] + + list( + product( + CSC_CONTAINERS + + CSR_CONTAINERS + + COO_CONTAINERS + + LIL_CONTAINERS + + BSR_CONTAINERS, + [np.nan], + ) + ), +) +def test_missing_indicator_sparse_param(arr_type, missing_values, param_sparse): + # check the format of the output with different sparse parameter + X_fit = np.array([[missing_values, missing_values, 1], [4, missing_values, 2]]) + X_trans = np.array([[missing_values, missing_values, 1], [4, 12, 10]]) + X_fit = arr_type(X_fit).astype(np.float64) + X_trans = arr_type(X_trans).astype(np.float64) + + indicator = MissingIndicator(missing_values=missing_values, sparse=param_sparse) + X_fit_mask = indicator.fit_transform(X_fit) + X_trans_mask = indicator.transform(X_trans) + + if param_sparse is True: + assert X_fit_mask.format == "csc" + assert X_trans_mask.format == "csc" + elif param_sparse == "auto" and missing_values == 0: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + elif param_sparse is False: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + else: + if sparse.issparse(X_fit): + assert X_fit_mask.format == "csc" + assert X_trans_mask.format == "csc" + else: + assert isinstance(X_fit_mask, np.ndarray) + assert isinstance(X_trans_mask, np.ndarray) + + +def test_missing_indicator_string(): + X = np.array([["a", "b", "c"], ["b", "c", "a"]], dtype=object) + indicator = MissingIndicator(missing_values="a", features="all") + X_trans = indicator.fit_transform(X) + assert_array_equal(X_trans, np.array([[True, False, False], [False, False, True]])) + + +@pytest.mark.parametrize( + "X, missing_values, X_trans_exp", + [ + ( + np.array([["a", "b"], ["b", "a"]], dtype=object), + "a", + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ( + np.array([[np.nan, 1.0], [1.0, np.nan]]), + np.nan, + np.array([[1.0, 1.0, True, False], [1.0, 1.0, False, True]]), + ), + ( + np.array([[np.nan, "b"], ["b", np.nan]], dtype=object), + np.nan, + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ( + np.array([[None, "b"], ["b", None]], dtype=object), + None, + np.array([["b", "b", True, False], ["b", "b", False, True]], dtype=object), + ), + ], +) +def test_missing_indicator_with_imputer(X, missing_values, X_trans_exp): + trans = make_union( + SimpleImputer(missing_values=missing_values, strategy="most_frequent"), + MissingIndicator(missing_values=missing_values), + ) + X_trans = trans.fit_transform(X) + assert_array_equal(X_trans, X_trans_exp) + + +@pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) +@pytest.mark.parametrize( + "imputer_missing_values, missing_value, err_msg", + [ + ("NaN", np.nan, "Input X contains NaN"), + ("-1", -1, "types are expected to be both numerical."), + ], +) +def test_inconsistent_dtype_X_missing_values( + imputer_constructor, imputer_missing_values, missing_value, err_msg +): + # regression test for issue #11390. Comparison between incoherent dtype + # for X and missing_values was not raising a proper error. + rng = np.random.RandomState(42) + X = rng.randn(10, 10) + X[0, 0] = missing_value + + imputer = imputer_constructor(missing_values=imputer_missing_values) + + with pytest.raises(ValueError, match=err_msg): + imputer.fit_transform(X) + + +def test_missing_indicator_no_missing(): + # check that all features are dropped if there are no missing values when + # features='missing-only' (#13491) + X = np.array([[1, 1], [1, 1]]) + + mi = MissingIndicator(features="missing-only", missing_values=-1) + Xt = mi.fit_transform(X) + + assert Xt.shape[1] == 0 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_missing_indicator_sparse_no_explicit_zeros(csr_container): + # Check that non missing values don't become explicit zeros in the mask + # generated by missing indicator when X is sparse. (#13491) + X = csr_container([[0, 1, 2], [1, 2, 0], [2, 0, 1]]) + + mi = MissingIndicator(features="all", missing_values=1) + Xt = mi.fit_transform(X) + + assert Xt.nnz == Xt.sum() + + +@pytest.mark.parametrize("imputer_constructor", [SimpleImputer, IterativeImputer]) +def test_imputer_without_indicator(imputer_constructor): + X = np.array([[1, 1], [1, 1]]) + imputer = imputer_constructor() + imputer.fit(X) + + assert imputer.indicator_ is None + + +@pytest.mark.parametrize( + "arr_type", + CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS + LIL_CONTAINERS + BSR_CONTAINERS, +) +def test_simple_imputation_add_indicator_sparse_matrix(arr_type): + X_sparse = arr_type([[np.nan, 1, 5], [2, np.nan, 1], [6, 3, np.nan], [1, 2, 9]]) + X_true = np.array( + [ + [3.0, 1.0, 5.0, 1.0, 0.0, 0.0], + [2.0, 2.0, 1.0, 0.0, 1.0, 0.0], + [6.0, 3.0, 5.0, 0.0, 0.0, 1.0], + [1.0, 2.0, 9.0, 0.0, 0.0, 0.0], + ] + ) + + imputer = SimpleImputer(missing_values=np.nan, add_indicator=True) + X_trans = imputer.fit_transform(X_sparse) + + assert sparse.issparse(X_trans) + assert X_trans.shape == X_true.shape + assert_allclose(X_trans.toarray(), X_true) + + +@pytest.mark.parametrize( + "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", + [("ascending", [3, 4, 2, 0, 1]), ("descending", [1, 0, 2, 4, 3])], +) +def test_imputation_order(order, idx_order): + # regression test for #15393 + rng = np.random.RandomState(42) + X = rng.rand(100, 5) + X[:50, 1] = np.nan + X[:30, 0] = np.nan + X[:20, 2] = np.nan + X[:10, 4] = np.nan + + with pytest.warns(ConvergenceWarning): + trs = IterativeImputer(max_iter=1, imputation_order=order, random_state=0).fit( + X + ) + idx = [x.feat_idx for x in trs.imputation_sequence_] + assert idx == idx_order + + +@pytest.mark.parametrize("missing_value", [-1, np.nan]) +def test_simple_imputation_inverse_transform(missing_value): + # Test inverse_transform feature for np.nan + X_1 = np.array( + [ + [9, missing_value, 3, -1], + [4, -1, 5, 4], + [6, 7, missing_value, -1], + [8, 9, 0, missing_value], + ] + ) + + X_2 = np.array( + [ + [5, 4, 2, 1], + [2, 1, missing_value, 3], + [9, missing_value, 7, 1], + [6, 4, 2, missing_value], + ] + ) + + X_3 = np.array( + [ + [1, missing_value, 5, 9], + [missing_value, 4, missing_value, missing_value], + [2, missing_value, 7, missing_value], + [missing_value, 3, missing_value, 8], + ] + ) + + X_4 = np.array( + [ + [1, 1, 1, 3], + [missing_value, 2, missing_value, 1], + [2, 3, 3, 4], + [missing_value, 4, missing_value, 2], + ] + ) + + imputer = SimpleImputer( + missing_values=missing_value, strategy="mean", add_indicator=True + ) + + X_1_trans = imputer.fit_transform(X_1) + X_1_inv_trans = imputer.inverse_transform(X_1_trans) + + X_2_trans = imputer.transform(X_2) # test on new data + X_2_inv_trans = imputer.inverse_transform(X_2_trans) + + assert_array_equal(X_1_inv_trans, X_1) + assert_array_equal(X_2_inv_trans, X_2) + + for X in [X_3, X_4]: + X_trans = imputer.fit_transform(X) + X_inv_trans = imputer.inverse_transform(X_trans) + assert_array_equal(X_inv_trans, X) + + +@pytest.mark.parametrize("missing_value", [-1, np.nan]) +def test_simple_imputation_inverse_transform_exceptions(missing_value): + X_1 = np.array( + [ + [9, missing_value, 3, -1], + [4, -1, 5, 4], + [6, 7, missing_value, -1], + [8, 9, 0, missing_value], + ] + ) + + imputer = SimpleImputer(missing_values=missing_value, strategy="mean") + X_1_trans = imputer.fit_transform(X_1) + with pytest.raises( + ValueError, match=f"Got 'add_indicator={imputer.add_indicator}'" + ): + imputer.inverse_transform(X_1_trans) + + +@pytest.mark.parametrize( + "expected,array,dtype,extra_value,n_repeat", + [ + # array of object dtype + ("extra_value", ["a", "b", "c"], object, "extra_value", 2), + ( + "most_frequent_value", + ["most_frequent_value", "most_frequent_value", "value"], + object, + "extra_value", + 1, + ), + ("a", ["min_value", "min_valuevalue"], object, "a", 2), + ("min_value", ["min_value", "min_value", "value"], object, "z", 2), + # array of numeric dtype + (10, [1, 2, 3], int, 10, 2), + (1, [1, 1, 2], int, 10, 1), + (10, [20, 20, 1], int, 10, 2), + (1, [1, 1, 20], int, 10, 2), + ], +) +def test_most_frequent(expected, array, dtype, extra_value, n_repeat): + assert expected == _most_frequent( + np.array(array, dtype=dtype), extra_value, n_repeat + ) + + +@pytest.mark.parametrize( + "expected,array", + [ + ("a", ["a", "b"]), + (1, [1, 2]), + (None, [None, "a"]), + (None, [None, 1]), + (None, [None, "a", 1]), + (1, [1, "1"]), + (1, ["1", 1]), + ], +) +def test_most_frequent_tie_object(expected, array): + """Check the tie breaking behavior of the most frequent strategy. + + Non-regression test for issue #31717. + """ + assert expected == _most_frequent(np.array(array, dtype=object), None, 0) + + +@pytest.mark.parametrize( + "initial_strategy", ["mean", "median", "most_frequent", "constant"] +) +def test_iterative_imputer_keep_empty_features(initial_strategy): + """Check the behaviour of the iterative imputer with different initial strategy + and keeping empty features (i.e. features containing only missing values). + """ + X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]]) + + imputer = IterativeImputer( + initial_strategy=initial_strategy, keep_empty_features=True + ) + X_imputed = imputer.fit_transform(X) + assert_allclose(X_imputed[:, 1], 0) + X_imputed = imputer.transform(X) + assert_allclose(X_imputed[:, 1], 0) + + +# TODO (1.8): check that `keep_empty_features=False` drop the +# empty features due to the behaviour change. +def test_iterative_imputer_constant_fill_value(): + """Check that we propagate properly the parameter `fill_value`.""" + X = np.array([[-1, 2, 3, -1], [4, -1, 5, -1], [6, 7, -1, -1], [8, 9, 0, -1]]) + + fill_value = 100 + imputer = IterativeImputer( + missing_values=-1, + initial_strategy="constant", + fill_value=fill_value, + max_iter=0, + keep_empty_features=True, + ) + imputer.fit_transform(X) + assert_array_equal(imputer.initial_imputer_.statistics_, fill_value) + + +def test_iterative_imputer_min_max_value_remove_empty(): + """Check that we properly apply the empty feature mask to `min_value` and + `max_value`. + + Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29355 + """ + # Intentionally make column 2 as a missing column, then the bound of the imputed + # value of column 3 should be (4, 5) + X = np.array( + [ + [1, 2, np.nan, np.nan], + [4, 5, np.nan, 6], + [7, 8, np.nan, np.nan], + [10, 11, np.nan, 12], + ] + ) + min_value = [-np.inf, -np.inf, -np.inf, 4] + max_value = [np.inf, np.inf, np.inf, 5] + + X_imputed = IterativeImputer( + min_value=min_value, + max_value=max_value, + keep_empty_features=False, + ).fit_transform(X) + + X_without_missing_column = np.delete(X, 2, axis=1) + assert X_imputed.shape == X_without_missing_column.shape + assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(4) + assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(5) + + # Intentionally make column 3 as a missing column, then the bound of the imputed + # value of column 2 should be (3.5, 6) + X = np.array( + [ + [1, 2, np.nan, np.nan], + [4, 5, 6, np.nan], + [7, 8, np.nan, np.nan], + [10, 11, 12, np.nan], + ] + ) + min_value = [-np.inf, -np.inf, 3.5, -np.inf] + max_value = [np.inf, np.inf, 6, np.inf] + + X_imputed = IterativeImputer( + min_value=min_value, + max_value=max_value, + keep_empty_features=False, + ).fit_transform(X) + + X_without_missing_column = X[:, :3] + assert X_imputed.shape == X_without_missing_column.shape + assert np.min(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(3.5) + assert np.max(X_imputed[np.isnan(X_without_missing_column)]) == pytest.approx(6) + + +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_knn_imputer_keep_empty_features(keep_empty_features): + """Check the behaviour of `keep_empty_features` for `KNNImputer`.""" + X = np.array([[1, np.nan, 2], [3, np.nan, np.nan]]) + + imputer = KNNImputer(keep_empty_features=keep_empty_features) + + for method in ["fit_transform", "transform"]: + X_imputed = getattr(imputer, method)(X) + if keep_empty_features: + assert X_imputed.shape == X.shape + assert_array_equal(X_imputed[:, 1], 0) + else: + assert X_imputed.shape == (X.shape[0], X.shape[1] - 1) + + +def test_simple_impute_pd_na(): + pd = pytest.importorskip("pandas") + + # Impute pandas array of string types. + df = pd.DataFrame({"feature": pd.Series(["abc", None, "de"], dtype="string")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value="na") + _assert_array_equal_and_same_dtype( + imputer.fit_transform(df), np.array([["abc"], ["na"], ["de"]], dtype=object) + ) + + # Impute pandas array of string types without any missing values. + df = pd.DataFrame({"feature": pd.Series(["abc", "de", "fgh"], dtype="string")}) + imputer = SimpleImputer(fill_value="ok", strategy="constant") + _assert_array_equal_and_same_dtype( + imputer.fit_transform(df), np.array([["abc"], ["de"], ["fgh"]], dtype=object) + ) + + # Impute pandas array of integer types. + df = pd.DataFrame({"feature": pd.Series([1, None, 3], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-1) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64") + ) + + # Use `np.nan` also works. + imputer = SimpleImputer(missing_values=np.nan, strategy="constant", fill_value=-1) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [-1], [3]], dtype="float64") + ) + + # Impute pandas array of integer types with 'median' strategy. + df = pd.DataFrame({"feature": pd.Series([1, None, 2, 3], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="median") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [2], [2], [3]], dtype="float64") + ) + + # Impute pandas array of integer types with 'mean' strategy. + df = pd.DataFrame({"feature": pd.Series([1, None, 2], dtype="Int64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="mean") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1], [1.5], [2]], dtype="float64") + ) + + # Impute pandas array of float types. + df = pd.DataFrame({"feature": pd.Series([1.0, None, 3.0], dtype="float64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="constant", fill_value=-2.0) + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), np.array([[1.0], [-2.0], [3.0]], dtype="float64") + ) + + # Impute pandas array of float types with 'median' strategy. + df = pd.DataFrame({"feature": pd.Series([1.0, None, 2.0, 3.0], dtype="float64")}) + imputer = SimpleImputer(missing_values=pd.NA, strategy="median") + _assert_allclose_and_same_dtype( + imputer.fit_transform(df), + np.array([[1.0], [2.0], [2.0], [3.0]], dtype="float64"), + ) + + +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) + + +def test_imputer_lists_fit_transform(): + """Check transform uses object dtype when fitted on an object dtype. + + Non-regression test for #19572. + """ + + X = [["a", "b"], ["c", "b"], ["a", "a"]] + imp_frequent = SimpleImputer(strategy="most_frequent").fit(X) + X_trans = imp_frequent.transform([[np.nan, np.nan]]) + assert X_trans.dtype == object + assert_array_equal(X_trans, [["a", "b"]]) + + +@pytest.mark.parametrize("dtype_test", [np.float32, np.float64]) +def test_imputer_transform_preserves_numeric_dtype(dtype_test): + """Check transform preserves numeric dtype independent of fit dtype.""" + X = np.asarray( + [[1.2, 3.4, np.nan], [np.nan, 1.2, 1.3], [4.2, 2, 1]], dtype=np.float64 + ) + imp = SimpleImputer().fit(X) + + X_test = np.asarray([[np.nan, np.nan, np.nan]], dtype=dtype_test) + X_trans = imp.transform(X_test) + assert X_trans.dtype == dtype_test + + +@pytest.mark.parametrize("array_type", ["array", "sparse"]) +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_simple_imputer_constant_keep_empty_features(array_type, keep_empty_features): + """Check the behaviour of `keep_empty_features` with `strategy='constant'. + For backward compatibility, a column full of missing values will always be + fill and never dropped. + """ + X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]]) + X = _convert_container(X, array_type) + fill_value = 10 + imputer = SimpleImputer( + strategy="constant", + fill_value=fill_value, + keep_empty_features=keep_empty_features, + ) + + for method in ["fit_transform", "transform"]: + # TODO(1.8): Remove the condition and still call getattr(imputer, method)(X) + if method.startswith("fit") and not keep_empty_features: + warn_msg = '`strategy="constant"`, empty features are not dropped. ' + with pytest.warns(FutureWarning, match=warn_msg): + X_imputed = getattr(imputer, method)(X) + else: + X_imputed = getattr(imputer, method)(X) + assert X_imputed.shape == X.shape + constant_feature = ( + X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0] + ) + assert_array_equal(constant_feature, fill_value) + + +@pytest.mark.parametrize("array_type", ["array", "sparse"]) +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent"]) +@pytest.mark.parametrize("keep_empty_features", [True, False]) +def test_simple_imputer_keep_empty_features(strategy, array_type, keep_empty_features): + """Check the behaviour of `keep_empty_features` with all strategies but + 'constant'. + """ + X = np.array([[np.nan, 2], [np.nan, 3], [np.nan, 6]]) + X = _convert_container(X, array_type) + imputer = SimpleImputer(strategy=strategy, keep_empty_features=keep_empty_features) + + for method in ["fit_transform", "transform"]: + X_imputed = getattr(imputer, method)(X) + if keep_empty_features: + assert X_imputed.shape == X.shape + constant_feature = ( + X_imputed[:, 0].toarray() if array_type == "sparse" else X_imputed[:, 0] + ) + assert_array_equal(constant_feature, 0) + else: + assert X_imputed.shape == (X.shape[0], X.shape[1] - 1) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_imputation_custom(csc_container): + X = np.array( + [ + [1.1, 1.1, 1.1], + [3.9, 1.2, np.nan], + [np.nan, 1.3, np.nan], + [0.1, 1.4, 1.4], + [4.9, 1.5, 1.5], + [np.nan, 1.6, 1.6], + ] + ) + + X_true = np.array( + [ + [1.1, 1.1, 1.1], + [3.9, 1.2, 1.1], + [0.1, 1.3, 1.1], + [0.1, 1.4, 1.4], + [4.9, 1.5, 1.5], + [0.1, 1.6, 1.6], + ] + ) + + imputer = SimpleImputer(missing_values=np.nan, strategy=np.min) + X_trans = imputer.fit_transform(X) + assert_array_equal(X_trans, X_true) + + # Sparse matrix + imputer = SimpleImputer(missing_values=np.nan, strategy=np.min) + X_trans = imputer.fit_transform(csc_container(X)) + assert_array_equal(X_trans.toarray(), X_true) + + +def test_simple_imputer_constant_fill_value_casting(): + """Check that we raise a proper error message when we cannot cast the fill value + to the input data type. Otherwise, check that the casting is done properly. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/28309 + """ + # cannot cast fill_value at fit + fill_value = 1.5 + X_int64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.int64) + imputer = SimpleImputer( + strategy="constant", fill_value=fill_value, missing_values=2 + ) + err_msg = f"fill_value={fill_value!r} (of type {type(fill_value)!r}) cannot be cast" + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer.fit(X_int64) + + # cannot cast fill_value at transform + X_float64 = np.array([[1, 2, 3], [2, 3, 4]], dtype=np.float64) + imputer.fit(X_float64) + err_msg = ( + f"The dtype of the filling value (i.e. {imputer.statistics_.dtype!r}) " + "cannot be cast" + ) + with pytest.raises(ValueError, match=re.escape(err_msg)): + imputer.transform(X_int64) + + # check that no error is raised when having the same kind of dtype + fill_value_list = [np.float64(1.5), 1.5, 1] + X_float32 = X_float64.astype(np.float32) + + for fill_value in fill_value_list: + imputer = SimpleImputer( + strategy="constant", fill_value=fill_value, missing_values=2 + ) + X_trans = imputer.fit_transform(X_float32) + assert X_trans.dtype == X_float32.dtype + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +def test_iterative_imputer_no_empty_features(strategy): + """Check the behaviour of `keep_empty_features` with no empty features. + + With no-empty features, we should get the same imputation whatever the + parameter `keep_empty_features`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/29375 + """ + X = np.array([[np.nan, 0, 1], [2, np.nan, 3], [4, 5, np.nan]]) + + imputer_drop_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=1, keep_empty_features=False + ) + + imputer_keep_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=1, keep_empty_features=True + ) + + assert_allclose( + imputer_drop_empty_features.fit_transform(X), + imputer_keep_empty_features.fit_transform(X), + ) + + +@pytest.mark.parametrize("strategy", ["mean", "median", "most_frequent", "constant"]) +@pytest.mark.parametrize( + "X_test", + [ + np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), # without empty feature + np.array([[np.nan, 2, 3, 4], [np.nan, 6, 7, 8]]), # empty feature at column 0 + np.array([[1, 2, 3, np.nan], [5, 6, 7, np.nan]]), # empty feature at column 3 + ], +) +def test_iterative_imputer_with_empty_features(strategy, X_test): + """Check the behaviour of `keep_empty_features` in the presence of empty features. + + With `keep_empty_features=True`, the empty feature will be imputed with the value + defined by the initial imputation. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/29375 + """ + X_train = np.array( + [[np.nan, np.nan, 0, 1], [np.nan, 2, np.nan, 3], [np.nan, 4, 5, np.nan]] + ) + + imputer_drop_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=0, keep_empty_features=False + ) + X_train_drop_empty_features = imputer_drop_empty_features.fit_transform(X_train) + X_test_drop_empty_features = imputer_drop_empty_features.transform(X_test) + + imputer_keep_empty_features = IterativeImputer( + initial_strategy=strategy, fill_value=0, keep_empty_features=True + ) + X_train_keep_empty_features = imputer_keep_empty_features.fit_transform(X_train) + X_test_keep_empty_features = imputer_keep_empty_features.transform(X_test) + + assert_allclose(X_train_drop_empty_features, X_train_keep_empty_features[:, 1:]) + assert_allclose(X_train_keep_empty_features[:, 0], 0) + + assert X_train_drop_empty_features.shape[1] == X_test_drop_empty_features.shape[1] + assert X_train_keep_empty_features.shape[1] == X_test_keep_empty_features.shape[1] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_knn.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_knn.py new file mode 100644 index 0000000000000000000000000000000000000000..34244d628600fc29ae2af1e620f34c83eafc6d81 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/impute/tests/test_knn.py @@ -0,0 +1,570 @@ +import numpy as np +import pytest + +from sklearn import config_context +from sklearn.impute import KNNImputer +from sklearn.metrics.pairwise import nan_euclidean_distances, pairwise_distances +from sklearn.neighbors import KNeighborsRegressor +from sklearn.utils._testing import assert_allclose + + +@pytest.mark.parametrize("weights", ["uniform", "distance"]) +@pytest.mark.parametrize("n_neighbors", range(1, 6)) +def test_knn_imputer_shape(weights, n_neighbors): + # Verify the shapes of the imputed matrix for different weights and + # number of neighbors. + n_rows = 10 + n_cols = 2 + X = np.random.rand(n_rows, n_cols) + X[0, 0] = np.nan + + imputer = KNNImputer(n_neighbors=n_neighbors, weights=weights) + X_imputed = imputer.fit_transform(X) + assert X_imputed.shape == (n_rows, n_cols) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_default_with_invalid_input(na): + # Test imputation with default values and invalid input + + # Test with inf present + X = np.array( + [ + [np.inf, 1, 1, 2, na], + [2, 1, 2, 2, 3], + [3, 2, 3, 3, 8], + [na, 6, 0, 5, 13], + [na, 7, 0, 7, 8], + [6, 6, 2, 5, 7], + ] + ) + 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() + X = np.array( + [ + [np.inf, 1, 1, 2, na], + [2, 1, 2, 2, 3], + [3, 2, 3, 3, 8], + [na, 6, 0, 5, 13], + [na, 7, 0, 7, 8], + [6, 6, 2, 5, 7], + ] + ) + + X_fit = np.array( + [ + [0, 1, 1, 2, na], + [2, 1, 2, 2, 3], + [3, 2, 3, 3, 8], + [na, 6, 0, 5, 13], + [na, 7, 0, 7, 8], + [6, 6, 2, 5, 7], + ] + ) + imputer = KNNImputer(missing_values=na).fit(X_fit) + with pytest.raises(ValueError, match="Input X contains (infinity|NaN)"): + imputer.transform(X) + + # Test with missing_values=0 when NaN present + imputer = KNNImputer(missing_values=0, n_neighbors=2, weights="uniform") + X = np.array( + [ + [np.nan, 0, 0, 0, 5], + [np.nan, 1, 0, np.nan, 3], + [np.nan, 2, 0, 0, 0], + [np.nan, 6, 0, 5, 13], + ] + ) + msg = "Input X contains NaN" + with pytest.raises(ValueError, match=msg): + imputer.fit(X) + + X = np.array( + [ + [0, 0], + [np.nan, 2], + ] + ) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_removes_all_na_features(na): + X = np.array( + [ + [1, 1, na, 1, 1, 1.0], + [2, 3, na, 2, 2, 2], + [3, 4, na, 3, 3, na], + [6, 4, na, na, 6, 6], + ] + ) + knn = KNNImputer(missing_values=na, n_neighbors=2).fit(X) + + X_transform = knn.transform(X) + assert not np.isnan(X_transform).any() + assert X_transform.shape == (4, 5) + + X_test = np.arange(0, 12).reshape(2, 6) + X_transform = knn.transform(X_test) + assert_allclose(X_test[:, [0, 1, 3, 4, 5]], X_transform) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_zero_nan_imputes_the_same(na): + # Test with an imputable matrix and compare with different missing_values + X_zero = np.array( + [ + [1, 0, 1, 1, 1.0], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 0], + [6, 6, 0, 6, 6], + ] + ) + + X_nan = np.array( + [ + [1, na, 1, 1, 1.0], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, na], + [6, 6, na, 6, 6], + ] + ) + + X_imputed = np.array( + [ + [1, 2.5, 1, 1, 1.0], + [2, 2, 2, 2, 2], + [3, 3, 3, 3, 1.5], + [6, 6, 2.5, 6, 6], + ] + ) + + imputer_zero = KNNImputer(missing_values=0, n_neighbors=2, weights="uniform") + + imputer_nan = KNNImputer(missing_values=na, n_neighbors=2, weights="uniform") + + assert_allclose(imputer_zero.fit_transform(X_zero), X_imputed) + assert_allclose( + imputer_zero.fit_transform(X_zero), imputer_nan.fit_transform(X_nan) + ) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_verify(na): + # Test with an imputable matrix + X = np.array( + [ + [1, 0, 0, 1], + [2, 1, 2, na], + [3, 2, 3, na], + [na, 4, 5, 5], + [6, na, 6, 7], + [8, 8, 8, 8], + [16, 15, 18, 19], + ] + ) + + X_imputed = np.array( + [ + [1, 0, 0, 1], + [2, 1, 2, 8], + [3, 2, 3, 8], + [4, 4, 5, 5], + [6, 3, 6, 7], + [8, 8, 8, 8], + [16, 15, 18, 19], + ] + ) + + imputer = KNNImputer(missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed) + + # Test when there is not enough neighbors + X = np.array( + [ + [1, 0, 0, na], + [2, 1, 2, na], + [3, 2, 3, na], + [4, 4, 5, na], + [6, 7, 6, na], + [8, 8, 8, na], + [20, 20, 20, 20], + [22, 22, 22, 22], + ] + ) + + # Not enough neighbors, use column mean from training + X_impute_value = (20 + 22) / 2 + X_imputed = np.array( + [ + [1, 0, 0, X_impute_value], + [2, 1, 2, X_impute_value], + [3, 2, 3, X_impute_value], + [4, 4, 5, X_impute_value], + [6, 7, 6, X_impute_value], + [8, 8, 8, X_impute_value], + [20, 20, 20, 20], + [22, 22, 22, 22], + ] + ) + + imputer = KNNImputer(missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed) + + # Test when data in fit() and transform() are different + X = np.array([[0, 0], [na, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 16]]) + + X1 = np.array([[1, 0], [3, 2], [4, na]]) + + X_2_1 = (0 + 3 + 6 + 7 + 8) / 5 + X1_imputed = np.array([[1, 0], [3, 2], [4, X_2_1]]) + + imputer = KNNImputer(missing_values=na) + assert_allclose(imputer.fit(X).transform(X1), X1_imputed) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_one_n_neighbors(na): + X = np.array([[0, 0], [na, 2], [4, 3], [5, na], [7, 7], [na, 8], [14, 13]]) + + X_imputed = np.array([[0, 0], [4, 2], [4, 3], [5, 3], [7, 7], [7, 8], [14, 13]]) + + imputer = KNNImputer(n_neighbors=1, missing_values=na) + + assert_allclose(imputer.fit_transform(X), X_imputed) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_all_samples_are_neighbors(na): + X = np.array([[0, 0], [na, 2], [4, 3], [5, na], [7, 7], [na, 8], [14, 13]]) + + X_imputed = np.array( + [[0, 0], [6.25, 2], [4, 3], [5, 5.75], [7, 7], [6.25, 8], [14, 13]] + ) + + n_neighbors = X.shape[0] - 1 + imputer = KNNImputer(n_neighbors=n_neighbors, missing_values=na) + + assert_allclose(imputer.fit_transform(X), X_imputed) + + n_neighbors = X.shape[0] + imputer_plus1 = KNNImputer(n_neighbors=n_neighbors, missing_values=na) + assert_allclose(imputer_plus1.fit_transform(X), X_imputed) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_weight_uniform(na): + X = np.array([[0, 0], [na, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 10]]) + + # Test with "uniform" weight (or unweighted) + X_imputed_uniform = np.array( + [[0, 0], [5, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 10]] + ) + + imputer = KNNImputer(weights="uniform", missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed_uniform) + + # Test with "callable" weight + def no_weight(dist): + return None + + imputer = KNNImputer(weights=no_weight, missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed_uniform) + + # Test with "callable" uniform weight + def uniform_weight(dist): + return np.ones_like(dist) + + imputer = KNNImputer(weights=uniform_weight, missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed_uniform) + + +@pytest.mark.parametrize("na", [np.nan, -1]) +def test_knn_imputer_weight_distance(na): + X = np.array([[0, 0], [na, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 10]]) + + # Test with "distance" weight + nn = KNeighborsRegressor(metric="euclidean", weights="distance") + X_rows_idx = [0, 2, 3, 4, 5, 6] + nn.fit(X[X_rows_idx, 1:], X[X_rows_idx, 0]) + knn_imputed_value = nn.predict(X[1:2, 1:])[0] + + # Manual calculation + X_neighbors_idx = [0, 2, 3, 4, 5] + dist = nan_euclidean_distances(X[1:2, :], X, missing_values=na) + weights = 1 / dist[:, X_neighbors_idx].ravel() + manual_imputed_value = np.average(X[X_neighbors_idx, 0], weights=weights) + + X_imputed_distance1 = np.array( + [[0, 0], [manual_imputed_value, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 10]] + ) + + # NearestNeighbor calculation + X_imputed_distance2 = np.array( + [[0, 0], [knn_imputed_value, 2], [4, 3], [5, 6], [7, 7], [9, 8], [11, 10]] + ) + + imputer = KNNImputer(weights="distance", missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed_distance1) + assert_allclose(imputer.fit_transform(X), X_imputed_distance2) + + # Test with weights = "distance" and n_neighbors=2 + X = np.array( + [ + [na, 0, 0], + [2, 1, 2], + [3, 2, 3], + [4, 5, 5], + ] + ) + + # neighbors are rows 1, 2, the nan_euclidean_distances are: + dist_0_1 = np.sqrt((3 / 2) * ((1 - 0) ** 2 + (2 - 0) ** 2)) + dist_0_2 = np.sqrt((3 / 2) * ((2 - 0) ** 2 + (3 - 0) ** 2)) + imputed_value = np.average([2, 3], weights=[1 / dist_0_1, 1 / dist_0_2]) + + X_imputed = np.array( + [ + [imputed_value, 0, 0], + [2, 1, 2], + [3, 2, 3], + [4, 5, 5], + ] + ) + + imputer = KNNImputer(n_neighbors=2, weights="distance", missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed) + + # Test with varying missingness patterns + X = np.array( + [ + [1, 0, 0, 1], + [0, na, 1, na], + [1, 1, 1, na], + [0, 1, 0, 0], + [0, 0, 0, 0], + [1, 0, 1, 1], + [10, 10, 10, 10], + ] + ) + + # Get weights of donor neighbors + dist = nan_euclidean_distances(X, missing_values=na) + r1c1_nbor_dists = dist[1, [0, 2, 3, 4, 5]] + r1c3_nbor_dists = dist[1, [0, 3, 4, 5, 6]] + r1c1_nbor_wt = 1 / r1c1_nbor_dists + r1c3_nbor_wt = 1 / r1c3_nbor_dists + + r2c3_nbor_dists = dist[2, [0, 3, 4, 5, 6]] + r2c3_nbor_wt = 1 / r2c3_nbor_dists + + # Collect donor values + col1_donor_values = np.ma.masked_invalid(X[[0, 2, 3, 4, 5], 1]).copy() + col3_donor_values = np.ma.masked_invalid(X[[0, 3, 4, 5, 6], 3]).copy() + + # Final imputed values + r1c1_imp = np.ma.average(col1_donor_values, weights=r1c1_nbor_wt) + r1c3_imp = np.ma.average(col3_donor_values, weights=r1c3_nbor_wt) + r2c3_imp = np.ma.average(col3_donor_values, weights=r2c3_nbor_wt) + + X_imputed = np.array( + [ + [1, 0, 0, 1], + [0, r1c1_imp, 1, r1c3_imp], + [1, 1, 1, r2c3_imp], + [0, 1, 0, 0], + [0, 0, 0, 0], + [1, 0, 1, 1], + [10, 10, 10, 10], + ] + ) + + imputer = KNNImputer(weights="distance", missing_values=na) + assert_allclose(imputer.fit_transform(X), X_imputed) + + X = np.array( + [ + [0, 0, 0, na], + [1, 1, 1, na], + [2, 2, na, 2], + [3, 3, 3, 3], + [4, 4, 4, 4], + [5, 5, 5, 5], + [6, 6, 6, 6], + [na, 7, 7, 7], + ] + ) + + dist = pairwise_distances( + X, metric="nan_euclidean", squared=False, missing_values=na + ) + + # Calculate weights + r0c3_w = 1.0 / dist[0, 2:-1] + r1c3_w = 1.0 / dist[1, 2:-1] + r2c2_w = 1.0 / dist[2, (0, 1, 3, 4, 5)] + r7c0_w = 1.0 / dist[7, 2:7] + + # Calculate weighted averages + r0c3 = np.average(X[2:-1, -1], weights=r0c3_w) + r1c3 = np.average(X[2:-1, -1], weights=r1c3_w) + r2c2 = np.average(X[(0, 1, 3, 4, 5), 2], weights=r2c2_w) + r7c0 = np.average(X[2:7, 0], weights=r7c0_w) + + X_imputed = np.array( + [ + [0, 0, 0, r0c3], + [1, 1, 1, r1c3], + [2, 2, r2c2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4], + [5, 5, 5, 5], + [6, 6, 6, 6], + [r7c0, 7, 7, 7], + ] + ) + + imputer_comp_wt = KNNImputer(missing_values=na, weights="distance") + assert_allclose(imputer_comp_wt.fit_transform(X), X_imputed) + + +def test_knn_imputer_callable_metric(): + # Define callable metric that returns the l1 norm: + def custom_callable(x, y, missing_values=np.nan, squared=False): + x = np.ma.array(x, mask=np.isnan(x)) + y = np.ma.array(y, mask=np.isnan(y)) + dist = np.nansum(np.abs(x - y)) + return dist + + X = np.array([[4, 3, 3, np.nan], [6, 9, 6, 9], [4, 8, 6, 9], [np.nan, 9, 11, 10.0]]) + + X_0_3 = (9 + 9) / 2 + X_3_0 = (6 + 4) / 2 + X_imputed = np.array( + [[4, 3, 3, X_0_3], [6, 9, 6, 9], [4, 8, 6, 9], [X_3_0, 9, 11, 10.0]] + ) + + imputer = KNNImputer(n_neighbors=2, metric=custom_callable) + assert_allclose(imputer.fit_transform(X), X_imputed) + + +@pytest.mark.parametrize("working_memory", [None, 0]) +@pytest.mark.parametrize("na", [-1, np.nan]) +# Note that we use working_memory=0 to ensure that chunking is tested, even +# for a small dataset. However, it should raise a UserWarning that we ignore. +@pytest.mark.filterwarnings("ignore:adhere to working_memory") +def test_knn_imputer_with_simple_example(na, working_memory): + X = np.array( + [ + [0, na, 0, na], + [1, 1, 1, na], + [2, 2, na, 2], + [3, 3, 3, 3], + [4, 4, 4, 4], + [5, 5, 5, 5], + [6, 6, 6, 6], + [na, 7, 7, 7], + ] + ) + + r0c1 = np.mean(X[1:6, 1]) + r0c3 = np.mean(X[2:-1, -1]) + r1c3 = np.mean(X[2:-1, -1]) + r2c2 = np.mean(X[[0, 1, 3, 4, 5], 2]) + r7c0 = np.mean(X[2:-1, 0]) + + X_imputed = np.array( + [ + [0, r0c1, 0, r0c3], + [1, 1, 1, r1c3], + [2, 2, r2c2, 2], + [3, 3, 3, 3], + [4, 4, 4, 4], + [5, 5, 5, 5], + [6, 6, 6, 6], + [r7c0, 7, 7, 7], + ] + ) + + with config_context(working_memory=working_memory): + imputer_comp = KNNImputer(missing_values=na) + assert_allclose(imputer_comp.fit_transform(X), X_imputed) + + +@pytest.mark.parametrize("na", [-1, np.nan]) +@pytest.mark.parametrize("weights", ["uniform", "distance"]) +def test_knn_imputer_not_enough_valid_distances(na, weights): + # Samples with needed feature has nan distance + X1 = np.array([[na, 11], [na, 1], [3, na]]) + X1_imputed = np.array([[3, 11], [3, 1], [3, 6]]) + + knn = KNNImputer(missing_values=na, n_neighbors=1, weights=weights) + assert_allclose(knn.fit_transform(X1), X1_imputed) + + X2 = np.array([[4, na]]) + X2_imputed = np.array([[4, 6]]) + assert_allclose(knn.transform(X2), X2_imputed) + + +@pytest.mark.parametrize("na", [-1, np.nan]) +@pytest.mark.parametrize("weights", ["uniform", "distance"]) +def test_knn_imputer_nan_distance(na, weights): + # Samples with nan distance should be excluded from the mean computation + X1_train = np.array([[1, 1], [na, 2]]) + X1_test = np.array([[0, na]]) + X1_test_expected = np.array([[0, 1]]) + + knn1 = KNNImputer(n_neighbors=2, missing_values=na, weights=weights) + knn1.fit(X1_train) + assert_allclose(knn1.transform(X1_test), X1_test_expected) + + X2_train = np.array([[na, 1, 1], [2, na, 2], [3, 3, na]]) + X2_test = np.array([[na, 0, na], [0, na, na], [na, na, 0]]) + X2_test_expected = np.array([[3, 0, 1], [0, 3, 2], [2, 1, 0]]) + + knn2 = KNNImputer(n_neighbors=2, missing_values=na, weights=weights) + knn2.fit(X2_train) + assert_allclose(knn2.transform(X2_test), X2_test_expected) + + +@pytest.mark.parametrize("na", [-1, np.nan]) +def test_knn_imputer_drops_all_nan_features(na): + X1 = np.array([[na, 1], [na, 2]]) + knn = KNNImputer(missing_values=na, n_neighbors=1) + X1_expected = np.array([[1], [2]]) + assert_allclose(knn.fit_transform(X1), X1_expected) + + X2 = np.array([[1, 2], [3, na]]) + X2_expected = np.array([[2], [1.5]]) + assert_allclose(knn.transform(X2), X2_expected) + + +@pytest.mark.parametrize("working_memory", [None, 0]) +@pytest.mark.parametrize("na", [-1, np.nan]) +def test_knn_imputer_distance_weighted_not_enough_neighbors(na, working_memory): + X = np.array([[3, na], [2, na], [na, 4], [5, 6], [6, 8], [na, 5]]) + + dist = pairwise_distances( + X, metric="nan_euclidean", squared=False, missing_values=na + ) + + X_01 = np.average(X[3:5, 1], weights=1 / dist[0, 3:5]) + X_11 = np.average(X[3:5, 1], weights=1 / dist[1, 3:5]) + X_20 = np.average(X[3:5, 0], weights=1 / dist[2, 3:5]) + X_50 = np.average(X[3:5, 0], weights=1 / dist[5, 3:5]) + + X_expected = np.array([[3, X_01], [2, X_11], [X_20, 4], [5, 6], [6, 8], [X_50, 5]]) + + with config_context(working_memory=working_memory): + knn_3 = KNNImputer(missing_values=na, n_neighbors=3, weights="distance") + assert_allclose(knn_3.fit_transform(X), X_expected) + + knn_4 = KNNImputer(missing_values=na, n_neighbors=4, weights="distance") + assert_allclose(knn_4.fit_transform(X), X_expected) + + +@pytest.mark.parametrize("na, allow_nan", [(-1, False), (np.nan, True)]) +def test_knn_tags(na, allow_nan): + knn = KNNImputer(missing_values=na) + assert knn.__sklearn_tags__().input_tags.allow_nan == allow_nan diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0a1125ef04198083da041736a7ebc2ffeafe6a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/__init__.py @@ -0,0 +1,16 @@ +"""Tools for model inspection.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._partial_dependence import partial_dependence +from ._permutation_importance import permutation_importance +from ._plot.decision_boundary import DecisionBoundaryDisplay +from ._plot.partial_dependence import PartialDependenceDisplay + +__all__ = [ + "DecisionBoundaryDisplay", + "PartialDependenceDisplay", + "partial_dependence", + "permutation_importance", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_partial_dependence.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_partial_dependence.py new file mode 100644 index 0000000000000000000000000000000000000000..ad352c45cc03bd6018617c4ccaa6247fd68718b5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_partial_dependence.py @@ -0,0 +1,775 @@ +"""Partial dependence plots for regression and classification models.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from collections.abc import Iterable + +import numpy as np +from scipy import sparse +from scipy.stats.mstats import mquantiles + +from ..base import is_classifier, is_regressor +from ..ensemble import RandomForestRegressor +from ..ensemble._gb import BaseGradientBoosting +from ..ensemble._hist_gradient_boosting.gradient_boosting import ( + BaseHistGradientBoosting, +) +from ..tree import DecisionTreeRegressor +from ..utils import Bunch, _safe_indexing, check_array +from ..utils._indexing import _determine_key_type, _get_column_indices, _safe_assign +from ..utils._optional_dependencies import check_matplotlib_support # noqa: F401 +from ..utils._param_validation import ( + HasMethods, + Integral, + Interval, + StrOptions, + validate_params, +) +from ..utils._response import _get_response_values +from ..utils.extmath import cartesian +from ..utils.validation import _check_sample_weight, check_is_fitted +from ._pd_utils import _check_feature_names, _get_feature_index + +__all__ = [ + "partial_dependence", +] + + +def _grid_from_X(X, percentiles, is_categorical, grid_resolution, custom_values): + """Generate a grid of points based on the percentiles of X. + + The grid is a cartesian product between the columns of ``values``. The + ith column of ``values`` consists in ``grid_resolution`` equally-spaced + points between the percentiles of the jth column of X. + + If ``grid_resolution`` is bigger than the number of unique values in the + j-th column of X or if the feature is a categorical feature (by inspecting + `is_categorical`) , then those unique values will be used instead. + + Parameters + ---------- + X : array-like of shape (n_samples, n_target_features) + The data. + + percentiles : tuple of float + The percentiles which are used to construct the extreme values of + the grid. Must be in [0, 1]. + + is_categorical : list of bool + For each feature, tells whether it is categorical or not. If a feature + is categorical, then the values used will be the unique ones + (i.e. categories) instead of the percentiles. + + grid_resolution : int + The number of equally spaced points to be placed on the grid for each + feature. + + custom_values: dict + Mapping from column index of X to an array-like of values where + the partial dependence should be calculated for that feature + + Returns + ------- + grid : ndarray of shape (n_points, n_target_features) + A value for each feature at each point in the grid. ``n_points`` is + always ``<= grid_resolution ** X.shape[1]``. + + values : list of 1d ndarrays + The values with which the grid has been created. The size of each + array ``values[j]`` is either ``grid_resolution``, the number of + unique values in ``X[:, j]``, if j is not in ``custom_range``. + If j is in ``custom_range``, then it is the length of ``custom_range[j]``. + """ + if not isinstance(percentiles, Iterable) or len(percentiles) != 2: + raise ValueError("'percentiles' must be a sequence of 2 elements.") + if not all(0 <= x <= 1 for x in percentiles): + raise ValueError("'percentiles' values must be in [0, 1].") + if percentiles[0] >= percentiles[1]: + raise ValueError("percentiles[0] must be strictly less than percentiles[1].") + + if grid_resolution <= 1: + raise ValueError("'grid_resolution' must be strictly greater than 1.") + + def _convert_custom_values(values): + # Convert custom types such that object types are always used for string arrays + dtype = object if any(isinstance(v, str) for v in values) else None + return np.asarray(values, dtype=dtype) + + custom_values = {k: _convert_custom_values(v) for k, v in custom_values.items()} + if any(v.ndim != 1 for v in custom_values.values()): + error_string = ", ".join( + f"Feature {k}: {v.ndim} dimensions" + for k, v in custom_values.items() + if v.ndim != 1 + ) + + raise ValueError( + "The custom grid for some features is not a one-dimensional array. " + f"{error_string}" + ) + + values = [] + # TODO: we should handle missing values (i.e. `np.nan`) specifically and store them + # in a different Bunch attribute. + for feature, is_cat in enumerate(is_categorical): + if feature in custom_values: + # Use values in the custom range + axis = custom_values[feature] + else: + try: + uniques = np.unique(_safe_indexing(X, feature, axis=1)) + except TypeError as exc: + # `np.unique` will fail in the presence of `np.nan` and `str` categories + # due to sorting. Temporary, we reraise an error explaining the problem. + raise ValueError( + f"The column #{feature} contains mixed data types. Finding unique " + "categories fail due to sorting. It usually means that the column " + "contains `np.nan` values together with `str` categories. Such use " + "case is not yet supported in scikit-learn." + ) from exc + + if is_cat or uniques.shape[0] < grid_resolution: + # Use the unique values either because: + # - feature has low resolution use unique values + # - feature is categorical + axis = uniques + else: + # create axis based on percentiles and grid resolution + emp_percentiles = mquantiles( + _safe_indexing(X, feature, axis=1), prob=percentiles, axis=0 + ) + if np.allclose(emp_percentiles[0], emp_percentiles[1]): + raise ValueError( + "percentiles are too close to each other, " + "unable to build the grid. Please choose percentiles " + "that are further apart." + ) + axis = np.linspace( + emp_percentiles[0], + emp_percentiles[1], + num=grid_resolution, + endpoint=True, + ) + values.append(axis) + + return cartesian(values), values + + +def _partial_dependence_recursion(est, grid, features): + """Calculate partial dependence via the recursion method. + + The recursion method is in particular enabled for tree-based estimators. + + For each `grid` value, a weighted tree traversal is performed: if a split node + involves an input feature of interest, the corresponding left or right branch + is followed; otherwise both branches are followed, each branch being weighted + by the fraction of training samples that entered that branch. Finally, the + partial dependence is given by a weighted average of all the visited leaves + values. + + This method is more efficient in terms of speed than the `'brute'` method + (:func:`~sklearn.inspection._partial_dependence._partial_dependence_brute`). + However, here, the partial dependence computation is done explicitly with the + `X` used during training of `est`. + + Parameters + ---------- + est : BaseEstimator + A fitted estimator object implementing :term:`predict` or + :term:`decision_function`. Multioutput-multiclass classifiers are not + supported. Note that `'recursion'` is only supported for some tree-based + estimators (namely + :class:`~sklearn.ensemble.GradientBoostingClassifier`, + :class:`~sklearn.ensemble.GradientBoostingRegressor`, + :class:`~sklearn.ensemble.HistGradientBoostingClassifier`, + :class:`~sklearn.ensemble.HistGradientBoostingRegressor`, + :class:`~sklearn.tree.DecisionTreeRegressor`, + :class:`~sklearn.ensemble.RandomForestRegressor`, + ). + + grid : array-like of shape (n_points, n_target_features) + The grid of feature values for which the partial dependence is calculated. + Note that `n_points` is the number of points in the grid and `n_target_features` + is the number of features you are doing partial dependence at. + + features : array-like of {int, str} + The feature (e.g. `[0]`) or pair of interacting features + (e.g. `[(0, 1)]`) for which the partial dependency should be computed. + + Returns + ------- + averaged_predictions : array-like of shape (n_targets, n_points) + The averaged predictions for the given `grid` of features values. + Note that `n_targets` is the number of targets (e.g. 1 for binary + classification, `n_tasks` for multi-output regression, and `n_classes` for + multiclass classification) and `n_points` is the number of points in the `grid`. + """ + averaged_predictions = est._compute_partial_dependence_recursion(grid, features) + if averaged_predictions.ndim == 1: + # reshape to (1, n_points) for consistency with + # _partial_dependence_brute + averaged_predictions = averaged_predictions.reshape(1, -1) + + return averaged_predictions + + +def _partial_dependence_brute( + est, grid, features, X, response_method, sample_weight=None +): + """Calculate partial dependence via the brute force method. + + The brute method explicitly averages the predictions of an estimator over a + grid of feature values. + + For each `grid` value, all the samples from `X` have their variables of + interest replaced by that specific `grid` value. The predictions are then made + and averaged across the samples. + + This method is slower than the `'recursion'` + (:func:`~sklearn.inspection._partial_dependence._partial_dependence_recursion`) + version for estimators with this second option. However, with the `'brute'` + force method, the average will be done with the given `X` and not the `X` + used during training, as it is done in the `'recursion'` version. Therefore + the average can always accept `sample_weight` (even when the estimator was + fitted without). + + Parameters + ---------- + est : BaseEstimator + A fitted estimator object implementing :term:`predict`, + :term:`predict_proba`, or :term:`decision_function`. + Multioutput-multiclass classifiers are not supported. + + grid : array-like of shape (n_points, n_target_features) + The grid of feature values for which the partial dependence is calculated. + Note that `n_points` is the number of points in the grid and `n_target_features` + is the number of features you are doing partial dependence at. + + features : array-like of {int, str} + The feature (e.g. `[0]`) or pair of interacting features + (e.g. `[(0, 1)]`) for which the partial dependency should be computed. + + X : array-like of shape (n_samples, n_features) + `X` is used to generate values for the complement features. That is, for + each value in `grid`, the method will average the prediction of each + sample from `X` having that grid value for `features`. + + response_method : {'auto', 'predict_proba', 'decision_function'}, \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. For regressors + this parameter is ignored and the response is always the output of + :term:`predict`. By default, :term:`predict_proba` is tried first + and we revert to :term:`decision_function` if it doesn't exist. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights are used to calculate weighted means when averaging the + model output. If `None`, then samples are equally weighted. Note that + `sample_weight` does not change the individual predictions. + + Returns + ------- + averaged_predictions : array-like of shape (n_targets, n_points) + The averaged predictions for the given `grid` of features values. + Note that `n_targets` is the number of targets (e.g. 1 for binary + classification, `n_tasks` for multi-output regression, and `n_classes` for + multiclass classification) and `n_points` is the number of points in the `grid`. + + predictions : array-like + The predictions for the given `grid` of features values over the samples + from `X`. For non-multioutput regression and binary classification the + shape is `(n_instances, n_points)` and for multi-output regression and + multiclass classification the shape is `(n_targets, n_instances, n_points)`, + where `n_targets` is the number of targets (`n_tasks` for multi-output + regression, and `n_classes` for multiclass classification), `n_instances` + is the number of instances in `X`, and `n_points` is the number of points + in the `grid`. + """ + predictions = [] + averaged_predictions = [] + + if response_method == "auto": + response_method = ( + "predict" if is_regressor(est) else ["predict_proba", "decision_function"] + ) + + X_eval = X.copy() + for new_values in grid: + for i, variable in enumerate(features): + _safe_assign(X_eval, new_values[i], column_indexer=variable) + + # Note: predictions is of shape + # (n_points,) for non-multioutput regressors + # (n_points, n_tasks) for multioutput regressors + # (n_points, 1) for the regressors in cross_decomposition (I think) + # (n_points, 1) for binary classification (positive class already selected) + # (n_points, n_classes) for multiclass classification + pred, _ = _get_response_values(est, X_eval, response_method=response_method) + + predictions.append(pred) + # average over samples + averaged_predictions.append(np.average(pred, axis=0, weights=sample_weight)) + + n_samples = X.shape[0] + + # reshape to (n_targets, n_instances, n_points) where n_targets is: + # - 1 for non-multioutput regression and binary classification (shape is + # already correct in those cases) + # - n_tasks for multi-output regression + # - n_classes for multiclass classification. + predictions = np.array(predictions).T + if is_regressor(est) and predictions.ndim == 2: + # non-multioutput regression, shape is (n_instances, n_points,) + predictions = predictions.reshape(n_samples, -1) + elif is_classifier(est) and predictions.shape[0] == 2: + # Binary classification, shape is (2, n_instances, n_points). + # we output the effect of **positive** class + predictions = predictions[1] + predictions = predictions.reshape(n_samples, -1) + + # reshape averaged_predictions to (n_targets, n_points) where n_targets is: + # - 1 for non-multioutput regression and binary classification (shape is + # already correct in those cases) + # - n_tasks for multi-output regression + # - n_classes for multiclass classification. + averaged_predictions = np.array(averaged_predictions).T + if averaged_predictions.ndim == 1: + # reshape to (1, n_points) for consistency with + # _partial_dependence_recursion + averaged_predictions = averaged_predictions.reshape(1, -1) + + return averaged_predictions, predictions + + +@validate_params( + { + "estimator": [ + HasMethods(["fit", "predict"]), + HasMethods(["fit", "predict_proba"]), + HasMethods(["fit", "decision_function"]), + ], + "X": ["array-like", "sparse matrix"], + "features": ["array-like", Integral, str], + "sample_weight": ["array-like", None], + "categorical_features": ["array-like", None], + "feature_names": ["array-like", None], + "response_method": [StrOptions({"auto", "predict_proba", "decision_function"})], + "percentiles": [tuple], + "grid_resolution": [Interval(Integral, 1, None, closed="left")], + "method": [StrOptions({"auto", "recursion", "brute"})], + "kind": [StrOptions({"average", "individual", "both"})], + "custom_values": [dict, None], + }, + prefer_skip_nested_validation=True, +) +def partial_dependence( + estimator, + X, + features, + *, + sample_weight=None, + categorical_features=None, + feature_names=None, + response_method="auto", + percentiles=(0.05, 0.95), + grid_resolution=100, + custom_values=None, + method="auto", + kind="average", +): + """Partial dependence of ``features``. + + Partial dependence of a feature (or a set of features) corresponds to + the average response of an estimator for each possible value of the + feature. + + Read more in + :ref:`sphx_glr_auto_examples_inspection_plot_partial_dependence.py` + and the :ref:`User Guide `. + + .. warning:: + + For :class:`~sklearn.ensemble.GradientBoostingClassifier` and + :class:`~sklearn.ensemble.GradientBoostingRegressor`, the + `'recursion'` method (used by default) will not account for the `init` + predictor of the boosting process. In practice, this will produce + the same values as `'brute'` up to a constant offset in the target + response, provided that `init` is a constant estimator (which is the + default). However, if `init` is not a constant estimator, the + partial dependence values are incorrect for `'recursion'` because the + offset will be sample-dependent. It is preferable to use the `'brute'` + method. Note that this only applies to + :class:`~sklearn.ensemble.GradientBoostingClassifier` and + :class:`~sklearn.ensemble.GradientBoostingRegressor`, not to + :class:`~sklearn.ensemble.HistGradientBoostingClassifier` and + :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. + + Parameters + ---------- + estimator : BaseEstimator + A fitted estimator object implementing :term:`predict`, + :term:`predict_proba`, or :term:`decision_function`. + Multioutput-multiclass classifiers are not supported. + + X : {array-like, sparse matrix or dataframe} of shape (n_samples, n_features) + ``X`` is used to generate a grid of values for the target + ``features`` (where the partial dependence will be evaluated), and + also to generate values for the complement features when the + `method` is 'brute'. + + features : array-like of {int, str, bool} or int or str + The feature (e.g. `[0]`) or pair of interacting features + (e.g. `[(0, 1)]`) for which the partial dependency should be computed. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights are used to calculate weighted means when averaging the + model output. If `None`, then samples are equally weighted. If + `sample_weight` is not `None`, then `method` will be set to `'brute'`. + Note that `sample_weight` is ignored for `kind='individual'`. + + .. versionadded:: 1.3 + + categorical_features : array-like of shape (n_features,) or shape \ + (n_categorical_features,), dtype={bool, int, str}, default=None + Indicates the categorical features. + + - `None`: no feature will be considered categorical; + - boolean array-like: boolean mask of shape `(n_features,)` + indicating which features are categorical. Thus, this array has + the same shape has `X.shape[1]`; + - integer or string array-like: integer indices or strings + indicating categorical features. + + .. versionadded:: 1.2 + + feature_names : array-like of shape (n_features,), dtype=str, default=None + Name of each feature; `feature_names[i]` holds the name of the feature + with index `i`. + By default, the name of the feature corresponds to their numerical + index for NumPy array and their column name for pandas dataframe. + + .. versionadded:: 1.2 + + response_method : {'auto', 'predict_proba', 'decision_function'}, \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. For regressors + this parameter is ignored and the response is always the output of + :term:`predict`. By default, :term:`predict_proba` is tried first + and we revert to :term:`decision_function` if it doesn't exist. If + ``method`` is 'recursion', the response is always the output of + :term:`decision_function`. + + percentiles : tuple of float, default=(0.05, 0.95) + The lower and upper percentile used to create the extreme values + for the grid. Must be in [0, 1]. + This parameter is overridden by `custom_values` if that parameter is set. + + grid_resolution : int, default=100 + The number of equally spaced points on the grid, for each target + feature. + This parameter is overridden by `custom_values` if that parameter is set. + + custom_values : dict + A dictionary mapping the index of an element of `features` to an array + of values where the partial dependence should be calculated + for that feature. Setting a range of values for a feature overrides + `grid_resolution` and `percentiles`. + + See :ref:`how to use partial_dependence + ` for an example of how this parameter can + be used. + + .. versionadded:: 1.7 + + method : {'auto', 'recursion', 'brute'}, default='auto' + The method used to calculate the averaged predictions: + + - `'recursion'` is only supported for some tree-based estimators + (namely + :class:`~sklearn.ensemble.GradientBoostingClassifier`, + :class:`~sklearn.ensemble.GradientBoostingRegressor`, + :class:`~sklearn.ensemble.HistGradientBoostingClassifier`, + :class:`~sklearn.ensemble.HistGradientBoostingRegressor`, + :class:`~sklearn.tree.DecisionTreeRegressor`, + :class:`~sklearn.ensemble.RandomForestRegressor`, + ) when `kind='average'`. + This is more efficient in terms of speed. + With this method, the target response of a + classifier is always the decision function, not the predicted + probabilities. Since the `'recursion'` method implicitly computes + the average of the Individual Conditional Expectation (ICE) by + design, it is not compatible with ICE and thus `kind` must be + `'average'`. + + - `'brute'` is supported for any estimator, but is more + computationally intensive. + + - `'auto'`: the `'recursion'` is used for estimators that support it, + and `'brute'` is used otherwise. If `sample_weight` is not `None`, + then `'brute'` is used regardless of the estimator. + + Please see :ref:`this note ` for + differences between the `'brute'` and `'recursion'` method. + + kind : {'average', 'individual', 'both'}, default='average' + Whether to return the partial dependence averaged across all the + samples in the dataset or one value per sample or both. + See Returns below. + + Note that the fast `method='recursion'` option is only available for + `kind='average'` and `sample_weights=None`. Computing individual + dependencies and doing weighted averages requires using the slower + `method='brute'`. + + .. versionadded:: 0.24 + + Returns + ------- + predictions : :class:`~sklearn.utils.Bunch` + Dictionary-like object, with the following attributes. + + individual : ndarray of shape (n_outputs, n_instances, \ + len(values[0]), len(values[1]), ...) + The predictions for all the points in the grid for all + samples in X. This is also known as Individual + Conditional Expectation (ICE). + Only available when `kind='individual'` or `kind='both'`. + + average : ndarray of shape (n_outputs, len(values[0]), \ + len(values[1]), ...) + The predictions for all the points in the grid, averaged + over all samples in X (or over the training data if + `method` is 'recursion'). + Only available when `kind='average'` or `kind='both'`. + + grid_values : seq of 1d ndarrays + The values with which the grid has been created. The generated + grid is a cartesian product of the arrays in `grid_values` where + `len(grid_values) == len(features)`. The size of each array + `grid_values[j]` is either `grid_resolution`, or the number of + unique values in `X[:, j]`, whichever is smaller. + + .. versionadded:: 1.3 + + `n_outputs` corresponds to the number of classes in a multi-class + setting, or to the number of tasks for multi-output regression. + For classical regression and binary classification `n_outputs==1`. + `n_values_feature_j` corresponds to the size `grid_values[j]`. + + See Also + -------- + PartialDependenceDisplay.from_estimator : Plot Partial Dependence. + PartialDependenceDisplay : Partial Dependence visualization. + + Examples + -------- + >>> X = [[0, 0, 2], [1, 0, 0]] + >>> y = [0, 1] + >>> from sklearn.ensemble import GradientBoostingClassifier + >>> gb = GradientBoostingClassifier(random_state=0).fit(X, y) + >>> partial_dependence(gb, features=[0], X=X, percentiles=(0, 1), + ... grid_resolution=2) # doctest: +SKIP + (array([[-4.52, 4.52]]), [array([ 0., 1.])]) + """ + check_is_fitted(estimator) + + if not (is_classifier(estimator) or is_regressor(estimator)): + raise ValueError("'estimator' must be a fitted regressor or classifier.") + + if is_classifier(estimator) and isinstance(estimator.classes_[0], np.ndarray): + raise ValueError("Multiclass-multioutput estimators are not supported") + + # Use check_array only on lists and other non-array-likes / sparse. Do not + # convert DataFrame into a NumPy array. + if not (hasattr(X, "__array__") or sparse.issparse(X)): + X = check_array(X, ensure_all_finite="allow-nan", dtype=object) + + if is_regressor(estimator) and response_method != "auto": + raise ValueError( + "The response_method parameter is ignored for regressors and " + "must be 'auto'." + ) + + if kind != "average": + if method == "recursion": + raise ValueError( + "The 'recursion' method only applies when 'kind' is set to 'average'" + ) + method = "brute" + + if method == "recursion" and sample_weight is not None: + raise ValueError( + "The 'recursion' method can only be applied when sample_weight is None." + ) + + if method == "auto": + if sample_weight is not None: + method = "brute" + elif isinstance(estimator, BaseGradientBoosting) and estimator.init is None: + method = "recursion" + elif isinstance( + estimator, + (BaseHistGradientBoosting, DecisionTreeRegressor, RandomForestRegressor), + ): + method = "recursion" + else: + method = "brute" + + if method == "recursion": + if not isinstance( + estimator, + ( + BaseGradientBoosting, + BaseHistGradientBoosting, + DecisionTreeRegressor, + RandomForestRegressor, + ), + ): + supported_classes_recursion = ( + "GradientBoostingClassifier", + "GradientBoostingRegressor", + "HistGradientBoostingClassifier", + "HistGradientBoostingRegressor", + "HistGradientBoostingRegressor", + "DecisionTreeRegressor", + "RandomForestRegressor", + ) + raise ValueError( + "Only the following estimators support the 'recursion' " + "method: {}. Try using method='brute'.".format( + ", ".join(supported_classes_recursion) + ) + ) + if response_method == "auto": + response_method = "decision_function" + + if response_method != "decision_function": + raise ValueError( + "With the 'recursion' method, the response_method must be " + "'decision_function'. Got {}.".format(response_method) + ) + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + + if _determine_key_type(features, accept_slice=False) == "int": + # _get_column_indices() supports negative indexing. Here, we limit + # the indexing to be positive. The upper bound will be checked + # by _get_column_indices() + if np.any(np.less(features, 0)): + raise ValueError("all features must be in [0, {}]".format(X.shape[1] - 1)) + + features_indices = np.asarray( + _get_column_indices(X, features), dtype=np.intp, order="C" + ).ravel() + + feature_names = _check_feature_names(X, feature_names) + + n_features = X.shape[1] + if categorical_features is None: + is_categorical = [False] * len(features_indices) + else: + categorical_features = np.asarray(categorical_features) + if categorical_features.size == 0: + raise ValueError( + "Passing an empty list (`[]`) to `categorical_features` is not " + "supported. Use `None` instead to indicate that there are no " + "categorical features." + ) + if categorical_features.dtype.kind == "b": + # categorical features provided as a list of boolean + if categorical_features.size != n_features: + raise ValueError( + "When `categorical_features` is a boolean array-like, " + "the array should be of shape (n_features,). Got " + f"{categorical_features.size} elements while `X` contains " + f"{n_features} features." + ) + is_categorical = [categorical_features[idx] for idx in features_indices] + elif categorical_features.dtype.kind in ("i", "O", "U"): + # categorical features provided as a list of indices or feature names + categorical_features_idx = [ + _get_feature_index(cat, feature_names=feature_names) + for cat in categorical_features + ] + is_categorical = [ + idx in categorical_features_idx for idx in features_indices + ] + else: + raise ValueError( + "Expected `categorical_features` to be an array-like of boolean," + f" integer, or string. Got {categorical_features.dtype} instead." + ) + + custom_values = custom_values or {} + if isinstance(features, (str, int)): + features = [features] + + for feature_idx, feature, is_cat in zip(features_indices, features, is_categorical): + if is_cat: + continue + + if _safe_indexing(X, feature_idx, axis=1).dtype.kind in "iu": + # TODO(1.9): raise a ValueError instead. + warnings.warn( + f"The column {feature!r} contains integer data. Partial " + "dependence plots are not supported for integer data: this " + "can lead to implicit rounding with NumPy arrays or even errors " + "with newer pandas versions. Please convert numerical features" + "to floating point dtypes ahead of time to avoid problems. " + "This will raise ValueError in scikit-learn 1.9.", + FutureWarning, + ) + # Do not warn again for other features to avoid spamming the caller. + break + + X_subset = _safe_indexing(X, features_indices, axis=1) + + custom_values_for_X_subset = { + index: custom_values.get(feature) + for index, feature in enumerate(features) + if feature in custom_values + } + + grid, values = _grid_from_X( + X_subset, + percentiles, + is_categorical, + grid_resolution, + custom_values_for_X_subset, + ) + + if method == "brute": + averaged_predictions, predictions = _partial_dependence_brute( + estimator, grid, features_indices, X, response_method, sample_weight + ) + + # reshape predictions to + # (n_outputs, n_instances, n_values_feature_0, n_values_feature_1, ...) + predictions = predictions.reshape( + -1, X.shape[0], *[val.shape[0] for val in values] + ) + else: + averaged_predictions = _partial_dependence_recursion( + estimator, grid, features_indices + ) + + # reshape averaged_predictions to + # (n_outputs, n_values_feature_0, n_values_feature_1, ...) + averaged_predictions = averaged_predictions.reshape( + -1, *[val.shape[0] for val in values] + ) + pdp_results = Bunch(grid_values=values) + + if kind == "average": + pdp_results["average"] = averaged_predictions + elif kind == "individual": + pdp_results["individual"] = predictions + else: # kind='both' + pdp_results["average"] = averaged_predictions + pdp_results["individual"] = predictions + + return pdp_results diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_pd_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_pd_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a48ba4d9a4490df59b8503f0b8768c7a986537a9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_pd_utils.py @@ -0,0 +1,68 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + + +def _check_feature_names(X, feature_names=None): + """Check feature names. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data. + + feature_names : None or array-like of shape (n_names,), dtype=str + Feature names to check or `None`. + + Returns + ------- + feature_names : list of str + Feature names validated. If `feature_names` is `None`, then a list of + feature names is provided, i.e. the column names of a pandas dataframe + or a generic list of feature names (e.g. `["x0", "x1", ...]`) for a + NumPy array. + """ + if feature_names is None: + if hasattr(X, "columns") and hasattr(X.columns, "tolist"): + # get the column names for a pandas dataframe + feature_names = X.columns.tolist() + else: + # define a list of numbered indices for a numpy array + feature_names = [f"x{i}" for i in range(X.shape[1])] + elif hasattr(feature_names, "tolist"): + # convert numpy array or pandas index to a list + feature_names = feature_names.tolist() + if len(set(feature_names)) != len(feature_names): + raise ValueError("feature_names should not contain duplicates.") + + return feature_names + + +def _get_feature_index(fx, feature_names=None): + """Get feature index. + + Parameters + ---------- + fx : int or str + Feature index or name. + + feature_names : list of str, default=None + All feature names from which to search the indices. + + Returns + ------- + idx : int + Feature index. + """ + if isinstance(fx, str): + if feature_names is None: + raise ValueError( + f"Cannot plot partial dependence for feature {fx!r} since " + "the list of feature names was not provided, neither as " + "column names of a pandas data-frame nor via the feature_names " + "parameter." + ) + try: + return feature_names.index(fx) + except ValueError as e: + raise ValueError(f"Feature {fx!r} not in feature_names") from e + return fx diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_permutation_importance.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_permutation_importance.py new file mode 100644 index 0000000000000000000000000000000000000000..451062fbe272e066350b8b5307d23f9180ed6760 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_permutation_importance.py @@ -0,0 +1,313 @@ +"""Permutation importance for estimators.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers + +import numpy as np + +from ..ensemble._bagging import _generate_indices +from ..metrics import check_scoring, get_scorer_names +from ..model_selection._validation import _aggregate_score_dicts +from ..utils import Bunch, _safe_indexing, check_array, check_random_state +from ..utils._param_validation import ( + HasMethods, + Integral, + Interval, + RealNotInt, + StrOptions, + validate_params, +) +from ..utils.parallel import Parallel, delayed + + +def _weights_scorer(scorer, estimator, X, y, sample_weight): + if sample_weight is not None: + return scorer(estimator, X, y, sample_weight=sample_weight) + return scorer(estimator, X, y) + + +def _calculate_permutation_scores( + 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) + + # Work on a copy of X to ensure thread-safety in case of threading based + # parallelism. Furthermore, making a copy is also useful when the joblib + # backend is 'loky' (default) or the old 'multiprocessing': in those cases, + # 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. + 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) + if sample_weight is not None: + sample_weight = _safe_indexing(sample_weight, row_indices, axis=0) + else: + X_permuted = X.copy() + + scores = [] + shuffling_idx = np.arange(X_permuted.shape[0]) + for _ in range(n_repeats): + random_state.shuffle(shuffling_idx) + if hasattr(X_permuted, "iloc"): + col = X_permuted.iloc[shuffling_idx, col_idx] + col.index = X_permuted.index + X_permuted[X_permuted.columns[col_idx]] = col + else: + X_permuted[:, col_idx] = X_permuted[shuffling_idx, col_idx] + scores.append(_weights_scorer(scorer, estimator, X_permuted, y, sample_weight)) + + if isinstance(scores[0], dict): + scores = _aggregate_score_dicts(scores) + else: + scores = np.array(scores) + + return scores + + +def _create_importances_bunch(baseline_score, permuted_score): + """Compute the importances as the decrease in score. + + Parameters + ---------- + baseline_score : ndarray of shape (n_features,) + The baseline score without permutation. + permuted_score : ndarray of shape (n_features, n_repeats) + The permuted scores for the `n` repetitions. + + Returns + ------- + importances : :class:`~sklearn.utils.Bunch` + Dictionary-like object, with the following attributes. + importances_mean : ndarray, shape (n_features, ) + Mean of feature importance over `n_repeats`. + importances_std : ndarray, shape (n_features, ) + Standard deviation over `n_repeats`. + importances : ndarray, shape (n_features, n_repeats) + Raw permutation importance scores. + """ + importances = baseline_score - permuted_score + return Bunch( + importances_mean=np.mean(importances, axis=1), + importances_std=np.std(importances, axis=1), + importances=importances, + ) + + +@validate_params( + { + "estimator": [HasMethods(["fit"])], + "X": ["array-like"], + "y": ["array-like", None], + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + list, + tuple, + dict, + None, + ], + "n_repeats": [Interval(Integral, 1, None, closed="left")], + "n_jobs": [Integral, None], + "random_state": ["random_state"], + "sample_weight": ["array-like", None], + "max_samples": [ + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="right"), + ], + }, + prefer_skip_nested_validation=True, +) +def permutation_importance( + estimator, + X, + y, + *, + scoring=None, + n_repeats=5, + n_jobs=None, + random_state=None, + sample_weight=None, + max_samples=1.0, +): + """Permutation importance for feature evaluation [BRE]_. + + The :term:`estimator` is required to be a fitted estimator. `X` can be the + data set used to train the estimator or a hold-out set. The permutation + importance of a feature is calculated as follows. First, a baseline metric, + defined by :term:`scoring`, is evaluated on a (potentially different) + dataset defined by the `X`. Next, a feature column from the validation set + is permuted and the metric is evaluated again. The permutation importance + is defined to be the difference between the baseline metric and metric from + permutating the feature column. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object + An estimator that has already been :term:`fitted` and is compatible + with :term:`scorer`. + + X : ndarray or DataFrame, shape (n_samples, n_features) + Data on which permutation importance will be computed. + + y : array-like or None, shape (n_samples, ) or (n_samples, n_classes) + Targets for supervised or `None` for unsupervised. + + scoring : str, callable, list, tuple, or dict, default=None + Scorer to use. + If `scoring` represents a single score, one can use: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + If `scoring` represents multiple scores, one can use: + + - a list or tuple of unique strings; + - a callable returning a dictionary where the keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables a values. + + Passing multiple scores to `scoring` is more efficient than calling + `permutation_importance` for each of the scores as it reuses + predictions to avoid redundant computation. + + n_repeats : int, default=5 + Number of times to permute a feature. + + n_jobs : int or None, default=None + Number of jobs to run in parallel. The computation is done by computing + permutation score for each columns and parallelized over the columns. + `None` means 1 unless in a :obj:`joblib.parallel_backend` context. + `-1` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + Pseudo-random number generator to control the permutations of each + feature. + Pass an int to get reproducible results across function calls. + See :term:`Glossary `. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights used in scoring. + + .. 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 + Dictionary-like object, with the following attributes. + + importances_mean : ndarray of shape (n_features, ) + Mean of feature importance over `n_repeats`. + importances_std : ndarray of shape (n_features, ) + Standard deviation over `n_repeats`. + importances : ndarray of shape (n_features, n_repeats) + Raw permutation importance scores. + + If there are multiple scoring metrics in the scoring parameter + `result` is a dict with scorer names as keys (e.g. 'roc_auc') and + `Bunch` objects like above as values. + + References + ---------- + .. [BRE] :doi:`L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, + 2001. <10.1023/A:1010933404324>` + + Examples + -------- + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.inspection import permutation_importance + >>> X = [[1, 9, 9],[1, 9, 9],[1, 9, 9], + ... [0, 9, 9],[0, 9, 9],[0, 9, 9]] + >>> y = [1, 1, 1, 0, 0, 0] + >>> clf = LogisticRegression().fit(X, y) + >>> result = permutation_importance(clf, X, y, n_repeats=10, + ... random_state=0) + >>> result.importances_mean + array([0.4666, 0. , 0. ]) + >>> result.importances_std + array([0.2211, 0. , 0. ]) + """ + if not hasattr(X, "iloc"): + X = check_array(X, ensure_all_finite="allow-nan", dtype=None) + + # Precompute random seed from the random state to be used + # to get a fresh independent RandomState instance for each + # parallel call to _calculate_permutation_scores, irrespective of + # the fact that variables are shared or not depending on the active + # joblib backend (sequential, thread-based or process-based). + 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 max_samples > X.shape[0]: + raise ValueError("max_samples must be <= n_samples") + + scorer = check_scoring(estimator, scoring=scoring) + baseline_score = _weights_scorer(scorer, estimator, X, y, sample_weight) + + scores = Parallel(n_jobs=n_jobs)( + delayed(_calculate_permutation_scores)( + estimator, + X, + y, + sample_weight, + col_idx, + random_seed, + n_repeats, + scorer, + max_samples, + ) + for col_idx in range(X.shape[1]) + ) + + if isinstance(baseline_score, dict): + return { + name: _create_importances_bunch( + baseline_score[name], + # unpack the permuted scores + np.array([scores[col_idx][name] for col_idx in range(X.shape[1])]), + ) + for name in baseline_score + } + else: + return _create_importances_bunch(baseline_score, np.array(scores)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd18fb94b593f0a3125c1f5833f3b9597614ba --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/__init__.py @@ -0,0 +1,2 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/decision_boundary.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/decision_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..2ef85380583937f564891e8705b7ac91eff0f321 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/decision_boundary.py @@ -0,0 +1,564 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np + +from ...base import is_regressor +from ...preprocessing import LabelEncoder +from ...utils import _safe_indexing +from ...utils._optional_dependencies import check_matplotlib_support +from ...utils._response import _get_response_values +from ...utils._set_output import _get_adapter_from_container +from ...utils.validation import ( + _is_arraylike_not_scalar, + _is_pandas_df, + _is_polars_df, + _num_features, + check_is_fitted, +) + + +def _check_boundary_response_method(estimator, response_method, class_of_interest): + """Validate the response methods to be used with the fitted estimator. + + Parameters + ---------- + estimator : object + Fitted estimator to check. + + response_method : {'auto', 'decision_function', 'predict_proba', 'predict'} + Specifies whether to use :term:`decision_function`, :term:`predict_proba`, + :term:`predict` as the target response. If set to 'auto', the response method is + tried in the before mentioned order. + + class_of_interest : int, float, bool, str or None + The class considered when plotting the decision. Cannot be None if + multiclass and `response_method` is 'predict_proba' or 'decision_function'. + + .. versionadded:: 1.4 + + Returns + ------- + prediction_method : list of str or str + The name or list of names of the response methods to use. + """ + has_classes = hasattr(estimator, "classes_") + if has_classes and _is_arraylike_not_scalar(estimator.classes_[0]): + msg = "Multi-label and multi-output multi-class classifiers are not supported" + raise ValueError(msg) + + if response_method == "auto": + if is_regressor(estimator): + prediction_method = "predict" + else: + prediction_method = ["decision_function", "predict_proba", "predict"] + else: + prediction_method = response_method + + return prediction_method + + +class DecisionBoundaryDisplay: + """Decisions boundary visualization. + + It is recommended to use + :func:`~sklearn.inspection.DecisionBoundaryDisplay.from_estimator` + to create a :class:`DecisionBoundaryDisplay`. All parameters are stored as + attributes. + + Read more in the :ref:`User Guide `. + + For a detailed example comparing the decision boundaries of multinomial and + one-vs-rest logistic regression, please see + :ref:`sphx_glr_auto_examples_linear_model_plot_logistic_multinomial.py`. + + .. versionadded:: 1.1 + + Parameters + ---------- + xx0 : ndarray of shape (grid_resolution, grid_resolution) + First output of :func:`meshgrid `. + + xx1 : ndarray of shape (grid_resolution, grid_resolution) + Second output of :func:`meshgrid `. + + response : ndarray of shape (grid_resolution, grid_resolution) or \ + (grid_resolution, grid_resolution, n_classes) + Values of the response function. + + multiclass_colors : list of str or str, default=None + Specifies how to color each class when plotting all classes of multiclass + problem. Ignored for binary problems and multiclass problems when plotting a + single prediction value per point. + Possible inputs are: + + * list: list of Matplotlib + `color `_ + strings, of length `n_classes` + * str: name of :class:`matplotlib.colors.Colormap` + * None: 'viridis' colormap is used to sample colors + + Single color colormaps will be generated from the colors in the list or + colors taken from the colormap and passed to the `cmap` parameter of + the `plot_method`. + + .. versionadded:: 1.7 + + xlabel : str, default=None + Default label to place on x axis. + + ylabel : str, default=None + Default label to place on y axis. + + Attributes + ---------- + surface_ : matplotlib `QuadContourSet` or `QuadMesh` or list of such objects + If `plot_method` is 'contour' or 'contourf', `surface_` is + :class:`QuadContourSet `. If + `plot_method` is 'pcolormesh', `surface_` is + :class:`QuadMesh `. + + multiclass_colors_ : array of shape (n_classes, 4) + Colors used to plot each class in multiclass problems. + Only defined when `color_of_interest` is None. + + .. versionadded:: 1.7 + + ax_ : matplotlib Axes + Axes with decision boundary. + + figure_ : matplotlib Figure + Figure containing the decision boundary. + + See Also + -------- + DecisionBoundaryDisplay.from_estimator : Plot decision boundary given an estimator. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from sklearn.datasets import load_iris + >>> from sklearn.inspection import DecisionBoundaryDisplay + >>> from sklearn.tree import DecisionTreeClassifier + >>> iris = load_iris() + >>> feature_1, feature_2 = np.meshgrid( + ... np.linspace(iris.data[:, 0].min(), iris.data[:, 0].max()), + ... np.linspace(iris.data[:, 1].min(), iris.data[:, 1].max()) + ... ) + >>> grid = np.vstack([feature_1.ravel(), feature_2.ravel()]).T + >>> tree = DecisionTreeClassifier().fit(iris.data[:, :2], iris.target) + >>> y_pred = np.reshape(tree.predict(grid), feature_1.shape) + >>> display = DecisionBoundaryDisplay( + ... xx0=feature_1, xx1=feature_2, response=y_pred + ... ) + >>> display.plot() + <...> + >>> display.ax_.scatter( + ... iris.data[:, 0], iris.data[:, 1], c=iris.target, edgecolor="black" + ... ) + <...> + >>> plt.show() + """ + + def __init__( + self, *, xx0, xx1, response, multiclass_colors=None, xlabel=None, ylabel=None + ): + self.xx0 = xx0 + self.xx1 = xx1 + self.response = response + self.multiclass_colors = multiclass_colors + self.xlabel = xlabel + self.ylabel = ylabel + + def plot(self, plot_method="contourf", ax=None, xlabel=None, ylabel=None, **kwargs): + """Plot visualization. + + Parameters + ---------- + plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf' + Plotting method to call when plotting the response. Please refer + to the following matplotlib documentation for details: + :func:`contourf `, + :func:`contour `, + :func:`pcolormesh `. + + ax : Matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + xlabel : str, default=None + Overwrite the x-axis label. + + ylabel : str, default=None + Overwrite the y-axis label. + + **kwargs : dict + Additional keyword arguments to be passed to the `plot_method`. + + Returns + ------- + display: :class:`~sklearn.inspection.DecisionBoundaryDisplay` + Object that stores computed values. + """ + check_matplotlib_support("DecisionBoundaryDisplay.plot") + import matplotlib as mpl + import matplotlib.pyplot as plt + + if plot_method not in ("contourf", "contour", "pcolormesh"): + raise ValueError( + "plot_method must be 'contourf', 'contour', or 'pcolormesh'. " + f"Got {plot_method} instead." + ) + + if ax is None: + _, ax = plt.subplots() + + plot_func = getattr(ax, plot_method) + if self.response.ndim == 2: + self.surface_ = plot_func(self.xx0, self.xx1, self.response, **kwargs) + else: # self.response.ndim == 3 + n_responses = self.response.shape[-1] + for kwarg in ("cmap", "colors"): + if kwarg in kwargs: + warnings.warn( + f"'{kwarg}' is ignored in favor of 'multiclass_colors' " + "in the multiclass case when the response method is " + "'decision_function' or 'predict_proba'." + ) + del kwargs[kwarg] + + if self.multiclass_colors is None or isinstance( + self.multiclass_colors, str + ): + if self.multiclass_colors is None: + cmap = "tab10" if n_responses <= 10 else "gist_rainbow" + else: + cmap = self.multiclass_colors + + # Special case for the tab10 and tab20 colormaps that encode a + # discrete set of colors that are easily distinguishable + # contrary to other colormaps that are continuous. + if cmap == "tab10" and n_responses <= 10: + colors = plt.get_cmap("tab10", 10).colors[:n_responses] + elif cmap == "tab20" and n_responses <= 20: + colors = plt.get_cmap("tab20", 20).colors[:n_responses] + else: + cmap = plt.get_cmap(cmap, n_responses) + if not hasattr(cmap, "colors"): + # For LinearSegmentedColormap + colors = cmap(np.linspace(0, 1, n_responses)) + else: + colors = cmap.colors + elif isinstance(self.multiclass_colors, list): + colors = [mpl.colors.to_rgba(color) for color in self.multiclass_colors] + else: + raise ValueError("'multiclass_colors' must be a list or a str.") + + self.multiclass_colors_ = colors + if plot_method == "contour": + # Plot only argmax map for contour + class_map = self.response.argmax(axis=2) + self.surface_ = plot_func( + self.xx0, self.xx1, class_map, colors=colors, **kwargs + ) + else: + multiclass_cmaps = [ + mpl.colors.LinearSegmentedColormap.from_list( + f"colormap_{class_idx}", [(1.0, 1.0, 1.0, 1.0), (r, g, b, 1.0)] + ) + for class_idx, (r, g, b, _) in enumerate(colors) + ] + + self.surface_ = [] + for class_idx, cmap in enumerate(multiclass_cmaps): + response = np.ma.array( + self.response[:, :, class_idx], + mask=~(self.response.argmax(axis=2) == class_idx), + ) + self.surface_.append( + plot_func(self.xx0, self.xx1, response, cmap=cmap, **kwargs) + ) + + if xlabel is not None or not ax.get_xlabel(): + xlabel = self.xlabel if xlabel is None else xlabel + ax.set_xlabel(xlabel) + if ylabel is not None or not ax.get_ylabel(): + ylabel = self.ylabel if ylabel is None else ylabel + ax.set_ylabel(ylabel) + + self.ax_ = ax + self.figure_ = ax.figure + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + *, + grid_resolution=100, + eps=1.0, + plot_method="contourf", + response_method="auto", + class_of_interest=None, + multiclass_colors=None, + xlabel=None, + ylabel=None, + ax=None, + **kwargs, + ): + """Plot decision boundary given an estimator. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object + Trained estimator used to plot the decision boundary. + + X : {array-like, sparse matrix, dataframe} of shape (n_samples, 2) + Input data that should be only 2-dimensional. + + grid_resolution : int, default=100 + Number of grid points to use for plotting decision boundary. + Higher values will make the plot look nicer but be slower to + render. + + eps : float, default=1.0 + Extends the minimum and maximum values of X for evaluating the + response function. + + plot_method : {'contourf', 'contour', 'pcolormesh'}, default='contourf' + Plotting method to call when plotting the response. Please refer + to the following matplotlib documentation for details: + :func:`contourf `, + :func:`contour `, + :func:`pcolormesh `. + + response_method : {'auto', 'decision_function', 'predict_proba', \ + 'predict'}, default='auto' + Specifies whether to use :term:`decision_function`, + :term:`predict_proba` or :term:`predict` as the target response. + If set to 'auto', the response method is tried in the order as + listed above. + + .. versionchanged:: 1.6 + For multiclass problems, 'auto' no longer defaults to 'predict'. + + class_of_interest : int, float, bool or str, default=None + The class to be plotted when `response_method` is 'predict_proba' + or 'decision_function'. If None, `estimator.classes_[1]` is considered + the positive class for binary classifiers. For multiclass + classifiers, if None, all classes will be represented in the + decision boundary plot; the class with the highest response value + at each point is plotted. The color of each class can be set via + `multiclass_colors`. + + .. versionadded:: 1.4 + + multiclass_colors : list of str, or str, default=None + Specifies how to color each class when plotting multiclass + 'predict_proba' or 'decision_function' and `class_of_interest` is + None. Ignored in all other cases. + + Possible inputs are: + + * list: list of Matplotlib + `color `_ + strings, of length `n_classes` + * str: name of :class:`matplotlib.colors.Colormap` + * None: 'tab10' colormap is used to sample colors if the number of + classes is less than or equal to 10, otherwise 'gist_rainbow' + colormap. + + Single color colormaps will be generated from the colors in the list or + colors taken from the colormap, and passed to the `cmap` parameter of + the `plot_method`. + + .. versionadded:: 1.7 + + xlabel : str, default=None + The label used for the x-axis. If `None`, an attempt is made to + extract a label from `X` if it is a dataframe, otherwise an empty + string is used. + + ylabel : str, default=None + The label used for the y-axis. If `None`, an attempt is made to + extract a label from `X` if it is a dataframe, otherwise an empty + string is used. + + ax : Matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keyword arguments to be passed to the + `plot_method`. + + Returns + ------- + display : :class:`~sklearn.inspection.DecisionBoundaryDisplay` + Object that stores the result. + + See Also + -------- + DecisionBoundaryDisplay : Decision boundary visualization. + sklearn.metrics.ConfusionMatrixDisplay.from_estimator : Plot the + confusion matrix given an estimator, the data, and the label. + sklearn.metrics.ConfusionMatrixDisplay.from_predictions : Plot the + confusion matrix given the true and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_iris + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.inspection import DecisionBoundaryDisplay + >>> iris = load_iris() + >>> X = iris.data[:, :2] + >>> classifier = LogisticRegression().fit(X, iris.target) + >>> disp = DecisionBoundaryDisplay.from_estimator( + ... classifier, X, response_method="predict", + ... xlabel=iris.feature_names[0], ylabel=iris.feature_names[1], + ... alpha=0.5, + ... ) + >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor="k") + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + check_is_fitted(estimator) + import matplotlib as mpl + + if not grid_resolution > 1: + raise ValueError( + "grid_resolution must be greater than 1. Got" + f" {grid_resolution} instead." + ) + + if not eps >= 0: + raise ValueError( + f"eps must be greater than or equal to 0. Got {eps} instead." + ) + + possible_plot_methods = ("contourf", "contour", "pcolormesh") + if plot_method not in possible_plot_methods: + available_methods = ", ".join(possible_plot_methods) + raise ValueError( + f"plot_method must be one of {available_methods}. " + f"Got {plot_method} instead." + ) + + num_features = _num_features(X) + if num_features != 2: + raise ValueError( + f"n_features must be equal to 2. Got {num_features} instead." + ) + + if ( + response_method in ("predict_proba", "decision_function", "auto") + and multiclass_colors is not None + and hasattr(estimator, "classes_") + and (n_classes := len(estimator.classes_)) > 2 + ): + if isinstance(multiclass_colors, list): + if len(multiclass_colors) != n_classes: + raise ValueError( + "When 'multiclass_colors' is a list, it must be of the same " + f"length as 'estimator.classes_' ({n_classes}), got: " + f"{len(multiclass_colors)}." + ) + elif any( + not mpl.colors.is_color_like(col) for col in multiclass_colors + ): + raise ValueError( + "When 'multiclass_colors' is a list, it can only contain valid" + f" Matplotlib color names. Got: {multiclass_colors}" + ) + if isinstance(multiclass_colors, str): + if multiclass_colors not in mpl.pyplot.colormaps(): + raise ValueError( + "When 'multiclass_colors' is a string, it must be a valid " + f"Matplotlib colormap. Got: {multiclass_colors}" + ) + + x0, x1 = _safe_indexing(X, 0, axis=1), _safe_indexing(X, 1, axis=1) + + x0_min, x0_max = x0.min() - eps, x0.max() + eps + x1_min, x1_max = x1.min() - eps, x1.max() + eps + + xx0, xx1 = np.meshgrid( + np.linspace(x0_min, x0_max, grid_resolution), + np.linspace(x1_min, x1_max, grid_resolution), + ) + + X_grid = np.c_[xx0.ravel(), xx1.ravel()] + if _is_pandas_df(X) or _is_polars_df(X): + adapter = _get_adapter_from_container(X) + X_grid = adapter.create_container( + X_grid, + X_grid, + columns=X.columns, + ) + + prediction_method = _check_boundary_response_method( + estimator, response_method, class_of_interest + ) + try: + response, _, response_method_used = _get_response_values( + estimator, + X_grid, + response_method=prediction_method, + pos_label=class_of_interest, + return_response_method_used=True, + ) + except ValueError as exc: + if "is not a valid label" in str(exc): + # re-raise a more informative error message since `pos_label` is unknown + # to our user when interacting with + # `DecisionBoundaryDisplay.from_estimator` + raise ValueError( + f"class_of_interest={class_of_interest} is not a valid label: It " + f"should be one of {estimator.classes_}" + ) from exc + raise + + # convert classes predictions into integers + if response_method_used == "predict" and hasattr(estimator, "classes_"): + encoder = LabelEncoder() + encoder.classes_ = estimator.classes_ + response = encoder.transform(response) + + if response.ndim == 1: + response = response.reshape(*xx0.shape) + else: + if is_regressor(estimator): + raise ValueError("Multi-output regressors are not supported") + + if class_of_interest is not None: + # For the multiclass case, `_get_response_values` returns the response + # as-is. Thus, we have a column per class and we need to select the + # column corresponding to the positive class. + col_idx = np.flatnonzero(estimator.classes_ == class_of_interest)[0] + response = response[:, col_idx].reshape(*xx0.shape) + else: + response = response.reshape(*xx0.shape, response.shape[-1]) + + if xlabel is None: + xlabel = X.columns[0] if hasattr(X, "columns") else "" + + if ylabel is None: + ylabel = X.columns[1] if hasattr(X, "columns") else "" + + display = cls( + xx0=xx0, + xx1=xx1, + response=response, + multiclass_colors=multiclass_colors, + xlabel=xlabel, + ylabel=ylabel, + ) + return display.plot(ax=ax, plot_method=plot_method, **kwargs) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/partial_dependence.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/partial_dependence.py new file mode 100644 index 0000000000000000000000000000000000000000..b31a5070b236b811195f97b6643be7b4c191343e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/partial_dependence.py @@ -0,0 +1,1495 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +from itertools import chain +from math import ceil + +import numpy as np +from scipy import sparse +from scipy.stats.mstats import mquantiles + +from ...base import is_regressor +from ...utils import ( + Bunch, + _safe_indexing, + check_array, + check_random_state, +) +from ...utils._encode import _unique +from ...utils._optional_dependencies import check_matplotlib_support +from ...utils._plotting import _validate_style_kwargs +from ...utils.parallel import Parallel, delayed +from .. import partial_dependence +from .._pd_utils import _check_feature_names, _get_feature_index + + +class PartialDependenceDisplay: + """Partial Dependence Plot (PDP) and Individual Conditional Expectation (ICE). + + It is recommended to use + :func:`~sklearn.inspection.PartialDependenceDisplay.from_estimator` to create a + :class:`~sklearn.inspection.PartialDependenceDisplay`. All parameters are stored + as attributes. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Inspection Guide `. + + For an example on how to use this class, see the following example: + :ref:`sphx_glr_auto_examples_miscellaneous_plot_partial_dependence_visualization_api.py`. + + .. versionadded:: 0.22 + + Parameters + ---------- + pd_results : list of Bunch + Results of :func:`~sklearn.inspection.partial_dependence` for + ``features``. + + features : list of (int,) or list of (int, int) + Indices of features for a given plot. A tuple of one integer will plot + a partial dependence curve of one feature. A tuple of two integers will + plot a two-way partial dependence curve as a contour plot. + + feature_names : list of str + Feature names corresponding to the indices in ``features``. + + target_idx : int + + - In a multiclass setting, specifies the class for which the PDPs + should be computed. Note that for binary classification, the + positive class (index 1) is always used. + - In a multioutput setting, specifies the task for which the PDPs + should be computed. + + Ignored in binary classification or classical regression settings. + + deciles : dict + Deciles for feature indices in ``features``. + + kind : {'average', 'individual', 'both'} or list of such str, \ + default='average' + Whether to plot the partial dependence averaged across all the samples + in the dataset or one line per sample or both. + + - ``kind='average'`` results in the traditional PD plot; + - ``kind='individual'`` results in the ICE plot; + - ``kind='both'`` results in plotting both the ICE and PD on the same + plot. + + A list of such strings can be provided to specify `kind` on a per-plot + basis. The length of the list should be the same as the number of + interaction requested in `features`. + + .. note:: + ICE ('individual' or 'both') is not a valid option for 2-ways + interactions plot. As a result, an error will be raised. + 2-ways interaction plots should always be configured to + use the 'average' kind instead. + + .. note:: + The fast ``method='recursion'`` option is only available for + `kind='average'` and `sample_weights=None`. Computing individual + dependencies and doing weighted averages requires using the slower + `method='brute'`. + + .. versionadded:: 0.24 + Add `kind` parameter with `'average'`, `'individual'`, and `'both'` + options. + + .. versionadded:: 1.1 + Add the possibility to pass a list of string specifying `kind` + for each plot. + + subsample : float, int or None, default=1000 + Sampling for ICE curves when `kind` is 'individual' or 'both'. + If float, should be between 0.0 and 1.0 and represent the proportion + of the dataset to be used to plot ICE curves. If int, represents the + maximum absolute number of samples to use. + + Note that the full dataset is still used to calculate partial + dependence when `kind='both'`. + + .. versionadded:: 0.24 + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the selected samples when subsamples is not + `None`. See :term:`Glossary ` for details. + + .. versionadded:: 0.24 + + is_categorical : list of (bool,) or list of (bool, bool), default=None + Whether each target feature in `features` is categorical or not. + The list should be same size as `features`. If `None`, all features + are assumed to be continuous. + + .. versionadded:: 1.2 + + Attributes + ---------- + bounding_ax_ : matplotlib Axes or None + If `ax` is an axes or None, the `bounding_ax_` is the axes where the + grid of partial dependence plots are drawn. If `ax` is a list of axes + or a numpy array of axes, `bounding_ax_` is None. + + axes_ : ndarray of matplotlib Axes + If `ax` is an axes or None, `axes_[i, j]` is the axes on the i-th row + and j-th column. If `ax` is a list of axes, `axes_[i]` is the i-th item + in `ax`. Elements that are None correspond to a nonexisting axes in + that position. + + lines_ : ndarray of matplotlib Artists + If `ax` is an axes or None, `lines_[i, j]` is the partial dependence + curve on the i-th row and j-th column. If `ax` is a list of axes, + `lines_[i]` is the partial dependence curve corresponding to the i-th + item in `ax`. Elements that are None correspond to a nonexisting axes + or an axes that does not include a line plot. + + deciles_vlines_ : ndarray of matplotlib LineCollection + If `ax` is an axes or None, `vlines_[i, j]` is the line collection + representing the x axis deciles of the i-th row and j-th column. If + `ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in + `ax`. Elements that are None correspond to a nonexisting axes or an + axes that does not include a PDP plot. + + .. versionadded:: 0.23 + + deciles_hlines_ : ndarray of matplotlib LineCollection + If `ax` is an axes or None, `vlines_[i, j]` is the line collection + representing the y axis deciles of the i-th row and j-th column. If + `ax` is a list of axes, `vlines_[i]` corresponds to the i-th item in + `ax`. Elements that are None correspond to a nonexisting axes or an + axes that does not include a 2-way plot. + + .. versionadded:: 0.23 + + contours_ : ndarray of matplotlib Artists + If `ax` is an axes or None, `contours_[i, j]` is the partial dependence + plot on the i-th row and j-th column. If `ax` is a list of axes, + `contours_[i]` is the partial dependence plot corresponding to the i-th + item in `ax`. Elements that are None correspond to a nonexisting axes + or an axes that does not include a contour plot. + + bars_ : ndarray of matplotlib Artists + If `ax` is an axes or None, `bars_[i, j]` is the partial dependence bar + plot on the i-th row and j-th column (for a categorical feature). + If `ax` is a list of axes, `bars_[i]` is the partial dependence bar + plot corresponding to the i-th item in `ax`. Elements that are None + correspond to a nonexisting axes or an axes that does not include a + bar plot. + + .. versionadded:: 1.2 + + heatmaps_ : ndarray of matplotlib Artists + If `ax` is an axes or None, `heatmaps_[i, j]` is the partial dependence + heatmap on the i-th row and j-th column (for a pair of categorical + features) . If `ax` is a list of axes, `heatmaps_[i]` is the partial + dependence heatmap corresponding to the i-th item in `ax`. Elements + that are None correspond to a nonexisting axes or an axes that does not + include a heatmap. + + .. versionadded:: 1.2 + + figure_ : matplotlib Figure + Figure containing partial dependence plots. + + See Also + -------- + partial_dependence : Compute Partial Dependence values. + PartialDependenceDisplay.from_estimator : Plot Partial Dependence. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> from sklearn.inspection import PartialDependenceDisplay + >>> from sklearn.inspection import partial_dependence + >>> X, y = make_friedman1() + >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y) + >>> features, feature_names = [(0,)], [f"Features #{i}" for i in range(X.shape[1])] + >>> deciles = {0: np.linspace(0, 1, num=5)} + >>> pd_results = partial_dependence( + ... clf, X, features=0, kind="average", grid_resolution=5) + >>> display = PartialDependenceDisplay( + ... [pd_results], features=features, feature_names=feature_names, + ... target_idx=0, deciles=deciles + ... ) + >>> display.plot(pdp_lim={1: (-1.38, 0.66)}) + <...> + >>> plt.show() + """ + + def __init__( + self, + pd_results, + *, + features, + feature_names, + target_idx, + deciles, + kind="average", + subsample=1000, + random_state=None, + is_categorical=None, + ): + self.pd_results = pd_results + self.features = features + self.feature_names = feature_names + self.target_idx = target_idx + self.deciles = deciles + self.kind = kind + self.subsample = subsample + self.random_state = random_state + self.is_categorical = is_categorical + + @classmethod + def from_estimator( + cls, + estimator, + X, + features, + *, + sample_weight=None, + categorical_features=None, + feature_names=None, + target=None, + response_method="auto", + n_cols=3, + grid_resolution=100, + percentiles=(0.05, 0.95), + custom_values=None, + method="auto", + n_jobs=None, + verbose=0, + line_kw=None, + ice_lines_kw=None, + pd_line_kw=None, + contour_kw=None, + ax=None, + kind="average", + centered=False, + subsample=1000, + random_state=None, + ): + """Partial dependence (PD) and individual conditional expectation (ICE) plots. + + Partial dependence plots, individual conditional expectation plots, or an + overlay of both can be plotted by setting the `kind` parameter. + This method generates one plot for each entry in `features`. The plots + are arranged in a grid with `n_cols` columns. For one-way partial + dependence plots, the deciles of the feature values are shown on the + x-axis. For two-way plots, the deciles are shown on both axes and PDPs + are contour plots. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Inspection Guide `. + + For an example on how to use this class method, see + :ref:`sphx_glr_auto_examples_inspection_plot_partial_dependence.py`. + + .. note:: + + :func:`PartialDependenceDisplay.from_estimator` does not support using the + same axes with multiple calls. To plot the partial dependence for + multiple estimators, please pass the axes created by the first call to the + second call:: + + >>> from sklearn.inspection import PartialDependenceDisplay + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.linear_model import LinearRegression + >>> from sklearn.ensemble import RandomForestRegressor + >>> X, y = make_friedman1() + >>> est1 = LinearRegression().fit(X, y) + >>> est2 = RandomForestRegressor().fit(X, y) + >>> disp1 = PartialDependenceDisplay.from_estimator(est1, X, + ... [1, 2]) + >>> disp2 = PartialDependenceDisplay.from_estimator(est2, X, [1, 2], + ... ax=disp1.axes_) + + .. warning:: + + For :class:`~sklearn.ensemble.GradientBoostingClassifier` and + :class:`~sklearn.ensemble.GradientBoostingRegressor`, the + `'recursion'` method (used by default) will not account for the `init` + predictor of the boosting process. In practice, this will produce + the same values as `'brute'` up to a constant offset in the target + response, provided that `init` is a constant estimator (which is the + default). However, if `init` is not a constant estimator, the + partial dependence values are incorrect for `'recursion'` because the + offset will be sample-dependent. It is preferable to use the `'brute'` + method. Note that this only applies to + :class:`~sklearn.ensemble.GradientBoostingClassifier` and + :class:`~sklearn.ensemble.GradientBoostingRegressor`, not to + :class:`~sklearn.ensemble.HistGradientBoostingClassifier` and + :class:`~sklearn.ensemble.HistGradientBoostingRegressor`. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : BaseEstimator + A fitted estimator object implementing :term:`predict`, + :term:`predict_proba`, or :term:`decision_function`. + Multioutput-multiclass classifiers are not supported. + + X : {array-like, dataframe} of shape (n_samples, n_features) + ``X`` is used to generate a grid of values for the target + ``features`` (where the partial dependence will be evaluated), and + also to generate values for the complement features when the + `method` is `'brute'`. + + features : list of {int, str, pair of int, pair of str} + The target features for which to create the PDPs. + If `features[i]` is an integer or a string, a one-way PDP is created; + if `features[i]` is a tuple, a two-way PDP is created (only supported + with `kind='average'`). Each tuple must be of size 2. + If any entry is a string, then it must be in ``feature_names``. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights are used to calculate weighted means when averaging the + model output. If `None`, then samples are equally weighted. If + `sample_weight` is not `None`, then `method` will be set to `'brute'`. + Note that `sample_weight` is ignored for `kind='individual'`. + + .. versionadded:: 1.3 + + categorical_features : array-like of shape (n_features,) or shape \ + (n_categorical_features,), dtype={bool, int, str}, default=None + Indicates the categorical features. + + - `None`: no feature will be considered categorical; + - boolean array-like: boolean mask of shape `(n_features,)` + indicating which features are categorical. Thus, this array has + the same shape has `X.shape[1]`; + - integer or string array-like: integer indices or strings + indicating categorical features. + + .. versionadded:: 1.2 + + feature_names : array-like of shape (n_features,), dtype=str, default=None + Name of each feature; `feature_names[i]` holds the name of the feature + with index `i`. + By default, the name of the feature corresponds to their numerical + index for NumPy array and their column name for pandas dataframe. + + target : int, default=None + - In a multiclass setting, specifies the class for which the PDPs + should be computed. Note that for binary classification, the + positive class (index 1) is always used. + - In a multioutput setting, specifies the task for which the PDPs + should be computed. + + Ignored in binary classification or classical regression settings. + + response_method : {'auto', 'predict_proba', 'decision_function'}, \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. For regressors + this parameter is ignored and the response is always the output of + :term:`predict`. By default, :term:`predict_proba` is tried first + and we revert to :term:`decision_function` if it doesn't exist. If + ``method`` is `'recursion'`, the response is always the output of + :term:`decision_function`. + + n_cols : int, default=3 + The maximum number of columns in the grid plot. Only active when `ax` + is a single axis or `None`. + + grid_resolution : int, default=100 + The number of equally spaced points on the axes of the plots, for each + target feature. + This parameter is overridden by `custom_values` if that parameter is set. + + percentiles : tuple of float, default=(0.05, 0.95) + The lower and upper percentile used to create the extreme values + for the PDP axes. Must be in [0, 1]. + This parameter is overridden by `custom_values` if that parameter is set. + + custom_values : dict + A dictionary mapping the index of an element of `features` to an + array of values where the partial dependence should be calculated + for that feature. Setting a range of values for a feature overrides + `grid_resolution` and `percentiles`. + + .. versionadded:: 1.7 + + method : str, default='auto' + The method used to calculate the averaged predictions: + + - `'recursion'` is only supported for some tree-based estimators + (namely + :class:`~sklearn.ensemble.GradientBoostingClassifier`, + :class:`~sklearn.ensemble.GradientBoostingRegressor`, + :class:`~sklearn.ensemble.HistGradientBoostingClassifier`, + :class:`~sklearn.ensemble.HistGradientBoostingRegressor`, + :class:`~sklearn.tree.DecisionTreeRegressor`, + :class:`~sklearn.ensemble.RandomForestRegressor` + but is more efficient in terms of speed. + With this method, the target response of a + classifier is always the decision function, not the predicted + probabilities. Since the `'recursion'` method implicitly computes + the average of the ICEs by design, it is not compatible with ICE and + thus `kind` must be `'average'`. + + - `'brute'` is supported for any estimator, but is more + computationally intensive. + + - `'auto'`: the `'recursion'` is used for estimators that support it, + and `'brute'` is used otherwise. If `sample_weight` is not `None`, + then `'brute'` is used regardless of the estimator. + + Please see :ref:`this note ` for + differences between the `'brute'` and `'recursion'` method. + + n_jobs : int, default=None + The number of CPUs to use to compute the partial dependences. + Computation is parallelized over features specified by the `features` + parameter. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : int, default=0 + Verbose output during PD computations. + + line_kw : dict, default=None + Dict with keywords passed to the ``matplotlib.pyplot.plot`` call. + 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`. + + 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`. + + contour_kw : dict, default=None + Dict with keywords passed to the ``matplotlib.pyplot.contourf`` call. + For two-way partial dependence plots. + + ax : Matplotlib axes or array-like of Matplotlib axes, default=None + - If a single axis is passed in, it is treated as a bounding axes + and a grid of partial dependence plots will be drawn within + these bounds. The `n_cols` parameter controls the number of + columns in the grid. + - If an array-like of axes are passed in, the partial dependence + plots will be drawn directly into these axes. + - If `None`, a figure and a bounding axes is created and treated + as the single axes case. + + kind : {'average', 'individual', 'both'}, default='average' + Whether to plot the partial dependence averaged across all the samples + in the dataset or one line per sample or both. + + - ``kind='average'`` results in the traditional PD plot; + - ``kind='individual'`` results in the ICE plot. + + Note that the fast `method='recursion'` option is only available for + `kind='average'` and `sample_weights=None`. Computing individual + dependencies and doing weighted averages requires using the slower + `method='brute'`. + + centered : bool, default=False + If `True`, the ICE and PD lines will start at the origin of the + y-axis. By default, no centering is done. + + .. versionadded:: 1.1 + + subsample : float, int or None, default=1000 + Sampling for ICE curves when `kind` is 'individual' or 'both'. + If `float`, should be between 0.0 and 1.0 and represent the proportion + of the dataset to be used to plot ICE curves. If `int`, represents the + absolute number samples to use. + + Note that the full dataset is still used to calculate averaged partial + dependence when `kind='both'`. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the selected samples when subsamples is not + `None` and `kind` is either `'both'` or `'individual'`. + See :term:`Glossary ` for details. + + Returns + ------- + display : :class:`~sklearn.inspection.PartialDependenceDisplay` + + See Also + -------- + partial_dependence : Compute Partial Dependence values. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_friedman1 + >>> from sklearn.ensemble import GradientBoostingRegressor + >>> from sklearn.inspection import PartialDependenceDisplay + >>> X, y = make_friedman1() + >>> clf = GradientBoostingRegressor(n_estimators=10).fit(X, y) + >>> PartialDependenceDisplay.from_estimator(clf, X, [0, (0, 1)]) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + import matplotlib.pyplot as plt + + # set target_idx for multi-class estimators + if hasattr(estimator, "classes_") and np.size(estimator.classes_) > 2: + if target is None: + raise ValueError("target must be specified for multi-class") + target_idx = np.searchsorted(estimator.classes_, target) + if ( + not (0 <= target_idx < len(estimator.classes_)) + or estimator.classes_[target_idx] != target + ): + raise ValueError("target not in est.classes_, got {}".format(target)) + else: + # regression and binary classification + target_idx = 0 + + # Use check_array only on lists and other non-array-likes / sparse. Do not + # convert DataFrame into a NumPy array. + if not (hasattr(X, "__array__") or sparse.issparse(X)): + X = check_array(X, ensure_all_finite="allow-nan", dtype=object) + n_features = X.shape[1] + + feature_names = _check_feature_names(X, feature_names) + # expand kind to always be a list of str + kind_ = [kind] * len(features) if isinstance(kind, str) else kind + if len(kind_) != len(features): + raise ValueError( + "When `kind` is provided as a list of strings, it should contain " + f"as many elements as `features`. `kind` contains {len(kind_)} " + f"element(s) and `features` contains {len(features)} element(s)." + ) + + # convert features into a seq of int tuples + tmp_features, ice_for_two_way_pd = [], [] + for kind_plot, fxs in zip(kind_, features): + if isinstance(fxs, (numbers.Integral, str)): + fxs = (fxs,) + try: + fxs = tuple( + _get_feature_index(fx, feature_names=feature_names) for fx in fxs + ) + except TypeError as e: + raise ValueError( + "Each entry in features must be either an int, " + "a string, or an iterable of size at most 2." + ) from e + if not 1 <= np.size(fxs) <= 2: + raise ValueError( + "Each entry in features must be either an int, " + "a string, or an iterable of size at most 2." + ) + # store the information if 2-way PD was requested with ICE to later + # raise a ValueError with an exhaustive list of problematic + # settings. + ice_for_two_way_pd.append(kind_plot != "average" and np.size(fxs) > 1) + + tmp_features.append(fxs) + + if any(ice_for_two_way_pd): + # raise an error and be specific regarding the parameter values + # when 1- and 2-way PD were requested + kind_ = [ + "average" if forcing_average else kind_plot + for forcing_average, kind_plot in zip(ice_for_two_way_pd, kind_) + ] + raise ValueError( + "ICE plot cannot be rendered for 2-way feature interactions. " + "2-way feature interactions mandates PD plots using the " + "'average' kind: " + f"features={features!r} should be configured to use " + f"kind={kind_!r} explicitly." + ) + features = tmp_features + + if categorical_features is None: + is_categorical = [ + (False,) if len(fxs) == 1 else (False, False) for fxs in features + ] + else: + # we need to create a boolean indicator of which features are + # categorical from the categorical_features list. + categorical_features = np.asarray(categorical_features) + if categorical_features.dtype.kind == "b": + # categorical features provided as a list of boolean + if categorical_features.size != n_features: + raise ValueError( + "When `categorical_features` is a boolean array-like, " + "the array should be of shape (n_features,). Got " + f"{categorical_features.size} elements while `X` contains " + f"{n_features} features." + ) + is_categorical = [ + tuple(categorical_features[fx] for fx in fxs) for fxs in features + ] + elif categorical_features.dtype.kind in ("i", "O", "U"): + # categorical features provided as a list of indices or feature names + categorical_features_idx = [ + _get_feature_index(cat, feature_names=feature_names) + for cat in categorical_features + ] + is_categorical = [ + tuple([idx in categorical_features_idx for idx in fxs]) + for fxs in features + ] + else: + raise ValueError( + "Expected `categorical_features` to be an array-like of boolean," + f" integer, or string. Got {categorical_features.dtype} instead." + ) + + for cats in is_categorical: + if np.size(cats) == 2 and (cats[0] != cats[1]): + raise ValueError( + "Two-way partial dependence plots are not supported for pairs" + " of continuous and categorical features." + ) + + # collect the indices of the categorical features targeted by the partial + # dependence computation + categorical_features_targeted = set( + [ + fx + for fxs, cats in zip(features, is_categorical) + for fx in fxs + if any(cats) + ] + ) + if categorical_features_targeted: + min_n_cats = min( + [ + len(_unique(_safe_indexing(X, idx, axis=1))) + for idx in categorical_features_targeted + ] + ) + if grid_resolution < min_n_cats: + raise ValueError( + "The resolution of the computed grid is less than the " + "minimum number of categories in the targeted categorical " + "features. Expect the `grid_resolution` to be greater than " + f"{min_n_cats}. Got {grid_resolution} instead." + ) + + for is_cat, kind_plot in zip(is_categorical, kind_): + if any(is_cat) and kind_plot != "average": + raise ValueError( + "It is not possible to display individual effects for" + " categorical features." + ) + + # Early exit if the axes does not have the correct number of axes + if ax is not None and not isinstance(ax, plt.Axes): + axes = np.asarray(ax, dtype=object) + if axes.size != len(features): + raise ValueError( + "Expected ax to have {} axes, got {}".format( + len(features), axes.size + ) + ) + + for i in chain.from_iterable(features): + if i >= len(feature_names): + raise ValueError( + "All entries of features must be less than " + "len(feature_names) = {0}, got {1}.".format(len(feature_names), i) + ) + + if isinstance(subsample, numbers.Integral): + if subsample <= 0: + raise ValueError( + f"When an integer, subsample={subsample} should be positive." + ) + elif isinstance(subsample, numbers.Real): + if subsample <= 0 or subsample >= 1: + raise ValueError( + f"When a floating-point, subsample={subsample} should be in " + "the (0, 1) range." + ) + + # compute predictions and/or averaged predictions + pd_results = Parallel(n_jobs=n_jobs, verbose=verbose)( + delayed(partial_dependence)( + estimator, + X, + fxs, + sample_weight=sample_weight, + feature_names=feature_names, + categorical_features=categorical_features, + response_method=response_method, + method=method, + grid_resolution=grid_resolution, + percentiles=percentiles, + kind=kind_plot, + custom_values=custom_values, + ) + for kind_plot, fxs in zip(kind_, features) + ) + + # For multioutput regression, we can only check the validity of target + # now that we have the predictions. + # Also note: as multiclass-multioutput classifiers are not supported, + # multiclass and multioutput scenario are mutually exclusive. So there is + # no risk of overwriting target_idx here. + pd_result = pd_results[0] # checking the first result is enough + n_tasks = ( + pd_result.average.shape[0] + if kind_[0] == "average" + else pd_result.individual.shape[0] + ) + if is_regressor(estimator) and n_tasks > 1: + if target is None: + raise ValueError("target must be specified for multi-output regressors") + if not 0 <= target <= n_tasks: + raise ValueError( + "target must be in [0, n_tasks], got {}.".format(target) + ) + target_idx = target + + deciles = {} + for fxs, cats in zip(features, is_categorical): + for fx, cat in zip(fxs, cats): + if not cat and fx not in deciles: + X_col = _safe_indexing(X, fx, axis=1) + deciles[fx] = mquantiles(X_col, prob=np.arange(0.1, 1.0, 0.1)) + + display = cls( + pd_results=pd_results, + features=features, + feature_names=feature_names, + target_idx=target_idx, + deciles=deciles, + kind=kind, + subsample=subsample, + random_state=random_state, + is_categorical=is_categorical, + ) + 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, + centered=centered, + ) + + def _get_sample_count(self, n_samples): + """Compute the number of samples as an integer.""" + if isinstance(self.subsample, numbers.Integral): + if self.subsample < n_samples: + return self.subsample + return n_samples + elif isinstance(self.subsample, numbers.Real): + return ceil(n_samples * self.subsample) + return n_samples + + def _plot_ice_lines( + self, + preds, + feature_values, + n_ice_to_plot, + ax, + pd_plot_idx, + n_total_lines_by_plot, + individual_line_kw, + ): + """Plot the ICE lines. + + Parameters + ---------- + preds : ndarray of shape \ + (n_instances, n_grid_points) + The predictions computed for all points of `feature_values` for a + given feature for all samples in `X`. + feature_values : ndarray of shape (n_grid_points,) + The feature values for which the predictions have been computed. + n_ice_to_plot : int + The number of ICE lines to plot. + ax : Matplotlib axes + The axis on which to plot the ICE lines. + pd_plot_idx : int + The sequential index of the plot. It will be unraveled to find the + matching 2D position in the grid layout. + n_total_lines_by_plot : int + The total number of lines expected to be plot on the axis. + individual_line_kw : dict + Dict with keywords passed when plotting the ICE lines. + """ + rng = check_random_state(self.random_state) + # subsample ice + ice_lines_idx = rng.choice( + preds.shape[0], + n_ice_to_plot, + replace=False, + ) + ice_lines_subsampled = preds[ice_lines_idx, :] + # plot the subsampled ice + for ice_idx, ice in enumerate(ice_lines_subsampled): + line_idx = np.unravel_index( + pd_plot_idx * n_total_lines_by_plot + ice_idx, self.lines_.shape + ) + self.lines_[line_idx] = ax.plot( + feature_values, ice.ravel(), **individual_line_kw + )[0] + + def _plot_average_dependence( + self, + avg_preds, + feature_values, + ax, + pd_line_idx, + line_kw, + categorical, + bar_kw, + ): + """Plot the average partial dependence. + + Parameters + ---------- + avg_preds : ndarray of shape (n_grid_points,) + The average predictions for all points of `feature_values` for a + given feature for all samples in `X`. + feature_values : ndarray of shape (n_grid_points,) + The feature values for which the predictions have been computed. + ax : Matplotlib axes + The axis on which to plot the average PD. + pd_line_idx : int + The sequential index of the plot. It will be unraveled to find the + matching 2D position in the grid layout. + line_kw : dict + Dict with keywords passed when plotting the PD plot. + categorical : bool + Whether feature is categorical. + bar_kw: dict + Dict with keywords passed when plotting the PD bars (categorical). + """ + if categorical: + bar_idx = np.unravel_index(pd_line_idx, self.bars_.shape) + self.bars_[bar_idx] = ax.bar(feature_values, avg_preds, **bar_kw)[0] + ax.tick_params(axis="x", rotation=90) + else: + line_idx = np.unravel_index(pd_line_idx, self.lines_.shape) + self.lines_[line_idx] = ax.plot( + feature_values, + avg_preds, + **line_kw, + )[0] + + def _plot_one_way_partial_dependence( + self, + kind, + preds, + avg_preds, + feature_values, + feature_idx, + n_ice_lines, + ax, + n_cols, + pd_plot_idx, + n_lines, + ice_lines_kw, + pd_line_kw, + categorical, + bar_kw, + pdp_lim, + ): + """Plot 1-way partial dependence: ICE and PDP. + + Parameters + ---------- + kind : str + The kind of partial plot to draw. + preds : ndarray of shape \ + (n_instances, n_grid_points) or None + The predictions computed for all points of `feature_values` for a + given feature for all samples in `X`. + avg_preds : ndarray of shape (n_grid_points,) + The average predictions for all points of `feature_values` for a + given feature for all samples in `X`. + feature_values : ndarray of shape (n_grid_points,) + The feature values for which the predictions have been computed. + feature_idx : int + The index corresponding to the target feature. + n_ice_lines : int + The number of ICE lines to plot. + ax : Matplotlib axes + The axis on which to plot the ICE and PDP lines. + n_cols : int or None + The number of column in the axis. + pd_plot_idx : int + The sequential index of the plot. It will be unraveled to find the + matching 2D position in the grid layout. + n_lines : int + The total number of lines expected to be plot on the axis. + ice_lines_kw : dict + Dict with keywords passed when plotting the ICE lines. + pd_line_kw : dict + Dict with keywords passed when plotting the PD plot. + categorical : bool + Whether feature is categorical. + bar_kw: dict + Dict with keywords passed when plotting the PD bars (categorical). + pdp_lim : dict + Global min and max average predictions, such that all plots will + have the same scale and y limits. `pdp_lim[1]` is the global min + and max for single partial dependence curves. + """ + from matplotlib import transforms + + if kind in ("individual", "both"): + self._plot_ice_lines( + preds[self.target_idx], + feature_values, + n_ice_lines, + ax, + pd_plot_idx, + n_lines, + ice_lines_kw, + ) + + if kind in ("average", "both"): + # the average is stored as the last line + if kind == "average": + pd_line_idx = pd_plot_idx + else: + pd_line_idx = pd_plot_idx * n_lines + n_ice_lines + self._plot_average_dependence( + avg_preds[self.target_idx].ravel(), + feature_values, + ax, + pd_line_idx, + pd_line_kw, + categorical, + bar_kw, + ) + + trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) + # create the decile line for the vertical axis + vlines_idx = np.unravel_index(pd_plot_idx, self.deciles_vlines_.shape) + if self.deciles.get(feature_idx[0], None) is not None: + self.deciles_vlines_[vlines_idx] = ax.vlines( + self.deciles[feature_idx[0]], + 0, + 0.05, + transform=trans, + color="k", + ) + # reset ylim which was overwritten by vlines + min_val = min(val[0] for val in pdp_lim.values()) + max_val = max(val[1] for val in pdp_lim.values()) + ax.set_ylim([min_val, max_val]) + + # Set xlabel if it is not already set + if not ax.get_xlabel(): + ax.set_xlabel(self.feature_names[feature_idx[0]]) + + if n_cols is None or pd_plot_idx % n_cols == 0: + if not ax.get_ylabel(): + ax.set_ylabel("Partial dependence") + else: + ax.set_yticklabels([]) + + if pd_line_kw.get("label", None) and kind != "individual" and not categorical: + ax.legend() + + def _plot_two_way_partial_dependence( + self, + avg_preds, + feature_values, + feature_idx, + ax, + pd_plot_idx, + Z_level, + contour_kw, + categorical, + heatmap_kw, + ): + """Plot 2-way partial dependence. + + Parameters + ---------- + avg_preds : ndarray of shape \ + (n_instances, n_grid_points, n_grid_points) + The average predictions for all points of `feature_values[0]` and + `feature_values[1]` for some given features for all samples in `X`. + feature_values : seq of 1d array + A sequence of array of the feature values for which the predictions + have been computed. + feature_idx : tuple of int + The indices of the target features + ax : Matplotlib axes + The axis on which to plot the ICE and PDP lines. + pd_plot_idx : int + The sequential index of the plot. It will be unraveled to find the + matching 2D position in the grid layout. + Z_level : ndarray of shape (8, 8) + The Z-level used to encode the average predictions. + contour_kw : dict + Dict with keywords passed when plotting the contours. + categorical : bool + Whether features are categorical. + heatmap_kw: dict + Dict with keywords passed when plotting the PD heatmap + (categorical). + """ + if categorical: + import matplotlib.pyplot as plt + + default_im_kw = dict(interpolation="nearest", cmap="viridis") + im_kw = {**default_im_kw, **heatmap_kw} + + data = avg_preds[self.target_idx] + im = ax.imshow(data, **im_kw) + text = None + cmap_min, cmap_max = im.cmap(0), im.cmap(1.0) + + text = np.empty_like(data, dtype=object) + # print text with appropriate color depending on background + thresh = (data.max() + data.min()) / 2.0 + + for flat_index in range(data.size): + row, col = np.unravel_index(flat_index, data.shape) + color = cmap_max if data[row, col] < thresh else cmap_min + + values_format = ".2f" + text_data = format(data[row, col], values_format) + + text_kwargs = dict(ha="center", va="center", color=color) + text[row, col] = ax.text(col, row, text_data, **text_kwargs) + + fig = ax.figure + fig.colorbar(im, ax=ax) + ax.set( + xticks=np.arange(len(feature_values[1])), + yticks=np.arange(len(feature_values[0])), + xticklabels=feature_values[1], + yticklabels=feature_values[0], + xlabel=self.feature_names[feature_idx[1]], + ylabel=self.feature_names[feature_idx[0]], + ) + + plt.setp(ax.get_xticklabels(), rotation="vertical") + + heatmap_idx = np.unravel_index(pd_plot_idx, self.heatmaps_.shape) + self.heatmaps_[heatmap_idx] = im + else: + from matplotlib import transforms + + XX, YY = np.meshgrid(feature_values[0], feature_values[1]) + Z = avg_preds[self.target_idx].T + CS = ax.contour(XX, YY, Z, levels=Z_level, linewidths=0.5, colors="k") + contour_idx = np.unravel_index(pd_plot_idx, self.contours_.shape) + self.contours_[contour_idx] = ax.contourf( + XX, + YY, + Z, + levels=Z_level, + vmax=Z_level[-1], + vmin=Z_level[0], + **contour_kw, + ) + ax.clabel(CS, fmt="%2.2f", colors="k", fontsize=10, inline=True) + + trans = transforms.blended_transform_factory(ax.transData, ax.transAxes) + # create the decile line for the vertical axis + xlim, ylim = ax.get_xlim(), ax.get_ylim() + vlines_idx = np.unravel_index(pd_plot_idx, self.deciles_vlines_.shape) + self.deciles_vlines_[vlines_idx] = ax.vlines( + self.deciles[feature_idx[0]], + 0, + 0.05, + transform=trans, + color="k", + ) + # create the decile line for the horizontal axis + hlines_idx = np.unravel_index(pd_plot_idx, self.deciles_hlines_.shape) + self.deciles_hlines_[hlines_idx] = ax.hlines( + self.deciles[feature_idx[1]], + 0, + 0.05, + transform=trans, + color="k", + ) + # reset xlim and ylim since they are overwritten by hlines and + # vlines + ax.set_xlim(xlim) + ax.set_ylim(ylim) + + # set xlabel if it is not already set + if not ax.get_xlabel(): + ax.set_xlabel(self.feature_names[feature_idx[0]]) + ax.set_ylabel(self.feature_names[feature_idx[1]]) + + def plot( + self, + *, + ax=None, + n_cols=3, + line_kw=None, + ice_lines_kw=None, + pd_line_kw=None, + contour_kw=None, + bar_kw=None, + heatmap_kw=None, + pdp_lim=None, + centered=False, + ): + """Plot partial dependence plots. + + Parameters + ---------- + ax : Matplotlib axes or array-like of Matplotlib axes, default=None + - If a single axis is passed in, it is treated as a bounding axes + and a grid of partial dependence plots will be drawn within + these bounds. The `n_cols` parameter controls the number of + columns in the grid. + - If an array-like of axes are passed in, the partial dependence + plots will be drawn directly into these axes. + - If `None`, a figure and a bounding axes is created and treated + as the single axes case. + + n_cols : int, default=3 + The maximum number of columns in the grid plot. Only active when + `ax` is a single axes or `None`. + + line_kw : dict, default=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. + + bar_kw : dict, default=None + Dict with keywords passed to the `matplotlib.pyplot.bar` + call for one-way categorical partial dependence plots. + + .. versionadded:: 1.2 + + heatmap_kw : dict, default=None + Dict with keywords passed to the `matplotlib.pyplot.imshow` + call for two-way categorical partial dependence plots. + + .. versionadded:: 1.2 + + pdp_lim : dict, default=None + Global min and max average predictions, such that all plots will have the + same scale and y limits. `pdp_lim[1]` is the global min and max for single + partial dependence curves. `pdp_lim[2]` is the global min and max for + two-way partial dependence curves. If `None` (default), the limit will be + inferred from the global minimum and maximum of all predictions. + + .. versionadded:: 1.1 + + centered : bool, default=False + If `True`, the ICE and PD lines will start at the origin of the + y-axis. By default, no centering is done. + + .. versionadded:: 1.1 + + Returns + ------- + display : :class:`~sklearn.inspection.PartialDependenceDisplay` + Returns a :class:`~sklearn.inspection.PartialDependenceDisplay` + object that contains the partial dependence plots. + """ + + check_matplotlib_support("plot_partial_dependence") + import matplotlib.pyplot as plt + from matplotlib.gridspec import GridSpecFromSubplotSpec + + if isinstance(self.kind, str): + kind = [self.kind] * len(self.features) + else: + kind = self.kind + + if self.is_categorical is None: + is_categorical = [ + (False,) if len(fx) == 1 else (False, False) for fx in self.features + ] + else: + is_categorical = self.is_categorical + + if len(kind) != len(self.features): + raise ValueError( + "When `kind` is provided as a list of strings, it should " + "contain as many elements as `features`. `kind` contains " + f"{len(kind)} element(s) and `features` contains " + f"{len(self.features)} element(s)." + ) + + valid_kinds = {"average", "individual", "both"} + if any([k not in valid_kinds for k in kind]): + raise ValueError( + f"Values provided to `kind` must be one of: {valid_kinds!r} or a list" + f" of such values. Currently, kind={self.kind!r}" + ) + + # Center results before plotting + if not centered: + pd_results_ = self.pd_results + else: + pd_results_ = [] + for kind_plot, pd_result in zip(kind, self.pd_results): + current_results = {"grid_values": pd_result["grid_values"]} + + if kind_plot in ("individual", "both"): + preds = pd_result.individual + preds = preds - preds[self.target_idx, :, 0, None] + current_results["individual"] = preds + + if kind_plot in ("average", "both"): + avg_preds = pd_result.average + avg_preds = avg_preds - avg_preds[self.target_idx, 0, None] + current_results["average"] = avg_preds + + pd_results_.append(Bunch(**current_results)) + + if pdp_lim is None: + # get global min and max average predictions of PD grouped by plot type + pdp_lim = {} + for kind_plot, pdp in zip(kind, pd_results_): + values = pdp["grid_values"] + preds = pdp.average if kind_plot == "average" else pdp.individual + min_pd = preds[self.target_idx].min() + max_pd = preds[self.target_idx].max() + + # expand the limits to account so that the plotted lines do not touch + # the edges of the plot + span = max_pd - min_pd + min_pd -= 0.05 * span + max_pd += 0.05 * span + + n_fx = len(values) + old_min_pd, old_max_pd = pdp_lim.get(n_fx, (min_pd, max_pd)) + min_pd = min(min_pd, old_min_pd) + max_pd = max(max_pd, old_max_pd) + pdp_lim[n_fx] = (min_pd, max_pd) + + 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 bar_kw is None: + bar_kw = {} + if heatmap_kw is None: + heatmap_kw = {} + + if ax is None: + _, ax = plt.subplots() + + if contour_kw is None: + contour_kw = {} + default_contour_kws = {"alpha": 0.75} + contour_kw = _validate_style_kwargs(default_contour_kws, contour_kw) + + n_features = len(self.features) + is_average_plot = [kind_plot == "average" for kind_plot in kind] + if all(is_average_plot): + # only average plots are requested + n_ice_lines = 0 + n_lines = 1 + else: + # we need to determine the number of ICE samples computed + ice_plot_idx = is_average_plot.index(False) + n_ice_lines = self._get_sample_count( + len(pd_results_[ice_plot_idx].individual[0]) + ) + if any([kind_plot == "both" for kind_plot in kind]): + n_lines = n_ice_lines + 1 # account for the average line + else: + n_lines = n_ice_lines + + if isinstance(ax, plt.Axes): + # If ax was set off, it has most likely been set to off + # by a previous call to plot. + if not ax.axison: + raise ValueError( + "The ax was already used in another plot " + "function, please set ax=display.axes_ " + "instead" + ) + + ax.set_axis_off() + self.bounding_ax_ = ax + self.figure_ = ax.figure + + n_cols = min(n_cols, n_features) + n_rows = int(np.ceil(n_features / float(n_cols))) + + self.axes_ = np.empty((n_rows, n_cols), dtype=object) + if all(is_average_plot): + self.lines_ = np.empty((n_rows, n_cols), dtype=object) + else: + self.lines_ = np.empty((n_rows, n_cols, n_lines), dtype=object) + self.contours_ = np.empty((n_rows, n_cols), dtype=object) + self.bars_ = np.empty((n_rows, n_cols), dtype=object) + self.heatmaps_ = np.empty((n_rows, n_cols), dtype=object) + + axes_ravel = self.axes_.ravel() + + gs = GridSpecFromSubplotSpec( + n_rows, n_cols, subplot_spec=ax.get_subplotspec() + ) + for i, spec in zip(range(n_features), gs): + axes_ravel[i] = self.figure_.add_subplot(spec) + + else: # array-like + ax = np.asarray(ax, dtype=object) + if ax.size != n_features: + raise ValueError( + "Expected ax to have {} axes, got {}".format(n_features, ax.size) + ) + + if ax.ndim == 2: + n_cols = ax.shape[1] + else: + n_cols = None + + self.bounding_ax_ = None + self.figure_ = ax.ravel()[0].figure + self.axes_ = ax + if all(is_average_plot): + self.lines_ = np.empty_like(ax, dtype=object) + else: + self.lines_ = np.empty(ax.shape + (n_lines,), dtype=object) + self.contours_ = np.empty_like(ax, dtype=object) + self.bars_ = np.empty_like(ax, dtype=object) + self.heatmaps_ = np.empty_like(ax, dtype=object) + + # create contour levels for two-way plots + if 2 in pdp_lim: + Z_level = np.linspace(*pdp_lim[2], num=8) + + self.deciles_vlines_ = np.empty_like(self.axes_, dtype=object) + self.deciles_hlines_ = np.empty_like(self.axes_, dtype=object) + + for pd_plot_idx, (axi, feature_idx, cat, pd_result, kind_plot) in enumerate( + zip( + self.axes_.ravel(), + self.features, + is_categorical, + pd_results_, + kind, + ) + ): + avg_preds = None + preds = None + feature_values = pd_result["grid_values"] + if kind_plot == "individual": + preds = pd_result.individual + elif kind_plot == "average": + avg_preds = pd_result.average + else: # kind_plot == 'both' + avg_preds = pd_result.average + preds = pd_result.individual + + if len(feature_values) == 1: + # define the line-style for the current plot + default_line_kws = { + "color": "C0", + "label": "average" if kind_plot == "both" else None, + } + if kind_plot == "individual": + default_ice_lines_kws = {"alpha": 0.3, "linewidth": 0.5} + default_pd_lines_kws = {} + elif kind_plot == "both": + # by default, we need to distinguish the average line from + # the individual lines via color and line style + default_ice_lines_kws = { + "alpha": 0.3, + "linewidth": 0.5, + "color": "tab:blue", + } + default_pd_lines_kws = { + "color": "tab:orange", + "linestyle": "--", + } + else: + default_ice_lines_kws = {} + default_pd_lines_kws = {} + + default_ice_lines_kws = {**default_line_kws, **default_ice_lines_kws} + default_pd_lines_kws = {**default_line_kws, **default_pd_lines_kws} + + line_kw = _validate_style_kwargs(default_line_kws, line_kw) + + ice_lines_kw = _validate_style_kwargs( + _validate_style_kwargs(default_ice_lines_kws, line_kw), ice_lines_kw + ) + del ice_lines_kw["label"] + + pd_line_kw = _validate_style_kwargs( + _validate_style_kwargs(default_pd_lines_kws, line_kw), pd_line_kw + ) + + default_bar_kws = {"color": "C0"} + bar_kw = _validate_style_kwargs(default_bar_kws, bar_kw) + + default_heatmap_kw = {} + heatmap_kw = _validate_style_kwargs(default_heatmap_kw, heatmap_kw) + + self._plot_one_way_partial_dependence( + kind_plot, + preds, + avg_preds, + feature_values[0], + feature_idx, + n_ice_lines, + axi, + n_cols, + pd_plot_idx, + n_lines, + ice_lines_kw, + pd_line_kw, + cat[0], + bar_kw, + pdp_lim, + ) + else: + self._plot_two_way_partial_dependence( + avg_preds, + feature_values, + feature_idx, + axi, + pd_plot_idx, + Z_level, + contour_kw, + cat[0] and cat[1], + heatmap_kw, + ) + + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_boundary_decision_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_boundary_decision_display.py new file mode 100644 index 0000000000000000000000000000000000000000..f409a50ab58c0865c17082f95122247bb0d5344d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_boundary_decision_display.py @@ -0,0 +1,710 @@ +import warnings + +import numpy as np +import pytest + +from sklearn.base import BaseEstimator, ClassifierMixin +from sklearn.datasets import ( + load_diabetes, + load_iris, + make_classification, + make_multilabel_classification, +) +from sklearn.ensemble import IsolationForest +from sklearn.inspection import DecisionBoundaryDisplay +from sklearn.inspection._plot.decision_boundary import _check_boundary_response_method +from sklearn.linear_model import LogisticRegression +from sklearn.preprocessing import scale +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_array_equal, +) +from sklearn.utils.fixes import parse_version + +X, y = make_classification( + n_informative=1, + n_redundant=1, + n_clusters_per_class=1, + n_features=2, + random_state=42, +) + + +def load_iris_2d_scaled(): + X, y = load_iris(return_X_y=True) + X = scale(X)[:, :2] + return X, y + + +@pytest.fixture(scope="module") +def fitted_clf(): + return LogisticRegression().fit(X, y) + + +def test_input_data_dimension(pyplot): + """Check that we raise an error when `X` does not have exactly 2 features.""" + X, y = make_classification(n_samples=10, n_features=4, random_state=0) + + clf = LogisticRegression().fit(X, y) + msg = "n_features must be equal to 2. Got 4 instead." + with pytest.raises(ValueError, match=msg): + DecisionBoundaryDisplay.from_estimator(estimator=clf, X=X) + + +def test_check_boundary_response_method_error(): + """Check error raised for multi-output multi-class classifiers by + `_check_boundary_response_method`. + """ + + class MultiLabelClassifier: + classes_ = [np.array([0, 1]), np.array([0, 1])] + + err_msg = "Multi-label and multi-output multi-class classifiers are not supported" + with pytest.raises(ValueError, match=err_msg): + _check_boundary_response_method(MultiLabelClassifier(), "predict", None) + + +@pytest.mark.parametrize( + "estimator, response_method, class_of_interest, expected_prediction_method", + [ + (DecisionTreeRegressor(), "predict", None, "predict"), + (DecisionTreeRegressor(), "auto", None, "predict"), + (LogisticRegression().fit(*load_iris_2d_scaled()), "predict", None, "predict"), + ( + LogisticRegression().fit(*load_iris_2d_scaled()), + "auto", + None, + ["decision_function", "predict_proba", "predict"], + ), + ( + LogisticRegression().fit(*load_iris_2d_scaled()), + "predict_proba", + 0, + "predict_proba", + ), + ( + LogisticRegression().fit(*load_iris_2d_scaled()), + "decision_function", + 0, + "decision_function", + ), + ( + LogisticRegression().fit(X, y), + "auto", + None, + ["decision_function", "predict_proba", "predict"], + ), + (LogisticRegression().fit(X, y), "predict", None, "predict"), + ( + LogisticRegression().fit(X, y), + ["predict_proba", "decision_function"], + None, + ["predict_proba", "decision_function"], + ), + ], +) +def test_check_boundary_response_method( + estimator, response_method, class_of_interest, expected_prediction_method +): + """Check the behaviour of `_check_boundary_response_method` for the supported + cases. + """ + prediction_method = _check_boundary_response_method( + estimator, response_method, class_of_interest + ) + assert prediction_method == expected_prediction_method + + +def test_multiclass_predict(pyplot): + """Check multiclass `response=predict` gives expected results.""" + grid_resolution = 10 + eps = 1.0 + X, y = make_classification(n_classes=3, n_informative=3, random_state=0) + X = X[:, [0, 1]] + lr = LogisticRegression(random_state=0).fit(X, y) + + disp = DecisionBoundaryDisplay.from_estimator( + lr, X, response_method="predict", grid_resolution=grid_resolution, eps=1.0 + ) + + x0_min, x0_max = X[:, 0].min() - eps, X[:, 0].max() + eps + x1_min, x1_max = X[:, 1].min() - eps, X[:, 1].max() + eps + xx0, xx1 = np.meshgrid( + np.linspace(x0_min, x0_max, grid_resolution), + np.linspace(x1_min, x1_max, grid_resolution), + ) + response = lr.predict(np.c_[xx0.ravel(), xx1.ravel()]) + assert_allclose(disp.response, response.reshape(xx0.shape)) + assert_allclose(disp.xx0, xx0) + assert_allclose(disp.xx1, xx1) + + +@pytest.mark.parametrize( + "kwargs, error_msg", + [ + ( + {"plot_method": "hello_world"}, + r"plot_method must be one of contourf, contour, pcolormesh. Got hello_world" + r" instead.", + ), + ( + {"grid_resolution": 1}, + r"grid_resolution must be greater than 1. Got 1 instead", + ), + ( + {"grid_resolution": -1}, + r"grid_resolution must be greater than 1. Got -1 instead", + ), + ({"eps": -1.1}, r"eps must be greater than or equal to 0. Got -1.1 instead"), + ], +) +def test_input_validation_errors(pyplot, kwargs, error_msg, fitted_clf): + """Check input validation from_estimator.""" + with pytest.raises(ValueError, match=error_msg): + DecisionBoundaryDisplay.from_estimator(fitted_clf, X, **kwargs) + + +@pytest.mark.parametrize( + "kwargs, error_msg", + [ + ( + {"multiclass_colors": {"dict": "not_list"}}, + "'multiclass_colors' must be a list or a str.", + ), + ({"multiclass_colors": "not_cmap"}, "it must be a valid Matplotlib colormap"), + ({"multiclass_colors": ["red", "green"]}, "it must be of the same length"), + ( + {"multiclass_colors": ["red", "green", "not color"]}, + "it can only contain valid Matplotlib color names", + ), + ], +) +def test_input_validation_errors_multiclass_colors(pyplot, kwargs, error_msg): + """Check input validation for `multiclass_colors` in `from_estimator`.""" + X, y = load_iris_2d_scaled() + clf = LogisticRegression().fit(X, y) + with pytest.raises(ValueError, match=error_msg): + DecisionBoundaryDisplay.from_estimator(clf, X, **kwargs) + + +def test_display_plot_input_error(pyplot, fitted_clf): + """Check input validation for `plot`.""" + disp = DecisionBoundaryDisplay.from_estimator(fitted_clf, X, grid_resolution=5) + + with pytest.raises(ValueError, match="plot_method must be 'contourf'"): + disp.plot(plot_method="hello_world") + + +@pytest.mark.parametrize( + "response_method", ["auto", "predict", "predict_proba", "decision_function"] +) +@pytest.mark.parametrize("plot_method", ["contourf", "contour"]) +def test_decision_boundary_display_classifier( + pyplot, fitted_clf, response_method, plot_method +): + """Check that decision boundary is correct.""" + fig, ax = pyplot.subplots() + eps = 2.0 + disp = DecisionBoundaryDisplay.from_estimator( + fitted_clf, + X, + grid_resolution=5, + response_method=response_method, + plot_method=plot_method, + eps=eps, + ax=ax, + ) + assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet) + assert disp.ax_ == ax + assert disp.figure_ == fig + + x0, x1 = X[:, 0], X[:, 1] + + x0_min, x0_max = x0.min() - eps, x0.max() + eps + x1_min, x1_max = x1.min() - eps, x1.max() + eps + + assert disp.xx0.min() == pytest.approx(x0_min) + assert disp.xx0.max() == pytest.approx(x0_max) + assert disp.xx1.min() == pytest.approx(x1_min) + assert disp.xx1.max() == pytest.approx(x1_max) + + fig2, ax2 = pyplot.subplots() + # change plotting method for second plot + disp.plot(plot_method="pcolormesh", ax=ax2, shading="auto") + assert isinstance(disp.surface_, pyplot.matplotlib.collections.QuadMesh) + assert disp.ax_ == ax2 + assert disp.figure_ == fig2 + + +@pytest.mark.parametrize("response_method", ["auto", "predict", "decision_function"]) +@pytest.mark.parametrize("plot_method", ["contourf", "contour"]) +def test_decision_boundary_display_outlier_detector( + pyplot, response_method, plot_method +): + """Check that decision boundary is correct for outlier detector.""" + fig, ax = pyplot.subplots() + eps = 2.0 + outlier_detector = IsolationForest(random_state=0).fit(X, y) + disp = DecisionBoundaryDisplay.from_estimator( + outlier_detector, + X, + grid_resolution=5, + response_method=response_method, + plot_method=plot_method, + eps=eps, + ax=ax, + ) + assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet) + assert disp.ax_ == ax + assert disp.figure_ == fig + + x0, x1 = X[:, 0], X[:, 1] + + x0_min, x0_max = x0.min() - eps, x0.max() + eps + x1_min, x1_max = x1.min() - eps, x1.max() + eps + + assert disp.xx0.min() == pytest.approx(x0_min) + assert disp.xx0.max() == pytest.approx(x0_max) + assert disp.xx1.min() == pytest.approx(x1_min) + assert disp.xx1.max() == pytest.approx(x1_max) + + +@pytest.mark.parametrize("response_method", ["auto", "predict"]) +@pytest.mark.parametrize("plot_method", ["contourf", "contour"]) +def test_decision_boundary_display_regressor(pyplot, response_method, plot_method): + """Check that we can display the decision boundary for a regressor.""" + X, y = load_diabetes(return_X_y=True) + X = X[:, :2] + tree = DecisionTreeRegressor().fit(X, y) + fig, ax = pyplot.subplots() + eps = 2.0 + disp = DecisionBoundaryDisplay.from_estimator( + tree, + X, + response_method=response_method, + ax=ax, + eps=eps, + plot_method=plot_method, + ) + assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet) + assert disp.ax_ == ax + assert disp.figure_ == fig + + x0, x1 = X[:, 0], X[:, 1] + + x0_min, x0_max = x0.min() - eps, x0.max() + eps + x1_min, x1_max = x1.min() - eps, x1.max() + eps + + assert disp.xx0.min() == pytest.approx(x0_min) + assert disp.xx0.max() == pytest.approx(x0_max) + assert disp.xx1.min() == pytest.approx(x1_min) + assert disp.xx1.max() == pytest.approx(x1_max) + + fig2, ax2 = pyplot.subplots() + # change plotting method for second plot + disp.plot(plot_method="pcolormesh", ax=ax2, shading="auto") + assert isinstance(disp.surface_, pyplot.matplotlib.collections.QuadMesh) + assert disp.ax_ == ax2 + assert disp.figure_ == fig2 + + +@pytest.mark.parametrize( + "response_method, msg", + [ + ( + "predict_proba", + "MyClassifier has none of the following attributes: predict_proba", + ), + ( + "decision_function", + "MyClassifier has none of the following attributes: decision_function", + ), + ( + "auto", + ( + "MyClassifier has none of the following attributes: decision_function, " + "predict_proba, predict" + ), + ), + ( + "bad_method", + "MyClassifier has none of the following attributes: bad_method", + ), + ], +) +def test_error_bad_response(pyplot, response_method, msg): + """Check errors for bad response.""" + + class MyClassifier(ClassifierMixin, BaseEstimator): + def fit(self, X, y): + self.fitted_ = True + self.classes_ = [0, 1] + return self + + clf = MyClassifier().fit(X, y) + + with pytest.raises(AttributeError, match=msg): + DecisionBoundaryDisplay.from_estimator(clf, X, response_method=response_method) + + +@pytest.mark.parametrize("response_method", ["auto", "predict", "predict_proba"]) +def test_multilabel_classifier_error(pyplot, response_method): + """Check that multilabel classifier raises correct error.""" + X, y = make_multilabel_classification(random_state=0) + X = X[:, :2] + tree = DecisionTreeClassifier().fit(X, y) + + msg = "Multi-label and multi-output multi-class classifiers are not supported" + with pytest.raises(ValueError, match=msg): + DecisionBoundaryDisplay.from_estimator( + tree, + X, + response_method=response_method, + ) + + +@pytest.mark.parametrize("response_method", ["auto", "predict", "predict_proba"]) +def test_multi_output_multi_class_classifier_error(pyplot, response_method): + """Check that multi-output multi-class classifier raises correct error.""" + X = np.asarray([[0, 1], [1, 2]]) + y = np.asarray([["tree", "cat"], ["cat", "tree"]]) + tree = DecisionTreeClassifier().fit(X, y) + + msg = "Multi-label and multi-output multi-class classifiers are not supported" + with pytest.raises(ValueError, match=msg): + DecisionBoundaryDisplay.from_estimator( + tree, + X, + response_method=response_method, + ) + + +def test_multioutput_regressor_error(pyplot): + """Check that multioutput regressor raises correct error.""" + X = np.asarray([[0, 1], [1, 2]]) + y = np.asarray([[0, 1], [4, 1]]) + tree = DecisionTreeRegressor().fit(X, y) + with pytest.raises(ValueError, match="Multi-output regressors are not supported"): + DecisionBoundaryDisplay.from_estimator(tree, X, response_method="predict") + + +@pytest.mark.parametrize( + "response_method", + ["predict_proba", "decision_function", ["predict_proba", "predict"]], +) +def test_regressor_unsupported_response(pyplot, response_method): + """Check that we can display the decision boundary for a regressor.""" + X, y = load_diabetes(return_X_y=True) + X = X[:, :2] + tree = DecisionTreeRegressor().fit(X, y) + err_msg = "should either be a classifier to be used with response_method" + with pytest.raises(ValueError, match=err_msg): + DecisionBoundaryDisplay.from_estimator(tree, X, response_method=response_method) + + +@pytest.mark.filterwarnings( + # We expect to raise the following warning because the classifier is fit on a + # NumPy array + "ignore:X has feature names, but LogisticRegression was fitted without" +) +def test_dataframe_labels_used(pyplot, fitted_clf): + """Check that column names are used for pandas.""" + pd = pytest.importorskip("pandas") + df = pd.DataFrame(X, columns=["col_x", "col_y"]) + + # pandas column names are used by default + _, ax = pyplot.subplots() + disp = DecisionBoundaryDisplay.from_estimator(fitted_clf, df, ax=ax) + assert ax.get_xlabel() == "col_x" + assert ax.get_ylabel() == "col_y" + + # second call to plot will have the names + fig, ax = pyplot.subplots() + disp.plot(ax=ax) + assert ax.get_xlabel() == "col_x" + assert ax.get_ylabel() == "col_y" + + # axes with a label will not get overridden + fig, ax = pyplot.subplots() + ax.set(xlabel="hello", ylabel="world") + disp.plot(ax=ax) + assert ax.get_xlabel() == "hello" + assert ax.get_ylabel() == "world" + + # labels get overridden only if provided to the `plot` method + disp.plot(ax=ax, xlabel="overwritten_x", ylabel="overwritten_y") + assert ax.get_xlabel() == "overwritten_x" + assert ax.get_ylabel() == "overwritten_y" + + # labels do not get inferred if provided to `from_estimator` + _, ax = pyplot.subplots() + disp = DecisionBoundaryDisplay.from_estimator( + fitted_clf, df, ax=ax, xlabel="overwritten_x", ylabel="overwritten_y" + ) + assert ax.get_xlabel() == "overwritten_x" + assert ax.get_ylabel() == "overwritten_y" + + +def test_string_target(pyplot): + """Check that decision boundary works with classifiers trained on string labels.""" + iris = load_iris() + X = iris.data[:, [0, 1]] + + # Use strings as target + y = iris.target_names[iris.target] + log_reg = LogisticRegression().fit(X, y) + + # Does not raise + DecisionBoundaryDisplay.from_estimator( + log_reg, + X, + grid_resolution=5, + response_method="predict", + ) + + +@pytest.mark.parametrize("constructor_name", ["pandas", "polars"]) +def test_dataframe_support(pyplot, constructor_name): + """Check that passing a dataframe at fit and to the Display does not + raise warnings. + + Non-regression test for: + * https://github.com/scikit-learn/scikit-learn/issues/23311 + * https://github.com/scikit-learn/scikit-learn/issues/28717 + """ + df = _convert_container( + X, constructor_name=constructor_name, columns_name=["col_x", "col_y"] + ) + estimator = LogisticRegression().fit(df, y) + + with warnings.catch_warnings(): + # no warnings linked to feature names validation should be raised + warnings.simplefilter("error", UserWarning) + DecisionBoundaryDisplay.from_estimator(estimator, df, response_method="predict") + + +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_class_of_interest_binary(pyplot, response_method): + """Check the behaviour of passing `class_of_interest` for plotting the output of + `predict_proba` and `decision_function` in the binary case. + """ + iris = load_iris() + X = iris.data[:100, :2] + y = iris.target[:100] + assert_array_equal(np.unique(y), [0, 1]) + + estimator = LogisticRegression().fit(X, y) + # We will check that `class_of_interest=None` is equivalent to + # `class_of_interest=estimator.classes_[1]` + disp_default = DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=None, + ) + disp_class_1 = DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=estimator.classes_[1], + ) + + assert_allclose(disp_default.response, disp_class_1.response) + + # we can check that `_get_response_values` modifies the response when targeting + # the other class, i.e. 1 - p(y=1|x) for `predict_proba` and -decision_function + # for `decision_function`. + disp_class_0 = DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=estimator.classes_[0], + ) + + if response_method == "predict_proba": + assert_allclose(disp_default.response, 1 - disp_class_0.response) + else: + assert response_method == "decision_function" + assert_allclose(disp_default.response, -disp_class_0.response) + + +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_class_of_interest_multiclass(pyplot, response_method): + """Check the behaviour of passing `class_of_interest` for plotting the output of + `predict_proba` and `decision_function` in the multiclass case. + """ + iris = load_iris() + X = iris.data[:, :2] + y = iris.target # the target are numerical labels + class_of_interest_idx = 2 + + estimator = LogisticRegression().fit(X, y) + disp = DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=class_of_interest_idx, + ) + + # we will check that we plot the expected values as response + grid = np.concatenate([disp.xx0.reshape(-1, 1), disp.xx1.reshape(-1, 1)], axis=1) + response = getattr(estimator, response_method)(grid)[:, class_of_interest_idx] + assert_allclose(response.reshape(*disp.response.shape), disp.response) + + # make the same test but this time using target as strings + y = iris.target_names[iris.target] + estimator = LogisticRegression().fit(X, y) + + disp = DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=iris.target_names[class_of_interest_idx], + ) + + grid = np.concatenate([disp.xx0.reshape(-1, 1), disp.xx1.reshape(-1, 1)], axis=1) + response = getattr(estimator, response_method)(grid)[:, class_of_interest_idx] + assert_allclose(response.reshape(*disp.response.shape), disp.response) + + # check that we raise an error for unknown labels + # this test should already be handled in `_get_response_values` but we can have this + # test here as well + err_msg = "class_of_interest=2 is not a valid label: It should be one of" + with pytest.raises(ValueError, match=err_msg): + DecisionBoundaryDisplay.from_estimator( + estimator, + X, + response_method=response_method, + class_of_interest=class_of_interest_idx, + ) + + +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_multiclass_plot_max_class(pyplot, response_method): + """Check plot correct when plotting max multiclass class.""" + import matplotlib as mpl + + # In matplotlib < v3.5, default value of `pcolormesh(shading)` is 'flat', which + # results in the last row and column being dropped. Thus older versions produce + # a 99x99 grid, while newer versions produce a 100x100 grid. + if parse_version(mpl.__version__) < parse_version("3.5"): + pytest.skip("`pcolormesh` in Matplotlib >= 3.5 gives smaller grid size.") + + X, y = load_iris_2d_scaled() + clf = LogisticRegression().fit(X, y) + + disp = DecisionBoundaryDisplay.from_estimator( + clf, + X, + plot_method="pcolormesh", + response_method=response_method, + ) + + grid = np.concatenate([disp.xx0.reshape(-1, 1), disp.xx1.reshape(-1, 1)], axis=1) + response = getattr(clf, response_method)(grid).reshape(*disp.response.shape) + assert_allclose(response, disp.response) + + assert len(disp.surface_) == len(clf.classes_) + # Get which class has highest response and check it is plotted + highest_class = np.argmax(response, axis=2) + for idx, quadmesh in enumerate(disp.surface_): + # Note quadmesh mask is True (i.e. masked) when `idx` is NOT the highest class + assert_array_equal( + highest_class != idx, + quadmesh.get_array().mask.reshape(*highest_class.shape), + ) + + +@pytest.mark.parametrize( + "multiclass_colors", + [ + "plasma", + "Blues", + ["red", "green", "blue"], + ], +) +@pytest.mark.parametrize("plot_method", ["contourf", "contour", "pcolormesh"]) +def test_multiclass_colors_cmap(pyplot, plot_method, multiclass_colors): + """Check correct cmap used for all `multiclass_colors` inputs.""" + import matplotlib as mpl + + if parse_version(mpl.__version__) < parse_version("3.5"): + pytest.skip( + "Matplotlib >= 3.5 is needed for `==` to check equivalence of colormaps" + ) + + X, y = load_iris_2d_scaled() + clf = LogisticRegression().fit(X, y) + + disp = DecisionBoundaryDisplay.from_estimator( + clf, + X, + plot_method=plot_method, + multiclass_colors=multiclass_colors, + ) + + if multiclass_colors == "plasma": + colors = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_)).colors + elif multiclass_colors == "Blues": + cmap = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_)) + colors = cmap(np.linspace(0, 1, len(clf.classes_))) + else: + colors = [mpl.colors.to_rgba(color) for color in multiclass_colors] + + if plot_method != "contour": + cmaps = [ + mpl.colors.LinearSegmentedColormap.from_list( + f"colormap_{class_idx}", [(1.0, 1.0, 1.0, 1.0), (r, g, b, 1.0)] + ) + for class_idx, (r, g, b, _) in enumerate(colors) + ] + for idx, quad in enumerate(disp.surface_): + assert quad.cmap == cmaps[idx] + else: + assert_allclose(disp.surface_.colors, colors) + + +def test_cmap_and_colors_logic(pyplot): + """Check the handling logic for `cmap` and `colors`.""" + X, y = load_iris_2d_scaled() + clf = LogisticRegression().fit(X, y) + + with pytest.warns( + UserWarning, + match="'cmap' is ignored in favor of 'multiclass_colors'", + ): + DecisionBoundaryDisplay.from_estimator( + clf, + X, + multiclass_colors="plasma", + cmap="Blues", + ) + + with pytest.warns( + UserWarning, + match="'colors' is ignored in favor of 'multiclass_colors'", + ): + DecisionBoundaryDisplay.from_estimator( + clf, + X, + multiclass_colors="plasma", + colors="blue", + ) + + +def test_subclass_named_constructors_return_type_is_subclass(pyplot): + """Check that named constructors return the correct type when subclassed. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/27675 + """ + clf = LogisticRegression().fit(X, y) + + class SubclassOfDisplay(DecisionBoundaryDisplay): + pass + + curve = SubclassOfDisplay.from_estimator(estimator=clf, X=X) + + assert isinstance(curve, SubclassOfDisplay) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py new file mode 100644 index 0000000000000000000000000000000000000000..75869079be9cc4fd2113a5186960e7acbc3722d4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py @@ -0,0 +1,1315 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.stats.mstats import mquantiles + +from sklearn.compose import make_column_transformer +from sklearn.datasets import ( + load_diabetes, + load_iris, + make_classification, + make_regression, +) +from sklearn.ensemble import GradientBoostingClassifier, GradientBoostingRegressor +from sklearn.inspection import PartialDependenceDisplay +from sklearn.linear_model import LinearRegression +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import OneHotEncoder +from sklearn.utils._testing import _convert_container + + +@pytest.fixture(scope="module") +def diabetes(): + # diabetes dataset, subsampled for speed + data = load_diabetes() + data.data = data.data[:50] + data.target = data.target[:50] + return data + + +@pytest.fixture(scope="module") +def clf_diabetes(diabetes): + clf = GradientBoostingRegressor(n_estimators=10, random_state=1) + clf.fit(diabetes.data, diabetes.target) + return clf + + +def custom_values_helper(feature, grid_resolution): + return np.linspace( + *mquantiles(feature, (0.05, 0.95), axis=0), num=grid_resolution, endpoint=True + ) + + +@pytest.mark.filterwarnings("ignore:A Bunch will be returned") +@pytest.mark.parametrize("grid_resolution", [10, 20]) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence( + use_custom_values, + grid_resolution, + pyplot, + clf_diabetes, + diabetes, +): + # Test partial dependence plot function. + # Use columns 0 & 2 as 1 is not quantitative (sex) + feature_names = diabetes.feature_names + custom_values = None + if use_custom_values: + custom_values = { + 0: custom_values_helper(diabetes.data[:, 0], grid_resolution), + 2: custom_values_helper(diabetes.data[:, 2], grid_resolution), + } + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 2, (0, 2)], + grid_resolution=grid_resolution, + feature_names=feature_names, + contour_kw={"cmap": "jet"}, + custom_values=custom_values, + ) + fig = pyplot.gcf() + axs = fig.get_axes() + assert disp.figure_ is fig + assert len(axs) == 4 + + assert disp.bounding_ax_ is not None + assert disp.axes_.shape == (1, 3) + assert disp.lines_.shape == (1, 3) + assert disp.contours_.shape == (1, 3) + assert disp.deciles_vlines_.shape == (1, 3) + assert disp.deciles_hlines_.shape == (1, 3) + + assert disp.lines_[0, 2] is None + assert disp.contours_[0, 0] is None + assert disp.contours_[0, 1] is None + + # deciles lines: always show on xaxis, only show on yaxis if 2-way PDP + for i in range(3): + assert disp.deciles_vlines_[0, i] is not None + assert disp.deciles_hlines_[0, 0] is None + assert disp.deciles_hlines_[0, 1] is None + assert disp.deciles_hlines_[0, 2] is not None + + assert disp.features == [(0,), (2,), (0, 2)] + assert np.all(disp.feature_names == feature_names) + assert len(disp.deciles) == 2 + for i in [0, 2]: + assert_allclose( + disp.deciles[i], + mquantiles(diabetes.data[:, i], prob=np.arange(0.1, 1.0, 0.1)), + ) + + single_feature_positions = [(0, (0, 0)), (2, (0, 1))] + expected_ylabels = ["Partial dependence", ""] + + for i, (feat_col, pos) in enumerate(single_feature_positions): + ax = disp.axes_[pos] + assert ax.get_ylabel() == expected_ylabels[i] + assert ax.get_xlabel() == diabetes.feature_names[feat_col] + + line = disp.lines_[pos] + + avg_preds = disp.pd_results[i] + assert avg_preds.average.shape == (1, grid_resolution) + target_idx = disp.target_idx + + line_data = line.get_data() + assert_allclose(line_data[0], avg_preds["grid_values"][0]) + assert_allclose(line_data[1], avg_preds.average[target_idx].ravel()) + + # two feature position + ax = disp.axes_[0, 2] + coutour = disp.contours_[0, 2] + assert coutour.get_cmap().name == "jet" + assert ax.get_xlabel() == diabetes.feature_names[0] + assert ax.get_ylabel() == diabetes.feature_names[2] + + +@pytest.mark.parametrize( + "kind, centered, subsample, shape", + [ + ("average", False, None, (1, 3)), + ("individual", False, None, (1, 3, 50)), + ("both", False, None, (1, 3, 51)), + ("individual", False, 20, (1, 3, 20)), + ("both", False, 20, (1, 3, 21)), + ("individual", False, 0.5, (1, 3, 25)), + ("both", False, 0.5, (1, 3, 26)), + ("average", True, None, (1, 3)), + ("individual", True, None, (1, 3, 50)), + ("both", True, None, (1, 3, 51)), + ("individual", True, 20, (1, 3, 20)), + ("both", True, 20, (1, 3, 21)), + ], +) +def test_plot_partial_dependence_kind( + pyplot, + kind, + centered, + subsample, + shape, + clf_diabetes, + diabetes, +): + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1, 2], + kind=kind, + centered=centered, + subsample=subsample, + ) + + assert disp.axes_.shape == (1, 3) + assert disp.lines_.shape == shape + assert disp.contours_.shape == (1, 3) + + assert disp.contours_[0, 0] is None + assert disp.contours_[0, 1] is None + assert disp.contours_[0, 2] is None + + if centered: + assert all([ln._y[0] == 0.0 for ln in disp.lines_.ravel() if ln is not None]) + else: + assert all([ln._y[0] != 0.0 for ln in disp.lines_.ravel() if ln is not None]) + + +@pytest.mark.parametrize( + "input_type, feature_names_type", + [ + ("dataframe", None), + ("dataframe", "list"), + ("list", "list"), + ("array", "list"), + ("dataframe", "array"), + ("list", "array"), + ("array", "array"), + ("dataframe", "series"), + ("list", "series"), + ("array", "series"), + ("dataframe", "index"), + ("list", "index"), + ("array", "index"), + ], +) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_str_features( + pyplot, + use_custom_values, + clf_diabetes, + diabetes, + input_type, + feature_names_type, +): + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + + if input_type == "dataframe": + pd = pytest.importorskip("pandas") + X = pd.DataFrame(diabetes.data, columns=diabetes.feature_names) + elif input_type == "list": + X = diabetes.data.tolist() + else: + X = diabetes.data + + if feature_names_type is None: + feature_names = None + else: + feature_names = _convert_container(diabetes.feature_names, feature_names_type) + + grid_resolution = 25 + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + # check with str features and array feature names and single column + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + X, + [("age", "bmi"), "bmi"], + grid_resolution=grid_resolution, + feature_names=feature_names, + n_cols=1, + line_kw={"alpha": 0.8}, + custom_values=custom_values, + ) + fig = pyplot.gcf() + axs = fig.get_axes() + assert len(axs) == 3 + + assert disp.figure_ is fig + assert disp.axes_.shape == (2, 1) + assert disp.lines_.shape == (2, 1) + assert disp.contours_.shape == (2, 1) + assert disp.deciles_vlines_.shape == (2, 1) + assert disp.deciles_hlines_.shape == (2, 1) + + assert disp.lines_[0, 0] is None + assert disp.deciles_vlines_[0, 0] is not None + assert disp.deciles_hlines_[0, 0] is not None + assert disp.contours_[1, 0] is None + assert disp.deciles_hlines_[1, 0] is None + assert disp.deciles_vlines_[1, 0] is not None + + # line + ax = disp.axes_[1, 0] + assert ax.get_xlabel() == "bmi" + assert ax.get_ylabel() == "Partial dependence" + + line = disp.lines_[1, 0] + avg_preds = disp.pd_results[1] + target_idx = disp.target_idx + assert line.get_alpha() == 0.8 + + line_data = line.get_data() + assert_allclose(line_data[0], avg_preds["grid_values"][0]) + assert_allclose(line_data[1], avg_preds.average[target_idx].ravel()) + + # contour + ax = disp.axes_[0, 0] + assert ax.get_xlabel() == "age" + assert ax.get_ylabel() == "bmi" + + +@pytest.mark.filterwarnings("ignore:A Bunch will be returned") +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_custom_axes( + use_custom_values, pyplot, clf_diabetes, diabetes +): + grid_resolution = 25 + fig, (ax1, ax2) = pyplot.subplots(1, 2) + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", ("age", "bmi")], + grid_resolution=grid_resolution, + feature_names=diabetes.feature_names, + ax=[ax1, ax2], + custom_values=custom_values, + ) + assert fig is disp.figure_ + assert disp.bounding_ax_ is None + assert disp.axes_.shape == (2,) + assert disp.axes_[0] is ax1 + assert disp.axes_[1] is ax2 + + ax = disp.axes_[0] + assert ax.get_xlabel() == "age" + assert ax.get_ylabel() == "Partial dependence" + + line = disp.lines_[0] + avg_preds = disp.pd_results[0] + target_idx = disp.target_idx + + line_data = line.get_data() + assert_allclose(line_data[0], avg_preds["grid_values"][0]) + assert_allclose(line_data[1], avg_preds.average[target_idx].ravel()) + + # contour + ax = disp.axes_[1] + assert ax.get_xlabel() == "age" + assert ax.get_ylabel() == "bmi" + + +@pytest.mark.parametrize( + "kind, lines", [("average", 1), ("individual", 50), ("both", 51)] +) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_passing_numpy_axes( + pyplot, + clf_diabetes, + diabetes, + use_custom_values, + kind, + lines, +): + grid_resolution = 25 + feature_names = diabetes.feature_names + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + disp1 = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + kind=kind, + grid_resolution=grid_resolution, + feature_names=feature_names, + custom_values=custom_values, + ) + assert disp1.axes_.shape == (1, 2) + assert disp1.axes_[0, 0].get_ylabel() == "Partial dependence" + assert disp1.axes_[0, 1].get_ylabel() == "" + assert len(disp1.axes_[0, 0].get_lines()) == lines + assert len(disp1.axes_[0, 1].get_lines()) == lines + + lr = LinearRegression() + lr.fit(diabetes.data, diabetes.target) + + disp2 = PartialDependenceDisplay.from_estimator( + lr, + diabetes.data, + ["age", "bmi"], + kind=kind, + grid_resolution=grid_resolution, + feature_names=feature_names, + ax=disp1.axes_, + ) + + assert np.all(disp1.axes_ == disp2.axes_) + assert len(disp2.axes_[0, 0].get_lines()) == 2 * lines + assert len(disp2.axes_[0, 1].get_lines()) == 2 * lines + + +@pytest.mark.parametrize("nrows, ncols", [(2, 2), (3, 1)]) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_incorrent_num_axes( + pyplot, + clf_diabetes, + diabetes, + use_custom_values, + nrows, + ncols, +): + grid_resolution = 5 + fig, axes = pyplot.subplots(nrows, ncols) + axes_formats = [list(axes.ravel()), tuple(axes.ravel()), axes] + + msg = "Expected ax to have 2 axes, got {}".format(nrows * ncols) + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + grid_resolution=grid_resolution, + feature_names=diabetes.feature_names, + custom_values=custom_values, + ) + + for ax_format in axes_formats: + with pytest.raises(ValueError, match=msg): + PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + grid_resolution=grid_resolution, + feature_names=diabetes.feature_names, + ax=ax_format, + custom_values=custom_values, + ) + + # with axes object + with pytest.raises(ValueError, match=msg): + disp.plot(ax=ax_format) + + +@pytest.mark.filterwarnings("ignore:A Bunch will be returned") +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_with_same_axes( + use_custom_values, pyplot, clf_diabetes, diabetes +): + # The first call to plot_partial_dependence will create two new axes to + # place in the space of the passed in axes, which results in a total of + # three axes in the figure. + # Currently the API does not allow for the second call to + # plot_partial_dependence to use the same axes again, because it will + # create two new axes in the space resulting in five axes. To get the + # expected behavior one needs to pass the generated axes into the second + # call: + # disp1 = plot_partial_dependence(...) + # disp2 = plot_partial_dependence(..., ax=disp1.axes_) + + grid_resolution = 25 + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + fig, ax = pyplot.subplots() + PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + grid_resolution=grid_resolution, + feature_names=diabetes.feature_names, + ax=ax, + custom_values=custom_values, + ) + + msg = ( + "The ax was already used in another plot function, please set " + "ax=display.axes_ instead" + ) + + with pytest.raises(ValueError, match=msg): + PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + grid_resolution=grid_resolution, + feature_names=diabetes.feature_names, + custom_values=custom_values, + ax=ax, + ) + + +@pytest.mark.filterwarnings("ignore:A Bunch will be returned") +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_feature_name_reuse( + use_custom_values, pyplot, clf_diabetes, diabetes +): + # second call to plot does not change the feature names from the first + # call + grid_resolution = 10 + + custom_values = None + if use_custom_values: + custom_values = { + 0: custom_values_helper(diabetes.data[:, 0], grid_resolution), + 1: custom_values_helper(diabetes.data[:, 1], grid_resolution), + } + + feature_names = diabetes.feature_names + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1], + grid_resolution=grid_resolution, + feature_names=feature_names, + custom_values=custom_values, + ) + + PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1], + grid_resolution=grid_resolution, + ax=disp.axes_, + custom_values=custom_values, + ) + + for i, ax in enumerate(disp.axes_.ravel()): + assert ax.get_xlabel() == feature_names[i] + + +@pytest.mark.filterwarnings("ignore:A Bunch will be returned") +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_multiclass(use_custom_values, pyplot): + grid_resolution = 25 + clf_int = GradientBoostingClassifier(n_estimators=10, random_state=1) + iris = load_iris() + + custom_values = None + if use_custom_values: + custom_values = { + 0: custom_values_helper(iris.data[:, 0], grid_resolution), + 1: custom_values_helper(iris.data[:, 1], grid_resolution), + } + + # Test partial dependence plot function on multi-class input. + clf_int.fit(iris.data, iris.target) + + disp_target_0 = PartialDependenceDisplay.from_estimator( + clf_int, + iris.data, + [0, 1], + target=0, + grid_resolution=grid_resolution, + custom_values=custom_values, + ) + assert disp_target_0.figure_ is pyplot.gcf() + assert disp_target_0.axes_.shape == (1, 2) + assert disp_target_0.lines_.shape == (1, 2) + assert disp_target_0.contours_.shape == (1, 2) + assert disp_target_0.deciles_vlines_.shape == (1, 2) + assert disp_target_0.deciles_hlines_.shape == (1, 2) + assert all(c is None for c in disp_target_0.contours_.flat) + assert disp_target_0.target_idx == 0 + + # now with symbol labels + target = iris.target_names[iris.target] + clf_symbol = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf_symbol.fit(iris.data, target) + + disp_symbol = PartialDependenceDisplay.from_estimator( + clf_symbol, + iris.data, + [0, 1], + target="setosa", + grid_resolution=grid_resolution, + custom_values=custom_values, + ) + assert disp_symbol.figure_ is pyplot.gcf() + assert disp_symbol.axes_.shape == (1, 2) + assert disp_symbol.lines_.shape == (1, 2) + assert disp_symbol.contours_.shape == (1, 2) + assert disp_symbol.deciles_vlines_.shape == (1, 2) + assert disp_symbol.deciles_hlines_.shape == (1, 2) + assert all(c is None for c in disp_symbol.contours_.flat) + assert disp_symbol.target_idx == 0 + + for int_result, symbol_result in zip( + disp_target_0.pd_results, disp_symbol.pd_results + ): + assert_allclose(int_result.average, symbol_result.average) + assert_allclose(int_result["grid_values"], symbol_result["grid_values"]) + + # check that the pd plots are different for another target + + disp_target_1 = PartialDependenceDisplay.from_estimator( + clf_int, + iris.data, + [0, 3], + target=1, + grid_resolution=grid_resolution, + custom_values=custom_values, + ) + target_0_data_y = disp_target_0.lines_[0, 0].get_data()[1] + target_1_data_y = disp_target_1.lines_[0, 0].get_data()[1] + assert any(target_0_data_y != target_1_data_y) + + +multioutput_regression_data = make_regression(n_samples=50, n_targets=2, random_state=0) + + +@pytest.mark.parametrize("target", [0, 1]) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_multioutput(use_custom_values, pyplot, target): + # Test partial dependence plot function on multi-output input. + X, y = multioutput_regression_data + clf = LinearRegression().fit(X, y) + + grid_resolution = 25 + + custom_values = None + if use_custom_values: + custom_values = { + 0: custom_values_helper(X[:, 0], grid_resolution), + 1: custom_values_helper(X[:, 1], grid_resolution), + } + + disp = PartialDependenceDisplay.from_estimator( + clf, + X, + [0, 1], + target=target, + grid_resolution=grid_resolution, + custom_values=custom_values, + ) + fig = pyplot.gcf() + axs = fig.get_axes() + assert len(axs) == 3 + assert disp.target_idx == target + assert disp.bounding_ax_ is not None + + positions = [(0, 0), (0, 1)] + expected_label = ["Partial dependence", ""] + + for i, pos in enumerate(positions): + ax = disp.axes_[pos] + assert ax.get_ylabel() == expected_label[i] + assert ax.get_xlabel() == f"x{i}" + + +def test_plot_partial_dependence_dataframe(pyplot, clf_diabetes, diabetes): + pd = pytest.importorskip("pandas") + df = pd.DataFrame(diabetes.data, columns=diabetes.feature_names) + + grid_resolution = 25 + + PartialDependenceDisplay.from_estimator( + clf_diabetes, + df, + ["bp", "s1"], + grid_resolution=grid_resolution, + feature_names=df.columns.tolist(), + ) + + +dummy_classification_data = make_classification(random_state=0) + + +@pytest.mark.parametrize( + "data, params, err_msg", + [ + ( + multioutput_regression_data, + {"target": None, "features": [0]}, + "target must be specified for multi-output", + ), + ( + multioutput_regression_data, + {"target": -1, "features": [0]}, + r"target must be in \[0, n_tasks\]", + ), + ( + multioutput_regression_data, + {"target": 100, "features": [0]}, + r"target must be in \[0, n_tasks\]", + ), + ( + dummy_classification_data, + {"features": ["foobar"], "feature_names": None}, + "Feature 'foobar' not in feature_names", + ), + ( + dummy_classification_data, + {"features": ["foobar"], "feature_names": ["abcd", "def"]}, + "Feature 'foobar' not in feature_names", + ), + ( + dummy_classification_data, + {"features": [(1, 2, 3)]}, + "Each entry in features must be either an int, ", + ), + ( + dummy_classification_data, + {"features": [1, {}]}, + "Each entry in features must be either an int, ", + ), + ( + dummy_classification_data, + {"features": [tuple()]}, + "Each entry in features must be either an int, ", + ), + ( + dummy_classification_data, + {"features": [123], "feature_names": ["blahblah"]}, + "All entries of features must be less than ", + ), + ( + dummy_classification_data, + {"features": [0, 1, 2], "feature_names": ["a", "b", "a"]}, + "feature_names should not contain duplicates", + ), + ( + dummy_classification_data, + {"features": [1, 2], "kind": ["both"]}, + "When `kind` is provided as a list of strings, it should contain", + ), + ( + dummy_classification_data, + {"features": [1], "subsample": -1}, + "When an integer, subsample=-1 should be positive.", + ), + ( + dummy_classification_data, + {"features": [1], "subsample": 1.2}, + r"When a floating-point, subsample=1.2 should be in the \(0, 1\) range", + ), + ( + dummy_classification_data, + {"features": [1, 2], "categorical_features": [1.0, 2.0]}, + "Expected `categorical_features` to be an array-like of boolean,", + ), + ( + dummy_classification_data, + {"features": [(1, 2)], "categorical_features": [2]}, + "Two-way partial dependence plots are not supported for pairs", + ), + ( + dummy_classification_data, + {"features": [1], "categorical_features": [1], "kind": "individual"}, + "It is not possible to display individual effects", + ), + ], +) +def test_plot_partial_dependence_error(pyplot, data, params, err_msg): + X, y = data + estimator = LinearRegression().fit(X, y) + + with pytest.raises(ValueError, match=err_msg): + PartialDependenceDisplay.from_estimator(estimator, X, **params) + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ({"target": 4, "features": [0]}, "target not in est.classes_, got 4"), + ({"target": None, "features": [0]}, "target must be specified for multi-class"), + ( + {"target": 1, "features": [4.5]}, + "Each entry in features must be either an int,", + ), + ], +) +def test_plot_partial_dependence_multiclass_error(pyplot, params, err_msg): + iris = load_iris() + clf = GradientBoostingClassifier(n_estimators=10, random_state=1) + clf.fit(iris.data, iris.target) + + with pytest.raises(ValueError, match=err_msg): + PartialDependenceDisplay.from_estimator(clf, iris.data, **params) + + +def test_plot_partial_dependence_does_not_override_ylabel( + pyplot, clf_diabetes, diabetes +): + # Non-regression test to be sure to not override the ylabel if it has been + # See https://github.com/scikit-learn/scikit-learn/issues/15772 + _, axes = pyplot.subplots(1, 2) + axes[0].set_ylabel("Hello world") + PartialDependenceDisplay.from_estimator( + clf_diabetes, diabetes.data, [0, 1], ax=axes + ) + + assert axes[0].get_ylabel() == "Hello world" + assert axes[1].get_ylabel() == "Partial dependence" + + +@pytest.mark.parametrize( + "categorical_features, array_type", + [ + (["col_A", "col_C"], "dataframe"), + ([0, 2], "array"), + ([True, False, True], "array"), + ], +) +def test_plot_partial_dependence_with_categorical( + pyplot, categorical_features, array_type +): + X = [[1, 1, "A"], [2, 0, "C"], [3, 2, "B"]] + column_name = ["col_A", "col_B", "col_C"] + X = _convert_container(X, array_type, columns_name=column_name) + y = np.array([1.2, 0.5, 0.45]).T + + preprocessor = make_column_transformer((OneHotEncoder(), categorical_features)) + model = make_pipeline(preprocessor, LinearRegression()) + model.fit(X, y) + + # single feature + disp = PartialDependenceDisplay.from_estimator( + model, + X, + features=["col_C"], + feature_names=column_name, + categorical_features=categorical_features, + ) + + assert disp.figure_ is pyplot.gcf() + assert disp.bars_.shape == (1, 1) + assert disp.bars_[0][0] is not None + assert disp.lines_.shape == (1, 1) + assert disp.lines_[0][0] is None + assert disp.contours_.shape == (1, 1) + assert disp.contours_[0][0] is None + assert disp.deciles_vlines_.shape == (1, 1) + assert disp.deciles_vlines_[0][0] is None + assert disp.deciles_hlines_.shape == (1, 1) + assert disp.deciles_hlines_[0][0] is None + assert disp.axes_[0, 0].get_legend() is None + + # interaction between two features + disp = PartialDependenceDisplay.from_estimator( + model, + X, + features=[("col_A", "col_C")], + feature_names=column_name, + categorical_features=categorical_features, + ) + + assert disp.figure_ is pyplot.gcf() + assert disp.bars_.shape == (1, 1) + assert disp.bars_[0][0] is None + assert disp.lines_.shape == (1, 1) + assert disp.lines_[0][0] is None + assert disp.contours_.shape == (1, 1) + assert disp.contours_[0][0] is None + assert disp.deciles_vlines_.shape == (1, 1) + assert disp.deciles_vlines_[0][0] is None + assert disp.deciles_hlines_.shape == (1, 1) + assert disp.deciles_hlines_[0][0] is None + assert disp.axes_[0, 0].get_legend() is None + + +def test_plot_partial_dependence_legend(pyplot): + pd = pytest.importorskip("pandas") + X = pd.DataFrame( + { + "col_A": ["A", "B", "C"], + "col_B": [1.0, 0.0, 2.0], + "col_C": ["C", "B", "A"], + } + ) + y = np.array([1.2, 0.5, 0.45]).T + + categorical_features = ["col_A", "col_C"] + preprocessor = make_column_transformer((OneHotEncoder(), categorical_features)) + model = make_pipeline(preprocessor, LinearRegression()) + model.fit(X, y) + + disp = PartialDependenceDisplay.from_estimator( + model, + X, + features=["col_B", "col_C"], + categorical_features=categorical_features, + kind=["both", "average"], + ) + + legend_text = disp.axes_[0, 0].get_legend().get_texts() + assert len(legend_text) == 1 + assert legend_text[0].get_text() == "average" + assert disp.axes_[0, 1].get_legend() is None + + +@pytest.mark.parametrize( + "kind, expected_shape", + [("average", (1, 2)), ("individual", (1, 2, 20)), ("both", (1, 2, 21))], +) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_plot_partial_dependence_subsampling( + pyplot, + clf_diabetes, + diabetes, + use_custom_values, + kind, + expected_shape, +): + # check that the subsampling is properly working + # non-regression test for: + # https://github.com/scikit-learn/scikit-learn/pull/18359 + matplotlib = pytest.importorskip("matplotlib") + grid_resolution = 25 + feature_names = diabetes.feature_names + + age = diabetes.data[:, diabetes.feature_names.index("age")] + bmi = diabetes.data[:, diabetes.feature_names.index("bmi")] + + custom_values = None + if use_custom_values: + custom_values = { + "age": custom_values_helper(age, grid_resolution), + "bmi": custom_values_helper(bmi, grid_resolution), + } + + disp1 = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + ["age", "bmi"], + kind=kind, + grid_resolution=grid_resolution, + feature_names=feature_names, + subsample=20, + random_state=0, + custom_values=custom_values, + ) + + assert disp1.lines_.shape == expected_shape + assert all( + [isinstance(line, matplotlib.lines.Line2D) for line in disp1.lines_.ravel()] + ) + + +@pytest.mark.parametrize( + "kind, line_kw, label", + [ + ("individual", {}, None), + ("individual", {"label": "xxx"}, None), + ("average", {}, None), + ("average", {"label": "xxx"}, "xxx"), + ("both", {}, "average"), + ("both", {"label": "xxx"}, "xxx"), + ], +) +def test_partial_dependence_overwrite_labels( + pyplot, + clf_diabetes, + diabetes, + kind, + line_kw, + label, +): + """Test that make sure that we can overwrite the label of the PDP plot""" + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 2], + grid_resolution=25, + feature_names=diabetes.feature_names, + kind=kind, + line_kw=line_kw, + ) + + for ax in disp.axes_.ravel(): + if label is None: + assert ax.get_legend() is None + else: + legend_text = ax.get_legend().get_texts() + assert len(legend_text) == 1 + assert legend_text[0].get_text() == label + + +@pytest.mark.parametrize( + "categorical_features, array_type", + [ + (["col_A", "col_C"], "dataframe"), + ([0, 2], "array"), + ([True, False, True], "array"), + ], +) +def test_grid_resolution_with_categorical(pyplot, categorical_features, array_type): + """Check that we raise a ValueError when the grid_resolution is too small + respect to the number of categories in the categorical features targeted. + """ + X = [["A", 1, "A"], ["B", 0, "C"], ["C", 2, "B"]] + column_name = ["col_A", "col_B", "col_C"] + X = _convert_container(X, array_type, columns_name=column_name) + y = np.array([1.2, 0.5, 0.45]).T + + preprocessor = make_column_transformer((OneHotEncoder(), categorical_features)) + model = make_pipeline(preprocessor, LinearRegression()) + model.fit(X, y) + + err_msg = ( + "resolution of the computed grid is less than the minimum number of categories" + ) + with pytest.raises(ValueError, match=err_msg): + PartialDependenceDisplay.from_estimator( + model, + X, + features=["col_C"], + feature_names=column_name, + categorical_features=categorical_features, + grid_resolution=2, + ) + + +@pytest.mark.parametrize("kind", ["individual", "average", "both"]) +@pytest.mark.parametrize("centered", [True, False]) +def test_partial_dependence_plot_limits_one_way( + pyplot, clf_diabetes, diabetes, kind, centered +): + """Check that the PD limit on the plots are properly set on one-way plots.""" + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + features=(0, 1), + kind=kind, + grid_resolution=25, + feature_names=diabetes.feature_names, + ) + + range_pd = np.array([-1, 1], dtype=np.float64) + for pd in disp.pd_results: + if "average" in pd: + pd["average"][...] = range_pd[1] + pd["average"][0, 0] = range_pd[0] + if "individual" in pd: + pd["individual"][...] = range_pd[1] + pd["individual"][0, 0, 0] = range_pd[0] + + disp.plot(centered=centered) + # check that we anchor to zero x-axis when centering + y_lim = range_pd - range_pd[0] if centered else range_pd + padding = 0.05 * (y_lim[1] - y_lim[0]) + y_lim[0] -= padding + y_lim[1] += padding + for ax in disp.axes_.ravel(): + assert_allclose(ax.get_ylim(), y_lim) + + +@pytest.mark.parametrize("centered", [True, False]) +def test_partial_dependence_plot_limits_two_way( + pyplot, clf_diabetes, diabetes, centered +): + """Check that the PD limit on the plots are properly set on two-way plots.""" + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + features=[(0, 1)], + kind="average", + grid_resolution=25, + feature_names=diabetes.feature_names, + ) + + range_pd = np.array([-1, 1], dtype=np.float64) + for pd in disp.pd_results: + pd["average"][...] = range_pd[1] + pd["average"][0, 0] = range_pd[0] + + disp.plot(centered=centered) + contours = disp.contours_[0, 0] + levels = range_pd - range_pd[0] if centered else range_pd + + padding = 0.05 * (levels[1] - levels[0]) + levels[0] -= padding + levels[1] += padding + expect_levels = np.linspace(*levels, num=8) + assert_allclose(contours.levels, expect_levels) + + +def test_partial_dependence_kind_list( + pyplot, + clf_diabetes, + diabetes, +): + """Check that we can provide a list of strings to kind parameter.""" + matplotlib = pytest.importorskip("matplotlib") + + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + features=[0, 2, (1, 2)], + grid_resolution=20, + kind=["both", "both", "average"], + ) + + for idx in [0, 1]: + assert all( + [ + isinstance(line, matplotlib.lines.Line2D) + for line in disp.lines_[0, idx].ravel() + ] + ) + assert disp.contours_[0, idx] is None + + assert disp.contours_[0, 2] is not None + assert all([line is None for line in disp.lines_[0, 2].ravel()]) + + +@pytest.mark.parametrize( + "features, kind", + [ + ([0, 2, (1, 2)], "individual"), + ([0, 2, (1, 2)], "both"), + ([(0, 1), (0, 2), (1, 2)], "individual"), + ([(0, 1), (0, 2), (1, 2)], "both"), + ([0, 2, (1, 2)], ["individual", "individual", "individual"]), + ([0, 2, (1, 2)], ["both", "both", "both"]), + ], +) +def test_partial_dependence_kind_error( + pyplot, + clf_diabetes, + diabetes, + features, + kind, +): + """Check that we raise an informative error when 2-way PD is requested + together with 1-way PD/ICE""" + warn_msg = ( + "ICE plot cannot be rendered for 2-way feature interactions. 2-way " + "feature interactions mandates PD plots using the 'average' kind" + ) + with pytest.raises(ValueError, match=warn_msg): + PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + features=features, + grid_resolution=20, + kind=kind, + ) + + +@pytest.mark.parametrize( + "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")), + ({"c": "r"}, None, None, ("r", "r")), + ({"c": "r", "ls": "-."}, {"color": "g"}, {"color": "b"}, ("g", "b")), + ({"c": "r"}, {"c": "g"}, {"c": "b"}, ("g", "b")), + ({"c": "r"}, {"ls": "--"}, {"ls": "-."}, ("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 = PartialDependenceDisplay.from_estimator( + 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], ( + f"{line.get_color()}!={expected_colors[0]}\n{line_kw} and {pd_line_kw}" + ) + if pd_line_kw is not None: + if "linestyle" in pd_line_kw: + assert line.get_linestyle() == pd_line_kw["linestyle"] + elif "ls" in pd_line_kw: + assert line.get_linestyle() == pd_line_kw["ls"] + else: + assert line.get_linestyle() == "--" + + line = disp.lines_[0, 0, 0] + assert line.get_color() == expected_colors[1], ( + f"{line.get_color()}!={expected_colors[1]}" + ) + if ice_lines_kw is not None: + if "linestyle" in ice_lines_kw: + assert line.get_linestyle() == ice_lines_kw["linestyle"] + elif "ls" in ice_lines_kw: + assert line.get_linestyle() == ice_lines_kw["ls"] + else: + assert line.get_linestyle() == "-" + + +def test_partial_dependence_display_wrong_len_kind( + pyplot, + clf_diabetes, + diabetes, +): + """Check that we raise an error when `kind` is a list with a wrong length. + + This case can only be triggered using the `PartialDependenceDisplay.from_estimator` + method. + """ + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + features=[0, 2], + grid_resolution=20, + kind="average", # len(kind) != len(features) + ) + + # alter `kind` to be a list with a length different from length of `features` + disp.kind = ["average"] + err_msg = ( + r"When `kind` is provided as a list of strings, it should contain as many" + r" elements as `features`. `kind` contains 1 element\(s\) and `features`" + r" contains 2 element\(s\)." + ) + with pytest.raises(ValueError, match=err_msg): + disp.plot() + + +@pytest.mark.parametrize( + "kind", + ["individual", "both", "average", ["average", "both"], ["individual", "both"]], +) +def test_partial_dependence_display_kind_centered_interaction( + pyplot, + kind, + clf_diabetes, + diabetes, +): + """Check that we properly center ICE and PD when passing kind as a string and as a + list.""" + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1], + kind=kind, + centered=True, + subsample=5, + ) + + assert all([ln._y[0] == 0.0 for ln in disp.lines_.ravel() if ln is not None]) + + +def test_partial_dependence_display_with_constant_sample_weight( + pyplot, + clf_diabetes, + diabetes, +): + """Check that the utilization of a constant sample weight maintains the + standard behavior. + """ + disp = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1], + kind="average", + method="brute", + ) + + sample_weight = np.ones_like(diabetes.target) + disp_sw = PartialDependenceDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 1], + sample_weight=sample_weight, + kind="average", + method="brute", + ) + + assert np.array_equal( + disp.pd_results[0]["average"], disp_sw.pd_results[0]["average"] + ) + + +def test_subclass_named_constructors_return_type_is_subclass( + pyplot, diabetes, clf_diabetes +): + """Check that named constructors return the correct type when subclassed. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/27675 + """ + + class SubclassOfDisplay(PartialDependenceDisplay): + pass + + curve = SubclassOfDisplay.from_estimator( + clf_diabetes, + diabetes.data, + [0, 2, (0, 2)], + ) + + assert isinstance(curve, SubclassOfDisplay) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_partial_dependence.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_partial_dependence.py new file mode 100644 index 0000000000000000000000000000000000000000..816fe5512edc4a142380c3d84bc59a030e1168ff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_partial_dependence.py @@ -0,0 +1,1217 @@ +""" +Testing for the partial dependence module. +""" + +import re +import warnings + +import numpy as np +import pytest + +import sklearn +from sklearn.base import BaseEstimator, ClassifierMixin, clone, is_regressor +from sklearn.cluster import KMeans +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_iris, make_classification, make_regression +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import ( + GradientBoostingClassifier, + GradientBoostingRegressor, + HistGradientBoostingClassifier, + HistGradientBoostingRegressor, + RandomForestRegressor, +) +from sklearn.exceptions import NotFittedError +from sklearn.impute import SimpleImputer +from sklearn.inspection import partial_dependence +from sklearn.inspection._partial_dependence import ( + _grid_from_X, + _partial_dependence_brute, + _partial_dependence_recursion, +) +from sklearn.linear_model import LinearRegression, LogisticRegression, MultiTaskLasso +from sklearn.metrics import r2_score +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import ( + OneHotEncoder, + PolynomialFeatures, + RobustScaler, + StandardScaler, + scale, +) +from sklearn.tree import DecisionTreeRegressor +from sklearn.tree.tests.test_tree import assert_is_subtree +from sklearn.utils._testing import assert_allclose, assert_array_equal +from sklearn.utils.fixes import _IS_32BIT +from sklearn.utils.validation import check_random_state + +# toy sample +X = [[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]] +y = [-1, -1, -1, 1, 1, 1] + + +# (X, y), n_targets <-- as expected in the output of partial_dep() +binary_classification_data = (make_classification(n_samples=50, random_state=0), 1) +multiclass_classification_data = ( + make_classification( + n_samples=50, n_classes=3, n_clusters_per_class=1, random_state=0 + ), + 3, +) +regression_data = (make_regression(n_samples=50, random_state=0), 1) +multioutput_regression_data = ( + make_regression(n_samples=50, n_targets=2, random_state=0), + 2, +) + +# iris +iris = load_iris() + + +@pytest.mark.parametrize( + "Estimator, method, data", + [ + (GradientBoostingClassifier, "auto", binary_classification_data), + (GradientBoostingClassifier, "auto", multiclass_classification_data), + (GradientBoostingClassifier, "brute", binary_classification_data), + (GradientBoostingClassifier, "brute", multiclass_classification_data), + (GradientBoostingRegressor, "auto", regression_data), + (GradientBoostingRegressor, "brute", regression_data), + (DecisionTreeRegressor, "brute", regression_data), + (LinearRegression, "brute", regression_data), + (LinearRegression, "brute", multioutput_regression_data), + (LogisticRegression, "brute", binary_classification_data), + (LogisticRegression, "brute", multiclass_classification_data), + (MultiTaskLasso, "brute", multioutput_regression_data), + ], +) +@pytest.mark.parametrize("grid_resolution", (5, 10)) +@pytest.mark.parametrize("features", ([1], [1, 2])) +@pytest.mark.parametrize("kind", ("average", "individual", "both")) +@pytest.mark.parametrize("use_custom_values", [True, False]) +def test_output_shape( + Estimator, method, data, grid_resolution, features, kind, use_custom_values +): + # Check that partial_dependence has consistent output shape for different + # kinds of estimators: + # - classifiers with binary and multiclass settings + # - regressors + # - multi-task regressors + + est = Estimator() + if hasattr(est, "n_estimators"): + est.set_params(n_estimators=2) # speed-up computations + + # n_target corresponds to the number of classes (1 for binary classif) or + # the number of tasks / outputs in multi task settings. It's equal to 1 for + # classical regression_data. + (X, y), n_targets = data + n_instances = X.shape[0] + + custom_values = None + if use_custom_values: + grid_resolution = 5 + custom_values = {f: X[:grid_resolution, f] for f in features} + + est.fit(X, y) + result = partial_dependence( + est, + X=X, + features=features, + method=method, + kind=kind, + grid_resolution=grid_resolution, + custom_values=custom_values, + ) + pdp, axes = result, result["grid_values"] + + expected_pdp_shape = (n_targets, *[grid_resolution for _ in range(len(features))]) + expected_ice_shape = ( + n_targets, + n_instances, + *[grid_resolution for _ in range(len(features))], + ) + if kind == "average": + assert pdp.average.shape == expected_pdp_shape + elif kind == "individual": + assert pdp.individual.shape == expected_ice_shape + else: # 'both' + assert pdp.average.shape == expected_pdp_shape + assert pdp.individual.shape == expected_ice_shape + + expected_axes_shape = (len(features), grid_resolution) + assert axes is not None + assert np.asarray(axes).shape == expected_axes_shape + + +def test_grid_from_X(): + # tests for _grid_from_X: sanity check for output, and for shapes. + + # Make sure that the grid is a cartesian product of the input (it will use + # the unique values instead of the percentiles) + percentiles = (0.05, 0.95) + grid_resolution = 100 + is_categorical = [False, False] + X = np.asarray([[1, 2], [3, 4]]) + grid, axes = _grid_from_X(X, percentiles, is_categorical, grid_resolution, {}) + assert_array_equal(grid, [[1, 2], [1, 4], [3, 2], [3, 4]]) + assert_array_equal(axes, X.T) + + # test shapes of returned objects depending on the number of unique values + # for a feature. + rng = np.random.RandomState(0) + grid_resolution = 15 + + # n_unique_values > grid_resolution + X = rng.normal(size=(20, 2)) + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical, + grid_resolution=grid_resolution, + custom_values={}, + ) + assert grid.shape == (grid_resolution * grid_resolution, X.shape[1]) + assert np.asarray(axes).shape == (2, grid_resolution) + assert grid.dtype == X.dtype + + # n_unique_values < grid_resolution, will use actual values + n_unique_values = 12 + X[n_unique_values - 1 :, 0] = 12345 + rng.shuffle(X) # just to make sure the order is irrelevant + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical, + grid_resolution=grid_resolution, + custom_values={}, + ) + assert grid.shape == (n_unique_values * grid_resolution, X.shape[1]) + # axes is a list of arrays of different shapes + assert axes[0].shape == (n_unique_values,) + assert axes[1].shape == (grid_resolution,) + assert grid.dtype == X.dtype + + # Check that uses custom_range + X = rng.normal(size=(20, 2)) + X[n_unique_values - 1 :, 0] = 12345 + col_1_range = [0, 2, 3] + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical=is_categorical, + grid_resolution=grid_resolution, + custom_values={1: col_1_range}, + ) + assert grid.shape == (n_unique_values * len(col_1_range), X.shape[1]) + # axes is a list of arrays of different shapes + assert axes[0].shape == (n_unique_values,) + assert axes[1].shape == (len(col_1_range),) + assert grid.dtype == X.dtype + + # Check that grid_resolution does not impact custom_range + X = rng.normal(size=(20, 2)) + col_0_range = [0, 2, 3, 4, 5, 6] + grid_resolution = 5 + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical=is_categorical, + grid_resolution=grid_resolution, + custom_values={0: col_0_range}, + ) + assert grid.shape == (grid_resolution * len(col_0_range), X.shape[1]) + # axes is a list of arrays of different shapes + assert axes[0].shape == (len(col_0_range),) + assert axes[1].shape == (grid_resolution,) + assert grid.dtype == np.result_type(X, np.asarray(col_0_range).dtype) + + X = np.array([[0, "a"], [1, "b"], [2, "c"]]) + + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical=is_categorical, + grid_resolution=grid_resolution, + custom_values={1: ["a", "b", "c"]}, + ) + assert grid.dtype == object + + +@pytest.mark.parametrize( + "grid_resolution", + [ + 2, # since n_categories > 2, we should not use quantiles resampling + 100, + ], +) +def test_grid_from_X_with_categorical(grid_resolution): + """Check that `_grid_from_X` always sample from categories and does not + depend from the percentiles. + """ + pd = pytest.importorskip("pandas") + percentiles = (0.05, 0.95) + is_categorical = [True] + X = pd.DataFrame({"cat_feature": ["A", "B", "C", "A", "B", "D", "E"]}) + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical, + grid_resolution=grid_resolution, + custom_values={}, + ) + assert grid.shape == (5, X.shape[1]) + assert axes[0].shape == (5,) + + +@pytest.mark.parametrize("grid_resolution", [3, 100]) +def test_grid_from_X_heterogeneous_type(grid_resolution): + """Check that `_grid_from_X` always sample from categories and does not + depend from the percentiles. + """ + pd = pytest.importorskip("pandas") + percentiles = (0.05, 0.95) + is_categorical = [True, False] + X = pd.DataFrame( + { + "cat": ["A", "B", "C", "A", "B", "D", "E", "A", "B", "D"], + "num": [1, 1, 1, 2, 5, 6, 6, 6, 6, 8], + } + ) + nunique = X.nunique() + + grid, axes = _grid_from_X( + X, + percentiles, + is_categorical, + grid_resolution=grid_resolution, + custom_values={}, + ) + if grid_resolution == 3: + assert grid.shape == (15, 2) + assert axes[0].shape[0] == nunique["num"] + assert axes[1].shape[0] == grid_resolution + else: + assert grid.shape == (25, 2) + assert axes[0].shape[0] == nunique["cat"] + assert axes[1].shape[0] == nunique["cat"] + + +@pytest.mark.parametrize( + "grid_resolution, percentiles, err_msg", + [ + (2, (0, 0.0001), "percentiles are too close"), + (100, (1, 2, 3, 4), "'percentiles' must be a sequence of 2 elements"), + (100, 12345, "'percentiles' must be a sequence of 2 elements"), + (100, (-1, 0.95), r"'percentiles' values must be in \[0, 1\]"), + (100, (0.05, 2), r"'percentiles' values must be in \[0, 1\]"), + (100, (0.9, 0.1), r"percentiles\[0\] must be strictly less than"), + (1, (0.05, 0.95), "'grid_resolution' must be strictly greater than 1"), + ], +) +def test_grid_from_X_error(grid_resolution, percentiles, err_msg): + X = np.asarray([[1, 2], [3, 4]]) + is_categorical = [False] + with pytest.raises(ValueError, match=err_msg): + _grid_from_X(X, percentiles, is_categorical, grid_resolution, custom_values={}) + + +@pytest.mark.parametrize("target_feature", range(5)) +@pytest.mark.parametrize( + "est, method", + [ + (LinearRegression(), "brute"), + (GradientBoostingRegressor(random_state=0), "brute"), + (GradientBoostingRegressor(random_state=0), "recursion"), + (HistGradientBoostingRegressor(random_state=0), "brute"), + (HistGradientBoostingRegressor(random_state=0), "recursion"), + ], +) +def test_partial_dependence_helpers(est, method, target_feature): + # Check that what is returned by _partial_dependence_brute or + # _partial_dependence_recursion is equivalent to manually setting a target + # feature to a given value, and computing the average prediction over all + # samples. + # This also checks that the brute and recursion methods give the same + # output. + # Note that even on the trainset, the brute and the recursion methods + # aren't always strictly equivalent, in particular when the slow method + # generates unrealistic samples that have low mass in the joint + # distribution of the input features, and when some of the features are + # dependent. Hence the high tolerance on the checks. + + X, y = make_regression(random_state=0, n_features=5, n_informative=5) + # The 'init' estimator for GBDT (here the average prediction) isn't taken + # into account with the recursion method, for technical reasons. We set + # the mean to 0 to that this 'bug' doesn't have any effect. + y = y - y.mean() + + # Clone is necessary to make the test thread-safe. + est = clone(est).fit(X, y) + + # target feature will be set to .5 and then to 123 + features = np.array([target_feature], dtype=np.intp) + grid = np.array([[0.5], [123]]) + + if method == "brute": + pdp, predictions = _partial_dependence_brute( + est, grid, features, X, response_method="auto" + ) + else: + pdp = _partial_dependence_recursion(est, grid, features) + + mean_predictions = [] + for val in (0.5, 123): + X_ = X.copy() + X_[:, target_feature] = val + mean_predictions.append(est.predict(X_).mean()) + + pdp = pdp[0] # (shape is (1, 2) so make it (2,)) + + # allow for greater margin for error with recursion method + rtol = 1e-1 if method == "recursion" else 1e-3 + assert np.allclose(pdp, mean_predictions, rtol=rtol) + + +@pytest.mark.parametrize("seed", range(1)) +def test_recursion_decision_tree_vs_forest_and_gbdt(seed): + # Make sure that the recursion method gives the same results on a + # DecisionTreeRegressor and a GradientBoostingRegressor or a + # RandomForestRegressor with 1 tree and equivalent parameters. + + rng = np.random.RandomState(seed) + + # Purely random dataset to avoid correlated features + n_samples = 1000 + n_features = 5 + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) * 10 + + # The 'init' estimator for GBDT (here the average prediction) isn't taken + # into account with the recursion method, for technical reasons. We set + # the mean to 0 to that this 'bug' doesn't have any effect. + y = y - y.mean() + + # set max_depth not too high to avoid splits with same gain but different + # features + max_depth = 5 + + tree_seed = 0 + forest = RandomForestRegressor( + n_estimators=1, + max_features=None, + bootstrap=False, + max_depth=max_depth, + random_state=tree_seed, + ) + # The forest will use ensemble.base._set_random_states to set the + # random_state of the tree sub-estimator. We simulate this here to have + # equivalent estimators. + equiv_random_state = check_random_state(tree_seed).randint(np.iinfo(np.int32).max) + gbdt = GradientBoostingRegressor( + n_estimators=1, + learning_rate=1, + criterion="squared_error", + max_depth=max_depth, + random_state=equiv_random_state, + ) + tree = DecisionTreeRegressor(max_depth=max_depth, random_state=equiv_random_state) + + forest.fit(X, y) + gbdt.fit(X, y) + tree.fit(X, y) + + # sanity check: if the trees aren't the same, the PD values won't be equal + try: + assert_is_subtree(tree.tree_, gbdt[0, 0].tree_) + assert_is_subtree(tree.tree_, forest[0].tree_) + except AssertionError: + # For some reason the trees aren't exactly equal on 32bits, so the PDs + # cannot be equal either. See + # https://github.com/scikit-learn/scikit-learn/issues/8853 + assert _IS_32BIT, "this should only fail on 32 bit platforms" + return + + grid = rng.randn(50).reshape(-1, 1) + for f in range(n_features): + features = np.array([f], dtype=np.intp) + + pdp_forest = _partial_dependence_recursion(forest, grid, features) + pdp_gbdt = _partial_dependence_recursion(gbdt, grid, features) + pdp_tree = _partial_dependence_recursion(tree, grid, features) + + np.testing.assert_allclose(pdp_gbdt, pdp_tree) + np.testing.assert_allclose(pdp_forest, pdp_tree) + + +@pytest.mark.parametrize( + "est", + ( + GradientBoostingClassifier(random_state=0), + HistGradientBoostingClassifier(random_state=0), + ), +) +@pytest.mark.parametrize("target_feature", (0, 1, 2, 3, 4, 5)) +def test_recursion_decision_function(est, target_feature): + # Make sure the recursion method (implicitly uses decision_function) has + # the same result as using brute method with + # response_method=decision_function + + X, y = make_classification(n_classes=2, n_clusters_per_class=1, random_state=1) + assert np.mean(y) == 0.5 # make sure the init estimator predicts 0 anyway + + est = clone(est).fit(X, y) + + preds_1 = partial_dependence( + est, + X, + [target_feature], + response_method="decision_function", + method="recursion", + kind="average", + ) + preds_2 = partial_dependence( + est, + X, + [target_feature], + response_method="decision_function", + method="brute", + kind="average", + ) + + assert_allclose(preds_1["average"], preds_2["average"], atol=1e-7) + + +@pytest.mark.parametrize( + "est", + ( + LinearRegression(), + GradientBoostingRegressor(random_state=0), + HistGradientBoostingRegressor( + random_state=0, min_samples_leaf=1, max_leaf_nodes=None, max_iter=1 + ), + DecisionTreeRegressor(random_state=0), + ), +) +@pytest.mark.parametrize("power", (1, 2)) +def test_partial_dependence_easy_target(est, power): + # If the target y only depends on one feature in an obvious way (linear or + # quadratic) then the partial dependence for that feature should reflect + # it. + # We here fit a linear regression_data model (with polynomial features if + # needed) and compute r_squared to check that the partial dependence + # correctly reflects the target. + + rng = np.random.RandomState(0) + n_samples = 200 + target_variable = 2 + X = rng.normal(size=(n_samples, 5)) + y = X[:, target_variable] ** power + + est = clone(est).fit(X, y) + + pdp = partial_dependence( + est, features=[target_variable], X=X, grid_resolution=1000, kind="average" + ) + + new_X = pdp["grid_values"][0].reshape(-1, 1) + new_y = pdp["average"][0] + # add polynomial features if needed + new_X = PolynomialFeatures(degree=power).fit_transform(new_X) + + lr = LinearRegression().fit(new_X, new_y) + r2 = r2_score(new_y, lr.predict(new_X)) + + assert r2 > 0.99 + + +@pytest.mark.parametrize( + "Estimator", + ( + sklearn.tree.DecisionTreeClassifier, + sklearn.tree.ExtraTreeClassifier, + sklearn.ensemble.ExtraTreesClassifier, + sklearn.neighbors.KNeighborsClassifier, + sklearn.neighbors.RadiusNeighborsClassifier, + sklearn.ensemble.RandomForestClassifier, + ), +) +def test_multiclass_multioutput(Estimator): + # Make sure error is raised for multiclass-multioutput classifiers + + # make multiclass-multioutput dataset + X, y = make_classification(n_classes=3, n_clusters_per_class=1, random_state=0) + y = np.array([y, y]).T + + est = Estimator() + est.fit(X, y) + + with pytest.raises( + ValueError, match="Multiclass-multioutput estimators are not supported" + ): + partial_dependence(est, X, [0]) + + +class NoPredictProbaNoDecisionFunction(ClassifierMixin, BaseEstimator): + def fit(self, X, y): + # simulate that we have some classes + self.classes_ = [0, 1] + return self + + +@pytest.mark.parametrize( + "estimator, params, err_msg", + [ + ( + KMeans(random_state=0, n_init="auto"), + {"features": [0]}, + "'estimator' must be a fitted regressor or classifier", + ), + ( + LinearRegression(), + {"features": [0], "response_method": "predict_proba"}, + "The response_method parameter is ignored for regressors", + ), + ( + GradientBoostingClassifier(random_state=0), + { + "features": [0], + "response_method": "predict_proba", + "method": "recursion", + }, + "'recursion' method, the response_method must be 'decision_function'", + ), + ( + GradientBoostingClassifier(random_state=0), + {"features": [0], "response_method": "predict_proba", "method": "auto"}, + "'recursion' method, the response_method must be 'decision_function'", + ), + ( + LinearRegression(), + {"features": [0], "method": "recursion", "kind": "individual"}, + "The 'recursion' method only applies when 'kind' is set to 'average'", + ), + ( + LinearRegression(), + {"features": [0], "method": "recursion", "kind": "both"}, + "The 'recursion' method only applies when 'kind' is set to 'average'", + ), + ( + LinearRegression(), + {"features": [0], "method": "recursion"}, + "Only the following estimators support the 'recursion' method:", + ), + ( + LinearRegression(), + {"features": [0, 1], "custom_values": {0: [1, 2, 3], 1: np.ones((3, 3))}}, + ( + "The custom grid for some features is not a one-dimensional array. " + "Feature 1: 2 dimensions" + ), + ), + ], +) +def test_partial_dependence_error(estimator, params, err_msg): + X, y = make_classification(random_state=0) + estimator = clone(estimator).fit(X, y) + + with pytest.raises(ValueError, match=err_msg): + partial_dependence(estimator, X, **params) + + +@pytest.mark.parametrize( + "estimator", [LinearRegression(), GradientBoostingClassifier(random_state=0)] +) +@pytest.mark.parametrize("features", [-1, 10000]) +def test_partial_dependence_unknown_feature_indices(estimator, features): + X, y = make_classification(random_state=0) + estimator = clone(estimator).fit(X, y) + + err_msg = "all features must be in" + with pytest.raises(ValueError, match=err_msg): + partial_dependence(estimator, X, [features]) + + +@pytest.mark.parametrize( + "estimator", [LinearRegression(), GradientBoostingClassifier(random_state=0)] +) +def test_partial_dependence_unknown_feature_string(estimator): + pd = pytest.importorskip("pandas") + X, y = make_classification(random_state=0) + df = pd.DataFrame(X) + estimator = clone(estimator).fit(df, y) + + features = ["random"] + err_msg = "A given column is not a column of the dataframe" + with pytest.raises(ValueError, match=err_msg): + partial_dependence(estimator, df, features) + + +@pytest.mark.parametrize( + "estimator", [LinearRegression(), GradientBoostingClassifier(random_state=0)] +) +def test_partial_dependence_X_list(estimator): + # check that array-like objects are accepted + X, y = make_classification(random_state=0) + estimator = clone(estimator).fit(X, y) + partial_dependence(estimator, list(X), [0], kind="average") + + +def test_warning_recursion_non_constant_init(): + # make sure that passing a non-constant init parameter to a GBDT and using + # recursion method yields a warning. + + gbc = GradientBoostingClassifier(init=DummyClassifier(), random_state=0) + gbc.fit(X, y) + + with pytest.warns( + UserWarning, match="Using recursion method with a non-constant init predictor" + ): + partial_dependence(gbc, X, [0], method="recursion", kind="average") + + with pytest.warns( + UserWarning, match="Using recursion method with a non-constant init predictor" + ): + partial_dependence(gbc, X, [0], method="recursion", kind="average") + + +def test_partial_dependence_sample_weight_of_fitted_estimator(): + # Test near perfect correlation between partial dependence and diagonal + # when sample weights emphasize y = x predictions + # non-regression test for #13193 + # TODO: extend to HistGradientBoosting once sample_weight is supported + N = 1000 + rng = np.random.RandomState(123456) + mask = rng.randint(2, size=N, dtype=bool) + + x = rng.rand(N) + # set y = x on mask and y = -x outside + y = x.copy() + y[~mask] = -y[~mask] + X = np.c_[mask, x] + # sample weights to emphasize data points where y = x + sample_weight = np.ones(N) + sample_weight[mask] = 1000.0 + + clf = GradientBoostingRegressor(n_estimators=10, random_state=1) + clf.fit(X, y, sample_weight=sample_weight) + + pdp = partial_dependence(clf, X, features=[1], kind="average") + + assert np.corrcoef(pdp["average"], pdp["grid_values"])[0, 1] > 0.99 + + +def test_hist_gbdt_sw_not_supported(): + # TODO: remove/fix when PDP supports HGBT with sample weights + clf = HistGradientBoostingRegressor(random_state=1) + clf.fit(X, y, sample_weight=np.ones(len(X))) + + with pytest.raises( + NotImplementedError, match="does not support partial dependence" + ): + partial_dependence(clf, X, features=[1]) + + +def test_partial_dependence_pipeline(): + # check that the partial dependence support pipeline + iris = load_iris() + + scaler = StandardScaler() + clf = DummyClassifier(random_state=42) + pipe = make_pipeline(scaler, clf) + + clf.fit(scaler.fit_transform(iris.data), iris.target) + pipe.fit(iris.data, iris.target) + + features = 0 + pdp_pipe = partial_dependence( + pipe, iris.data, features=[features], grid_resolution=10, kind="average" + ) + pdp_clf = partial_dependence( + clf, + scaler.transform(iris.data), + features=[features], + grid_resolution=10, + kind="average", + ) + assert_allclose(pdp_pipe["average"], pdp_clf["average"]) + assert_allclose( + pdp_pipe["grid_values"][0], + pdp_clf["grid_values"][0] * scaler.scale_[features] + scaler.mean_[features], + ) + + +@pytest.mark.parametrize( + "features, grid_resolution, n_vals_expected", + [ + (["a"], 10, 10), + (["a"], 2, 2), + ], +) +def test_partial_dependence_binary_model_grid_resolution( + features, grid_resolution, n_vals_expected +): + pd = pytest.importorskip("pandas") + model = DummyClassifier() + + rng = np.random.RandomState(0) + X = pd.DataFrame( + { + "a": rng.randint(0, 10, size=100).astype(np.float64), + "b": rng.randint(0, 10, size=100).astype(np.float64), + } + ) + y = pd.Series(rng.randint(0, 2, size=100)) + model.fit(X, y) + + part_dep = partial_dependence( + model, + X, + features=features, + grid_resolution=grid_resolution, + kind="average", + ) + assert part_dep["average"].size == n_vals_expected + + +@pytest.mark.parametrize( + "features, custom_values, n_vals_expected", + [ + (["a"], {"a": [1.0, 2.0, 3.0, 4.0]}, 4), + (["a"], {"a": [1.0, 2.0]}, 2), + (["a"], {"a": [1.0]}, 1), + ], +) +def test_partial_dependence_binary_model_custom_values( + features, custom_values, n_vals_expected +): + pd = pytest.importorskip("pandas") + model = DummyClassifier() + + X = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0], "b": [6.0, 7.0, 8.0, 9.0]}) + y = pd.Series([0, 1, 0, 1]) + model.fit(X, y) + + part_dep = partial_dependence( + model, + X, + features=features, + grid_resolution=3, + custom_values=custom_values, + kind="average", + ) + assert part_dep["average"].size == n_vals_expected + + +@pytest.mark.parametrize( + "features, custom_values, n_vals_expected", + [ + (["b"], {"b": ["a", "b"]}, 2), + (["b"], {"b": ["a"]}, 1), + (["a", "b"], {"a": [1.0, 2.0], "b": ["a", "b"]}, 4), + ], +) +def test_partial_dependence_pipeline_custom_values( + features, custom_values, n_vals_expected +): + pd = pytest.importorskip("pandas") + pl = make_pipeline( + SimpleImputer(strategy="most_frequent"), OneHotEncoder(), DummyClassifier() + ) + + X = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0], "b": ["a", "b", "a", "b"]}) + y = pd.Series([0, 1, 0, 1]) + pl.fit(X, y) + + X_holdout = pd.DataFrame({"a": [1.0, 2.0, 3.0, 4.0], "b": ["a", "b", "a", None]}) + part_dep = partial_dependence( + pl, + X_holdout, + features=features, + grid_resolution=3, + custom_values=custom_values, + kind="average", + ) + assert part_dep["average"].size == n_vals_expected + + +@pytest.mark.parametrize( + "estimator", + [ + LogisticRegression(max_iter=1000, random_state=0), + GradientBoostingClassifier(random_state=0, n_estimators=5), + ], + ids=["estimator-brute", "estimator-recursion"], +) +@pytest.mark.parametrize( + "preprocessor", + [ + None, + make_column_transformer( + (StandardScaler(), [iris.feature_names[i] for i in (0, 2)]), + (RobustScaler(), [iris.feature_names[i] for i in (1, 3)]), + ), + make_column_transformer( + (StandardScaler(), [iris.feature_names[i] for i in (0, 2)]), + remainder="passthrough", + ), + ], + ids=["None", "column-transformer", "column-transformer-passthrough"], +) +@pytest.mark.parametrize( + "features", + [[0, 2], [iris.feature_names[i] for i in (0, 2)]], + ids=["features-integer", "features-string"], +) +def test_partial_dependence_dataframe(estimator, preprocessor, features): + # check that the partial dependence support dataframe and pipeline + # including a column transformer + pd = pytest.importorskip("pandas") + df = pd.DataFrame(scale(iris.data), columns=iris.feature_names) + + pipe = make_pipeline(preprocessor, clone(estimator)) + pipe.fit(df, iris.target) + pdp_pipe = partial_dependence( + pipe, df, features=features, grid_resolution=10, kind="average" + ) + + # the column transformer will reorder the column when transforming + # we mixed the index to be sure that we are computing the partial + # dependence of the right columns + if preprocessor is not None: + X_proc = clone(preprocessor).fit_transform(df) + features_clf = [0, 1] + else: + X_proc = df + features_clf = [0, 2] + + clf = clone(estimator).fit(X_proc, iris.target) + pdp_clf = partial_dependence( + clf, + X_proc, + features=features_clf, + method="brute", + grid_resolution=10, + kind="average", + ) + + assert_allclose(pdp_pipe["average"], pdp_clf["average"]) + if preprocessor is not None: + scaler = preprocessor.named_transformers_["standardscaler"] + assert_allclose( + pdp_pipe["grid_values"][1], + pdp_clf["grid_values"][1] * scaler.scale_[1] + scaler.mean_[1], + ) + else: + assert_allclose(pdp_pipe["grid_values"][1], pdp_clf["grid_values"][1]) + + +@pytest.mark.parametrize( + "features, custom_values, expected_pd_shape", + [ + (0, None, (3, 10)), + (0, {0: [1.0, 2.0, 3.0]}, (3, 3)), + (iris.feature_names[0], None, (3, 10)), + (iris.feature_names[0], {iris.feature_names[0]: np.array([1.0, 2.0])}, (3, 2)), + ([0, 2], None, (3, 10, 10)), + ([0, 2], {2: [7, 8, 9, 10]}, (3, 10, 4)), + ([iris.feature_names[i] for i in (0, 2)], None, (3, 10, 10)), + ( + [iris.feature_names[i] for i in (0, 2)], + {iris.feature_names[2]: [1, 2, 3, 10]}, + (3, 10, 4), + ), + ([iris.feature_names[i] for i in (0, 2)], {2: [1, 2, 3, 10]}, (3, 10, 10)), + ( + [iris.feature_names[i] for i in (0, 2, 3)], + {iris.feature_names[2]: [1, 10]}, + (3, 10, 2, 10), + ), + ([True, False, True, False], None, (3, 10, 10)), + ], + ids=[ + "scalar-int", + "scalar-int-custom-values", + "scalar-str", + "scalar-str-custom-values", + "list-int", + "list-int-custom-values", + "list-str", + "list-str-custom-values", + "list-str-custom-values-incorrect", + "list-str-three-features", + "mask", + ], +) +def test_partial_dependence_feature_type(features, custom_values, expected_pd_shape): + # check all possible features type supported in PDP + pd = pytest.importorskip("pandas") + df = pd.DataFrame(iris.data, columns=iris.feature_names) + + preprocessor = make_column_transformer( + (StandardScaler(), [iris.feature_names[i] for i in (0, 2)]), + (RobustScaler(), [iris.feature_names[i] for i in (1, 3)]), + ) + pipe = make_pipeline( + preprocessor, LogisticRegression(max_iter=1000, random_state=0) + ) + pipe.fit(df, iris.target) + pdp_pipe = partial_dependence( + pipe, + df, + features=features, + grid_resolution=10, + kind="average", + custom_values=custom_values, + ) + assert pdp_pipe["average"].shape == expected_pd_shape + assert len(pdp_pipe["grid_values"]) == len(pdp_pipe["average"].shape) - 1 + + +@pytest.mark.parametrize( + "estimator", + [ + LinearRegression(), + LogisticRegression(), + GradientBoostingRegressor(), + GradientBoostingClassifier(), + ], +) +def test_partial_dependence_unfitted(estimator): + X = iris.data + preprocessor = make_column_transformer( + (StandardScaler(), [0, 2]), (RobustScaler(), [1, 3]) + ) + pipe = make_pipeline(preprocessor, estimator) + with pytest.raises(NotFittedError, match="is not fitted yet"): + partial_dependence(pipe, X, features=[0, 2], grid_resolution=10) + with pytest.raises(NotFittedError, match="is not fitted yet"): + partial_dependence(estimator, X, features=[0, 2], grid_resolution=10) + + +@pytest.mark.parametrize( + "Estimator, data", + [ + (LinearRegression, multioutput_regression_data), + (LogisticRegression, binary_classification_data), + ], +) +def test_kind_average_and_average_of_individual(Estimator, data): + est = Estimator() + (X, y), n_targets = data + est.fit(X, y) + + pdp_avg = partial_dependence(est, X=X, features=[1, 2], kind="average") + pdp_ind = partial_dependence(est, X=X, features=[1, 2], kind="individual") + avg_ind = np.mean(pdp_ind["individual"], axis=1) + assert_allclose(avg_ind, pdp_avg["average"]) + + +@pytest.mark.parametrize( + "Estimator, data", + [ + (LinearRegression, multioutput_regression_data), + (LogisticRegression, binary_classification_data), + ], +) +def test_partial_dependence_kind_individual_ignores_sample_weight(Estimator, data): + """Check that `sample_weight` does not have any effect on reported ICE.""" + est = Estimator() + (X, y), n_targets = data + sample_weight = np.arange(X.shape[0]) + est.fit(X, y) + + pdp_nsw = partial_dependence(est, X=X, features=[1, 2], kind="individual") + pdp_sw = partial_dependence( + est, X=X, features=[1, 2], kind="individual", sample_weight=sample_weight + ) + assert_allclose(pdp_nsw["individual"], pdp_sw["individual"]) + assert_allclose(pdp_nsw["grid_values"], pdp_sw["grid_values"]) + + +@pytest.mark.parametrize( + "estimator", + [ + LinearRegression(), + LogisticRegression(), + RandomForestRegressor(), + GradientBoostingClassifier(), + ], +) +@pytest.mark.parametrize("non_null_weight_idx", [0, 1, -1]) +def test_partial_dependence_non_null_weight_idx(estimator, non_null_weight_idx): + """Check that if we pass a `sample_weight` of zeros with only one index with + sample weight equals one, then the average `partial_dependence` with this + `sample_weight` is equal to the individual `partial_dependence` of the + corresponding index. + """ + X, y = iris.data, iris.target + preprocessor = make_column_transformer( + (StandardScaler(), [0, 2]), (RobustScaler(), [1, 3]) + ) + pipe = make_pipeline(preprocessor, clone(estimator)).fit(X, y) + + sample_weight = np.zeros_like(y) + sample_weight[non_null_weight_idx] = 1 + pdp_sw = partial_dependence( + pipe, + X, + [2, 3], + kind="average", + sample_weight=sample_weight, + grid_resolution=10, + ) + pdp_ind = partial_dependence(pipe, X, [2, 3], kind="individual", grid_resolution=10) + output_dim = 1 if is_regressor(pipe) else len(np.unique(y)) + for i in range(output_dim): + assert_allclose( + pdp_ind["individual"][i][non_null_weight_idx], + pdp_sw["average"][i], + ) + + +@pytest.mark.parametrize( + "Estimator, data", + [ + (LinearRegression, multioutput_regression_data), + (LogisticRegression, binary_classification_data), + ], +) +def test_partial_dependence_equivalence_equal_sample_weight(Estimator, data): + """Check that `sample_weight=None` is equivalent to having equal weights.""" + + est = Estimator() + (X, y), n_targets = data + est.fit(X, y) + + sample_weight, params = None, {"X": X, "features": [1, 2], "kind": "average"} + pdp_sw_none = partial_dependence(est, **params, sample_weight=sample_weight) + sample_weight = np.ones(len(y)) + pdp_sw_unit = partial_dependence(est, **params, sample_weight=sample_weight) + assert_allclose(pdp_sw_none["average"], pdp_sw_unit["average"]) + sample_weight = 2 * np.ones(len(y)) + pdp_sw_doubling = partial_dependence(est, **params, sample_weight=sample_weight) + assert_allclose(pdp_sw_none["average"], pdp_sw_doubling["average"]) + + +def test_partial_dependence_sample_weight_size_error(): + """Check that we raise an error when the size of `sample_weight` is not + consistent with `X` and `y`. + """ + est = LogisticRegression() + (X, y), n_targets = binary_classification_data + sample_weight = np.ones_like(y) + est.fit(X, y) + + with pytest.raises(ValueError, match="sample_weight.shape =="): + partial_dependence( + est, X, features=[0], sample_weight=sample_weight[1:], grid_resolution=10 + ) + + +def test_partial_dependence_sample_weight_with_recursion(): + """Check that we raise an error when `sample_weight` is provided with + `"recursion"` method. + """ + est = RandomForestRegressor() + (X, y), n_targets = regression_data + sample_weight = np.ones_like(y) + est.fit(X, y, sample_weight=sample_weight) + + with pytest.raises(ValueError, match="'recursion' method can only be applied when"): + partial_dependence( + est, X, features=[0], method="recursion", sample_weight=sample_weight + ) + + +def test_mixed_type_categorical(): + """Check that we raise a proper error when a column has mixed types and + the sorting of `np.unique` will fail.""" + X = np.array(["A", "B", "C", np.nan], dtype=object).reshape(-1, 1) + y = np.array([0, 1, 0, 1]) + + from sklearn.preprocessing import OrdinalEncoder + + clf = make_pipeline( + OrdinalEncoder(encoded_missing_value=-1), + LogisticRegression(), + ).fit(X, y) + with pytest.raises(ValueError, match="The column #0 contains mixed data types"): + partial_dependence(clf, X, features=[0]) + + +def test_reject_array_with_integer_dtype(): + X = np.arange(8).reshape(4, 2) + y = np.array([0, 1, 0, 1]) + clf = DummyClassifier() + clf.fit(X, y) + with pytest.warns( + FutureWarning, match=re.escape("The column 0 contains integer data.") + ): + partial_dependence(clf, X, features=0) + + with pytest.warns( + FutureWarning, match=re.escape("The column 1 contains integer data.") + ): + partial_dependence(clf, X, features=[1], categorical_features=[0]) + + with pytest.warns( + FutureWarning, match=re.escape("The column 0 contains integer data.") + ): + partial_dependence(clf, X, features=[0, 1]) + + # The following should not raise as we do not compute numerical partial + # dependence on integer columns. + with warnings.catch_warnings(): + warnings.simplefilter("error") + partial_dependence(clf, X, features=1, categorical_features=[1]) + + +def test_reject_pandas_with_integer_dtype(): + pd = pytest.importorskip("pandas") + X = pd.DataFrame( + { + "a": [1.0, 2.0, 3.0], + "b": [1, 2, 3], + "c": [1, 2, 3], + } + ) + y = np.array([0, 1, 0]) + clf = DummyClassifier() + clf.fit(X, y) + + with pytest.warns( + FutureWarning, match=re.escape("The column 'c' contains integer data.") + ): + partial_dependence(clf, X, features="c") + + with pytest.warns( + FutureWarning, match=re.escape("The column 'c' contains integer data.") + ): + partial_dependence(clf, X, features=["a", "c"]) + + # The following should not raise as we do not compute numerical partial + # dependence on integer columns. + with warnings.catch_warnings(): + warnings.simplefilter("error") + partial_dependence(clf, X, features=["a"]) + partial_dependence(clf, X, features=["c"], categorical_features=["c"]) + + +def test_partial_dependence_empty_categorical_features(): + """Check that we raise the proper exception when `categorical_features` + is an empty list""" + clf = make_pipeline(StandardScaler(), LogisticRegression()) + clf.fit(iris.data, iris.target) + + with pytest.raises( + ValueError, + match=re.escape( + "Passing an empty list (`[]`) to `categorical_features` is not " + "supported. Use `None` instead to indicate that there are no " + "categorical features." + ), + ): + partial_dependence( + estimator=clf, X=iris.data, features=[0], categorical_features=[] + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_pd_utils.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_pd_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5dea3834a77a70891a4efab25a560d09a49a13e1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_pd_utils.py @@ -0,0 +1,47 @@ +import numpy as np +import pytest + +from sklearn.inspection._pd_utils import _check_feature_names, _get_feature_index +from sklearn.utils._testing import _convert_container + + +@pytest.mark.parametrize( + "feature_names, array_type, expected_feature_names", + [ + (None, "array", ["x0", "x1", "x2"]), + (None, "dataframe", ["a", "b", "c"]), + (np.array(["a", "b", "c"]), "array", ["a", "b", "c"]), + ], +) +def test_check_feature_names(feature_names, array_type, expected_feature_names): + X = np.random.randn(10, 3) + column_names = ["a", "b", "c"] + X = _convert_container(X, constructor_name=array_type, columns_name=column_names) + feature_names_validated = _check_feature_names(X, feature_names) + assert feature_names_validated == expected_feature_names + + +def test_check_feature_names_error(): + X = np.random.randn(10, 3) + feature_names = ["a", "b", "c", "a"] + msg = "feature_names should not contain duplicates." + with pytest.raises(ValueError, match=msg): + _check_feature_names(X, feature_names) + + +@pytest.mark.parametrize("fx, idx", [(0, 0), (1, 1), ("a", 0), ("b", 1), ("c", 2)]) +def test_get_feature_index(fx, idx): + feature_names = ["a", "b", "c"] + assert _get_feature_index(fx, feature_names) == idx + + +@pytest.mark.parametrize( + "fx, feature_names, err_msg", + [ + ("a", None, "Cannot plot partial dependence for feature 'a'"), + ("d", ["a", "b", "c"], "Feature 'd' not in feature_names"), + ], +) +def test_get_feature_names_error(fx, feature_names, err_msg): + with pytest.raises(ValueError, match=err_msg): + _get_feature_index(fx, feature_names) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_permutation_importance.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_permutation_importance.py new file mode 100644 index 0000000000000000000000000000000000000000..b51ad7b71f66dc897ae2700f20e6f968da56e758 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/inspection/tests/test_permutation_importance.py @@ -0,0 +1,540 @@ +import numpy as np +import pytest +from joblib import parallel_backend +from numpy.testing import assert_allclose + +from sklearn.compose import ColumnTransformer +from sklearn.datasets import ( + load_diabetes, + load_iris, + make_classification, + make_regression, +) +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor +from sklearn.impute import SimpleImputer +from sklearn.inspection import permutation_importance +from sklearn.linear_model import LinearRegression, LogisticRegression +from sklearn.metrics import ( + get_scorer, + mean_squared_error, + r2_score, +) +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import KBinsDiscretizer, OneHotEncoder, StandardScaler, scale +from sklearn.utils._testing import _convert_container + + +@pytest.mark.parametrize("n_jobs", [1, 2]) +@pytest.mark.parametrize("max_samples", [0.5, 1.0]) +@pytest.mark.parametrize("sample_weight", [None, "ones"]) +def test_permutation_importance_correlated_feature_regression( + n_jobs, max_samples, sample_weight +): + # Make sure that feature highly correlated to the target have a higher + # importance + rng = np.random.RandomState(42) + n_repeats = 5 + + X, y = load_diabetes(return_X_y=True) + y_with_little_noise = (y + rng.normal(scale=0.001, size=y.shape[0])).reshape(-1, 1) + + X = np.hstack([X, y_with_little_noise]) + + weights = np.ones_like(y) if sample_weight == "ones" else sample_weight + clf = RandomForestRegressor(n_estimators=10, random_state=42) + clf.fit(X, y) + + result = permutation_importance( + clf, + X, + y, + sample_weight=weights, + n_repeats=n_repeats, + random_state=rng, + n_jobs=n_jobs, + max_samples=max_samples, + ) + + assert result.importances.shape == (X.shape[1], n_repeats) + + # the correlated feature with y was added as the last column and should + # have the highest importance + assert np.all(result.importances_mean[-1] > result.importances_mean[:-1]) + + +@pytest.mark.parametrize("n_jobs", [1, 2]) +@pytest.mark.parametrize("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 + # importance + rng = np.random.RandomState(42) + n_repeats = 5 + + dataset = load_iris() + X, y = dataset.data, dataset.target + y_with_little_noise = (y + rng.normal(scale=0.001, size=y.shape[0])).reshape(-1, 1) + + # Adds feature correlated with y as the last column + X = pd.DataFrame(X, columns=dataset.feature_names) + X["correlated_feature"] = y_with_little_noise + + clf = RandomForestClassifier(n_estimators=10, random_state=42) + clf.fit(X, y) + + result = permutation_importance( + 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) + + # the correlated feature with y was added as the last column and should + # have the highest importance + assert np.all(result.importances_mean[-1] > result.importances_mean[:-1]) + + +@pytest.mark.parametrize("n_jobs", [1, 2]) +@pytest.mark.parametrize("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: + rng = np.random.RandomState(seed) + n_repeats = 5 + n_samples = 1000 + n_classes = 5 + n_informative_features = 2 + n_noise_features = 1 + n_features = n_informative_features + n_noise_features + + # Generate a multiclass classification dataset and a set of informative + # binary features that can be used to predict some classes of y exactly + # while leaving some classes unexplained to make the problem harder. + classes = np.arange(n_classes) + y = rng.choice(classes, size=n_samples) + X = np.hstack([(y == c).reshape(-1, 1) for c in classes[:n_informative_features]]) + X = X.astype(np.float32) + + # Not all target classes are explained by the binary class indicator + # features: + assert n_informative_features < n_classes + + # Add 10 other noisy features with high cardinality (numerical) values + # that can be used to overfit the training data. + X = np.concatenate([X, rng.randn(n_samples, n_noise_features)], axis=1) + assert X.shape == (n_samples, n_features) + + # Split the dataset to be able to evaluate on a held-out test set. The + # Test size should be large enough for importance measurements to be + # stable: + X_train, X_test, y_train, y_test = train_test_split( + X, y, test_size=0.5, random_state=rng + ) + clf = RandomForestClassifier(n_estimators=5, random_state=rng) + clf.fit(X_train, y_train) + + # Variable importances computed by impurity decrease on the tree node + # splits often use the noisy features in splits. This can give misleading + # impression that high cardinality noisy variables are the most important: + tree_importances = clf.feature_importances_ + informative_tree_importances = tree_importances[:n_informative_features] + noisy_tree_importances = tree_importances[n_informative_features:] + assert informative_tree_importances.max() < noisy_tree_importances.min() + + # 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, + max_samples=max_samples, + ) + + assert r.importances.shape == (X.shape[1], n_repeats) + + # Split the importances between informative and noisy features + informative_importances = r.importances_mean[:n_informative_features] + noisy_importances = r.importances_mean[n_informative_features:] + + # Because we do not have a binary variable explaining each target classes, + # the RF model will have to use the random variable to make some + # (overfitting) splits (as max_depth is not set). Therefore the noisy + # variables will be non-zero but with small values oscillating around + # zero: + assert max(np.abs(noisy_importances)) > 1e-7 + assert noisy_importances.max() < 0.05 + + # The binary features correlated with y should have a higher importance + # than the high cardinality noisy features. + # The maximum test accuracy is 2 / 5 == 0.4, each informative feature + # contributing approximately a bit more than 0.2 of accuracy. + assert informative_importances.min() > 0.15 + + +def test_permutation_importance_mixed_types(): + rng = np.random.RandomState(42) + n_repeats = 4 + + # Last column is correlated with y + X = np.array([[1.0, 2.0, 3.0, np.nan], [2, 1, 2, 1]]).T + y = np.array([0, 1, 0, 1]) + + clf = make_pipeline(SimpleImputer(), LogisticRegression(solver="lbfgs")) + clf.fit(X, y) + result = permutation_importance(clf, X, y, n_repeats=n_repeats, random_state=rng) + + assert result.importances.shape == (X.shape[1], n_repeats) + + # the correlated feature with y is the last column and should + # have the highest importance + assert np.all(result.importances_mean[-1] > result.importances_mean[:-1]) + + # use another random state + rng = np.random.RandomState(0) + result2 = permutation_importance(clf, X, y, n_repeats=n_repeats, random_state=rng) + assert result2.importances.shape == (X.shape[1], n_repeats) + + assert not np.allclose(result.importances, result2.importances) + + # the correlated feature with y is the last column and should + # have the highest importance + assert np.all(result2.importances_mean[-1] > result2.importances_mean[:-1]) + + +def test_permutation_importance_mixed_types_pandas(): + pd = pytest.importorskip("pandas") + rng = np.random.RandomState(42) + n_repeats = 5 + + # Last column is correlated with y + X = pd.DataFrame({"col1": [1.0, 2.0, 3.0, np.nan], "col2": ["a", "b", "a", "b"]}) + y = np.array([0, 1, 0, 1]) + + num_preprocess = make_pipeline(SimpleImputer(), StandardScaler()) + preprocess = ColumnTransformer( + [("num", num_preprocess, ["col1"]), ("cat", OneHotEncoder(), ["col2"])] + ) + clf = make_pipeline(preprocess, LogisticRegression(solver="lbfgs")) + clf.fit(X, y) + + result = permutation_importance(clf, X, y, n_repeats=n_repeats, random_state=rng) + + assert result.importances.shape == (X.shape[1], n_repeats) + # the correlated feature with y is the last column and should + # have the highest importance + assert np.all(result.importances_mean[-1] > result.importances_mean[:-1]) + + +def test_permutation_importance_linear_regresssion(): + X, y = make_regression(n_samples=500, n_features=10, random_state=0) + + X = scale(X) + y = scale(y) + + lr = LinearRegression().fit(X, y) + + # this relationship can be computed in closed form + expected_importances = 2 * lr.coef_**2 + results = permutation_importance( + lr, X, y, n_repeats=50, scoring="neg_mean_squared_error" + ) + assert_allclose( + expected_importances, results.importances_mean, rtol=1e-1, atol=1e-6 + ) + + +@pytest.mark.parametrize("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, max_samples=max_samples + ) + + # First check that the problem is structured enough and that the model is + # complex enough to not yield trivial, constant importances: + imp_min = importance_sequential["importances"].min() + imp_max = importance_sequential["importances"].max() + assert imp_max - imp_min > 0.3 + + # The actually check that parallelism does not impact the results + # either with shared memory (threading) or without isolated memory + # via process-based parallelism using the default backend + # ('loky' or 'multiprocessing') depending on the joblib version: + + # process-based parallelism (by default): + importance_processes = permutation_importance( + lr, X, y, n_repeats=5, random_state=0, n_jobs=2 + ) + assert_allclose( + importance_processes["importances"], importance_sequential["importances"] + ) + + # thread-based parallelism: + with parallel_backend("threading"): + importance_threading = permutation_importance( + lr, X, y, n_repeats=5, random_state=0, n_jobs=2 + ) + assert_allclose( + importance_threading["importances"], importance_sequential["importances"] + ) + + +@pytest.mark.parametrize("n_jobs", [None, 1, 2]) +@pytest.mark.parametrize("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") + + # regression test to make sure that sequential and parallel calls will + # output the same results. + X, y = make_regression(n_samples=100, n_features=5, random_state=0) + X_df = pd.DataFrame(X) + + # Add a categorical feature that is statistically linked to y: + binner = KBinsDiscretizer( + n_bins=3, + encode="ordinal", + quantile_method="averaged_inverted_cdf", + ) + cat_column = binner.fit_transform(y.reshape(-1, 1)) + + # Concatenate the extra column to the numpy array: integers will be + # cast to float values + X = np.hstack([X, cat_column]) + assert X.dtype.kind == "f" + + # Insert extra column as a non-numpy-native dtype: + cat_column = pd.Categorical(cat_column.ravel()) + new_col_idx = len(X_df.columns) + X_df[new_col_idx] = cat_column + assert X_df[new_col_idx].dtype == cat_column.dtype + + # Stich an arbitrary index to the dataframe: + X_df.index = np.arange(len(X_df)).astype(str) + + rf = RandomForestRegressor(n_estimators=5, max_depth=3, random_state=0) + rf.fit(X, y) + + n_repeats = 3 + importance_array = permutation_importance( + 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 + # complex enough to not yield trivial, constant importances: + imp_min = importance_array["importances"].min() + imp_max = importance_array["importances"].max() + assert imp_max - imp_min > 0.3 + + # 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, + max_samples=max_samples, + ) + assert_allclose( + importance_array["importances"], importance_dataframe["importances"] + ) + + +@pytest.mark.parametrize("input_type", ["array", "dataframe"]) +def test_permutation_importance_large_memmaped_data(input_type): + # Smoke, non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/15810 + n_samples, n_features = int(5e4), 4 + X, y = make_classification( + n_samples=n_samples, n_features=n_features, random_state=0 + ) + assert X.nbytes > 1e6 # trigger joblib memmaping + + X = _convert_container(X, input_type) + clf = DummyClassifier(strategy="prior").fit(X, y) + + # Actual smoke test: should not raise any error: + n_repeats = 5 + r = permutation_importance(clf, X, y, n_repeats=n_repeats, n_jobs=2) + + # Auxiliary check: DummyClassifier is feature independent: + # 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 + ) + + +@pytest.mark.parametrize( + "list_single_scorer, multi_scorer", + [ + (["r2", "neg_mean_squared_error"], ["r2", "neg_mean_squared_error"]), + ( + ["r2", "neg_mean_squared_error"], + { + "r2": get_scorer("r2"), + "neg_mean_squared_error": get_scorer("neg_mean_squared_error"), + }, + ), + ( + ["r2", "neg_mean_squared_error"], + lambda estimator, X, y: { + "r2": r2_score(y, estimator.predict(X)), + "neg_mean_squared_error": -mean_squared_error(y, estimator.predict(X)), + }, + ), + ], +) +def test_permutation_importance_multi_metric(list_single_scorer, multi_scorer): + # Test permutation importance when scoring contains multiple scorers + + # Creating some data and estimator for the permutation test + x, y = make_regression(n_samples=500, n_features=10, random_state=0) + lr = LinearRegression().fit(x, y) + + multi_importance = permutation_importance( + lr, x, y, random_state=1, scoring=multi_scorer, n_repeats=2 + ) + assert set(multi_importance.keys()) == set(list_single_scorer) + + for scorer in list_single_scorer: + multi_result = multi_importance[scorer] + single_result = permutation_importance( + lr, x, y, random_state=1, scoring=scorer, n_repeats=2 + ) + + assert_allclose(multi_result.importances, single_result.importances) + + +def test_permutation_importance_max_samples_error(): + """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 <= n_samples" + + with pytest.raises(ValueError, match=err_msg): + permutation_importance(clf, X, y, max_samples=5) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..541f164daf46a336719b4148b7b25cea73fe212c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/__init__.py @@ -0,0 +1,95 @@ +"""A variety of linear models.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# See http://scikit-learn.sourceforge.net/modules/sgd.html and +# http://scikit-learn.sourceforge.net/modules/linear_model.html for +# complete documentation. + +from ._base import LinearRegression +from ._bayes import ARDRegression, BayesianRidge +from ._coordinate_descent import ( + ElasticNet, + ElasticNetCV, + Lasso, + LassoCV, + MultiTaskElasticNet, + MultiTaskElasticNetCV, + MultiTaskLasso, + MultiTaskLassoCV, + enet_path, + lasso_path, +) +from ._glm import GammaRegressor, PoissonRegressor, TweedieRegressor +from ._huber import HuberRegressor +from ._least_angle import ( + Lars, + LarsCV, + LassoLars, + LassoLarsCV, + LassoLarsIC, + lars_path, + lars_path_gram, +) +from ._logistic import LogisticRegression, LogisticRegressionCV +from ._omp import ( + OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV, + orthogonal_mp, + orthogonal_mp_gram, +) +from ._passive_aggressive import PassiveAggressiveClassifier, PassiveAggressiveRegressor +from ._perceptron import Perceptron +from ._quantile import QuantileRegressor +from ._ransac import RANSACRegressor +from ._ridge import Ridge, RidgeClassifier, RidgeClassifierCV, RidgeCV, ridge_regression +from ._stochastic_gradient import SGDClassifier, SGDOneClassSVM, SGDRegressor +from ._theil_sen import TheilSenRegressor + +__all__ = [ + "ARDRegression", + "BayesianRidge", + "ElasticNet", + "ElasticNetCV", + "GammaRegressor", + "HuberRegressor", + "Lars", + "LarsCV", + "Lasso", + "LassoCV", + "LassoLars", + "LassoLarsCV", + "LassoLarsIC", + "LinearRegression", + "LogisticRegression", + "LogisticRegressionCV", + "MultiTaskElasticNet", + "MultiTaskElasticNetCV", + "MultiTaskLasso", + "MultiTaskLassoCV", + "OrthogonalMatchingPursuit", + "OrthogonalMatchingPursuitCV", + "PassiveAggressiveClassifier", + "PassiveAggressiveRegressor", + "Perceptron", + "PoissonRegressor", + "QuantileRegressor", + "RANSACRegressor", + "Ridge", + "RidgeCV", + "RidgeClassifier", + "RidgeClassifierCV", + "SGDClassifier", + "SGDOneClassSVM", + "SGDRegressor", + "TheilSenRegressor", + "TweedieRegressor", + "enet_path", + "lars_path", + "lars_path_gram", + "lasso_path", + "orthogonal_mp", + "orthogonal_mp_gram", + "ridge_regression", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..c059e3fa84310e4bc022d43cf159eaed3aa752fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_base.py @@ -0,0 +1,869 @@ +""" +Generalized Linear Models. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import warnings +from abc import ABCMeta, abstractmethod +from numbers import Integral, Real + +import numpy as np +import scipy.sparse as sp +from scipy import linalg, optimize, sparse +from scipy.sparse.linalg import lsqr +from scipy.special import expit + +from ..base import ( + BaseEstimator, + ClassifierMixin, + MultiOutputMixin, + RegressorMixin, + _fit_context, +) +from ..utils import check_array, check_random_state +from ..utils._array_api import ( + _asarray_with_order, + _average, + get_namespace, + get_namespace_and_device, + indexing_dtype, + supported_float_dtypes, +) +from ..utils._param_validation import Interval +from ..utils._seq_dataset import ( + ArrayDataset32, + ArrayDataset64, + CSRDataset32, + CSRDataset64, +) +from ..utils.extmath import safe_sparse_dot +from ..utils.parallel import Parallel, delayed +from ..utils.sparsefuncs import mean_variance_axis +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data + +# TODO: bayesian_ridge_regression and bayesian_regression_ard +# should be squashed into its respective objects. + +SPARSE_INTERCEPT_DECAY = 0.01 +# For sparse data intercept updates are scaled by this decay factor to avoid +# intercept oscillation. + + +def make_dataset(X, y, sample_weight, random_state=None): + """Create ``Dataset`` abstraction for sparse and dense inputs. + + This also returns the ``intercept_decay`` which is different + for sparse datasets. + + Parameters + ---------- + X : array-like, shape (n_samples, n_features) + Training data + + y : array-like, shape (n_samples, ) + Target values. + + sample_weight : numpy array of shape (n_samples,) + The weight of each sample + + random_state : int, RandomState instance or None (default) + Determines random number generation for dataset random sampling. It is not + used for dataset shuffling. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + dataset + The ``Dataset`` abstraction + intercept_decay + The intercept decay + """ + + rng = check_random_state(random_state) + # seed should never be 0 in SequentialDataset64 + seed = rng.randint(1, np.iinfo(np.int32).max) + + if X.dtype == np.float32: + CSRData = CSRDataset32 + ArrayData = ArrayDataset32 + else: + CSRData = CSRDataset64 + ArrayData = ArrayDataset64 + + if sp.issparse(X): + dataset = CSRData(X.data, X.indptr, X.indices, y, sample_weight, seed=seed) + intercept_decay = SPARSE_INTERCEPT_DECAY + else: + X = np.ascontiguousarray(X) + dataset = ArrayData(X, y, sample_weight, seed=seed) + intercept_decay = 1.0 + + return dataset, intercept_decay + + +def _preprocess_data( + X, + y, + *, + fit_intercept, + copy=True, + copy_y=True, + sample_weight=None, + check_input=True, +): + """Common data preprocessing for fitting linear models. + + This helper is in charge of the following steps: + + - Ensure that `sample_weight` is an array or `None`. + - If `check_input=True`, perform standard input validation of `X`, `y`. + - Perform copies if requested to avoid side-effects in case of inplace + modifications of the input. + + Then, if `fit_intercept=True` this preprocessing centers both `X` and `y` as + follows: + - if `X` is dense, center the data and + store the mean vector in `X_offset`. + - if `X` is sparse, store the mean in `X_offset` + without centering `X`. The centering is expected to be handled by the + linear solver where appropriate. + - in either case, always center `y` and store the mean in `y_offset`. + - both `X_offset` and `y_offset` are always weighted by `sample_weight` + if not set to `None`. + + If `fit_intercept=False`, no centering is performed and `X_offset`, `y_offset` + are set to zero. + + Returns + ------- + X_out : {ndarray, sparse matrix} of shape (n_samples, n_features) + If copy=True a copy of the input X is triggered, otherwise operations are + inplace. + If input X is dense, then X_out is centered. + y_out : {ndarray, sparse matrix} of shape (n_samples,) or (n_samples, n_targets) + Centered version of y. Possibly performed inplace on input y depending + on the copy_y parameter. + X_offset : ndarray of shape (n_features,) + The mean per column of input X. + y_offset : float or ndarray of shape (n_features,) + X_scale : ndarray of shape (n_features,) + Always an array of ones. TODO: refactor the code base to make it + possible to remove this unused variable. + """ + xp, _, device_ = get_namespace_and_device(X, y, sample_weight) + n_samples, n_features = X.shape + X_is_sparse = sp.issparse(X) + + if isinstance(sample_weight, numbers.Number): + sample_weight = None + if sample_weight is not None: + sample_weight = xp.asarray(sample_weight) + + if check_input: + X = check_array( + X, copy=copy, accept_sparse=["csr", "csc"], dtype=supported_float_dtypes(xp) + ) + y = check_array(y, dtype=X.dtype, copy=copy_y, ensure_2d=False) + else: + y = xp.astype(y, X.dtype, copy=copy_y) + if copy: + if X_is_sparse: + X = X.copy() + else: + X = _asarray_with_order(X, order="K", copy=True, xp=xp) + + dtype_ = X.dtype + + if fit_intercept: + if X_is_sparse: + X_offset, X_var = mean_variance_axis(X, axis=0, weights=sample_weight) + else: + X_offset = _average(X, axis=0, weights=sample_weight, xp=xp) + + X_offset = xp.astype(X_offset, X.dtype, copy=False) + X -= X_offset + + y_offset = _average(y, axis=0, weights=sample_weight, xp=xp) + y -= y_offset + else: + X_offset = xp.zeros(n_features, dtype=X.dtype, device=device_) + if y.ndim == 1: + y_offset = xp.asarray(0.0, dtype=dtype_, device=device_) + else: + y_offset = xp.zeros(y.shape[1], dtype=dtype_, device=device_) + + # XXX: X_scale is no longer needed. It is an historic artifact from the + # time where linear model exposed the normalize parameter. + X_scale = xp.ones(n_features, dtype=X.dtype, device=device_) + return X, y, X_offset, y_offset, X_scale + + +# TODO: _rescale_data should be factored into _preprocess_data. +# Currently, the fact that sag implements its own way to deal with +# sample_weight makes the refactoring tricky. + + +def _rescale_data(X, y, sample_weight, inplace=False): + """Rescale data sample-wise by square root of 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 + ------- + X_rescaled : {array-like, sparse matrix} + + y_rescaled : {array-like, sparse matrix} + """ + # Assume that _validate_data and _check_sample_weight have been called by + # the caller. + xp, _ = get_namespace(X, y, sample_weight) + n_samples = X.shape[0] + sample_weight_sqrt = xp.sqrt(sample_weight) + + if sp.issparse(X) or sp.issparse(y): + sw_matrix = sparse.dia_matrix( + (sample_weight_sqrt, 0), shape=(n_samples, n_samples) + ) + + if sp.issparse(X): + X = safe_sparse_dot(sw_matrix, X) + else: + if inplace: + X *= sample_weight_sqrt[:, None] + else: + X = X * sample_weight_sqrt[:, None] + + if sp.issparse(y): + y = safe_sparse_dot(sw_matrix, y) + else: + if inplace: + if y.ndim == 1: + y *= sample_weight_sqrt + else: + y *= sample_weight_sqrt[:, None] + else: + if y.ndim == 1: + y = y * sample_weight_sqrt + else: + y = y * sample_weight_sqrt[:, None] + return X, y, sample_weight_sqrt + + +class LinearModel(BaseEstimator, metaclass=ABCMeta): + """Base class for Linear Models""" + + @abstractmethod + def fit(self, X, y): + """Fit model.""" + + def _decision_function(self, X): + check_is_fitted(self) + + X = validate_data(self, X, accept_sparse=["csr", "csc", "coo"], reset=False) + coef_ = self.coef_ + if coef_.ndim == 1: + return X @ coef_ + self.intercept_ + else: + return X @ coef_.T + self.intercept_ + + def predict(self, X): + """ + Predict using the linear model. + + Parameters + ---------- + X : array-like or sparse matrix, shape (n_samples, n_features) + Samples. + + Returns + ------- + C : array, shape (n_samples,) + Returns predicted values. + """ + return self._decision_function(X) + + def _set_intercept(self, X_offset, y_offset, X_scale): + """Set the intercept_""" + + xp, _ = get_namespace(X_offset, y_offset, X_scale) + + if self.fit_intercept: + # We always want coef_.dtype=X.dtype. For instance, X.dtype can differ from + # coef_.dtype if warm_start=True. + coef_ = xp.astype(self.coef_, X_scale.dtype, copy=False) + coef_ = self.coef_ = xp.divide(coef_, X_scale) + + if coef_.ndim == 1: + intercept_ = y_offset - X_offset @ coef_ + else: + intercept_ = y_offset - X_offset @ coef_.T + + self.intercept_ = intercept_ + + else: + self.intercept_ = 0.0 + + +# XXX Should this derive from LinearModel? It should be a mixin, not an ABC. +# Maybe the n_features checking can be moved to LinearModel. +class LinearClassifierMixin(ClassifierMixin): + """Mixin for linear classifiers. + + Handles prediction for sparse and dense X. + """ + + def decision_function(self, X): + """ + Predict confidence scores for samples. + + The confidence score for a sample is proportional to the signed + distance of that sample to the hyperplane. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix for which we want to get the confidence scores. + + Returns + ------- + scores : ndarray of shape (n_samples,) or (n_samples, n_classes) + Confidence scores per `(n_samples, n_classes)` combination. In the + binary case, confidence score for `self.classes_[1]` where >0 means + this class would be predicted. + """ + check_is_fitted(self) + xp, _ = get_namespace(X) + + X = validate_data(self, X, accept_sparse="csr", reset=False) + scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ + return ( + xp.reshape(scores, (-1,)) + if (scores.ndim > 1 and scores.shape[1] == 1) + else scores + ) + + def predict(self, X): + """ + Predict class labels for samples in X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data matrix for which we want to get the predictions. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + Vector containing the class labels for each sample. + """ + xp, _ = get_namespace(X) + scores = self.decision_function(X) + if len(scores.shape) == 1: + indices = xp.astype(scores > 0, indexing_dtype(xp)) + else: + indices = xp.argmax(scores, axis=1) + + return xp.take(self.classes_, indices, axis=0) + + def _predict_proba_lr(self, X): + """Probability estimation for OvR logistic regression. + + Positive class probabilities are computed as + 1. / (1. + np.exp(-self.decision_function(X))); + multiclass is handled by normalizing that over all classes. + """ + prob = self.decision_function(X) + expit(prob, out=prob) + if prob.ndim == 1: + return np.vstack([1 - prob, prob]).T + else: + # OvR normalization, like LibLinear's predict_probability + prob /= prob.sum(axis=1).reshape((prob.shape[0], -1)) + return prob + + +class SparseCoefMixin: + """Mixin for converting coef_ to and from CSR format. + + L1-regularizing estimators should inherit this. + """ + + def densify(self): + """ + Convert coefficient matrix to dense array format. + + Converts the ``coef_`` member (back) to a numpy.ndarray. This is the + default format of ``coef_`` and is required for fitting, so calling + this method is only required on models that have previously been + sparsified; otherwise, it is a no-op. + + Returns + ------- + self + Fitted estimator. + """ + msg = "Estimator, %(name)s, must be fitted before densifying." + check_is_fitted(self, msg=msg) + if sp.issparse(self.coef_): + self.coef_ = self.coef_.toarray() + return self + + def sparsify(self): + """ + Convert coefficient matrix to sparse format. + + Converts the ``coef_`` member to a scipy.sparse matrix, which for + L1-regularized models can be much more memory- and storage-efficient + than the usual numpy.ndarray representation. + + The ``intercept_`` member is not converted. + + Returns + ------- + self + Fitted estimator. + + Notes + ----- + For non-sparse models, i.e. when there are not many zeros in ``coef_``, + this may actually *increase* memory usage, so use this method with + care. A rule of thumb is that the number of zero elements, which can + be computed with ``(coef_ == 0).sum()``, must be more than 50% for this + to provide significant benefits. + + After calling this method, further fitting with the partial_fit + method (if any) will not work until you call densify. + """ + msg = "Estimator, %(name)s, must be fitted before sparsifying." + check_is_fitted(self, msg=msg) + self.coef_ = sp.csr_matrix(self.coef_) + return self + + +class LinearRegression(MultiOutputMixin, RegressorMixin, LinearModel): + """ + Ordinary least squares Linear Regression. + + LinearRegression fits a linear model with coefficients w = (w1, ..., wp) + to minimize the residual sum of squares between the observed targets in + the dataset, and the targets predicted by the linear approximation. + + Parameters + ---------- + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to False, no intercept will be used in calculations + (i.e. data is expected to be centered). + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + tol : float, default=1e-6 + The precision of the solution (`coef_`) is determined by `tol` which + specifies a different convergence criterion for the `lsqr` solver. + `tol` is set as `atol` and `btol` of `scipy.sparse.linalg.lsqr` when + fitting on sparse training data. This parameter has no effect when fitting + on dense data. + + .. versionadded:: 1.7 + + n_jobs : int, default=None + The number of jobs to use for the computation. This will only provide + speedup in case of sufficiently large problems, that is if firstly + `n_targets > 1` and secondly `X` is sparse or if `positive` is set + to `True`. ``None`` means 1 unless in a + :obj:`joblib.parallel_backend` context. ``-1`` means using all + processors. See :term:`Glossary ` 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. + + For a comparison between a linear regression model with positive constraints + on the regression coefficients and a linear regression without such constraints, + see :ref:`sphx_glr_auto_examples_linear_model_plot_nnls.py`. + + .. versionadded:: 0.24 + + Attributes + ---------- + coef_ : array of shape (n_features, ) or (n_targets, n_features) + Estimated coefficients for the linear regression problem. + If multiple targets are passed during the fit (y 2D), this + is a 2D array of shape (n_targets, n_features), while if only + one target is passed, this is a 1D array of length n_features. + + rank_ : int + Rank of matrix `X`. Only available when `X` is dense. + + singular_ : array of shape (min(X, y),) + Singular values of `X`. Only available when `X` is dense. + + intercept_ : float or array of shape (n_targets,) + Independent term in the linear model. Set to 0.0 if + `fit_intercept = False`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + Ridge : Ridge regression addresses some of the + problems of Ordinary Least Squares by imposing a penalty on the + size of the coefficients with l2 regularization. + Lasso : The Lasso is a linear model that estimates + sparse coefficients with l1 regularization. + ElasticNet : Elastic-Net is a linear regression + model trained with both l1 and l2 -norm regularization of the + coefficients. + + Notes + ----- + From the implementation point of view, this is just plain Ordinary + Least Squares (scipy.linalg.lstsq) or Non Negative Least Squares + (scipy.optimize.nnls) wrapped as a predictor object. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.linear_model import LinearRegression + >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) + >>> # y = 1 * x_0 + 2 * x_1 + 3 + >>> y = np.dot(X, np.array([1, 2])) + 3 + >>> reg = LinearRegression().fit(X, y) + >>> reg.score(X, y) + 1.0 + >>> reg.coef_ + array([1., 2.]) + >>> reg.intercept_ + np.float64(3.0) + >>> reg.predict(np.array([[3, 5]])) + array([16.]) + """ + + _parameter_constraints: dict = { + "fit_intercept": ["boolean"], + "copy_X": ["boolean"], + "n_jobs": [None, Integral], + "positive": ["boolean"], + "tol": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + *, + fit_intercept=True, + copy_X=True, + tol=1e-6, + n_jobs=None, + positive=False, + ): + self.fit_intercept = fit_intercept + self.copy_X = copy_X + self.tol = tol + self.n_jobs = n_jobs + self.positive = positive + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """ + Fit linear model. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. Will be cast to X's dtype if necessary. + + sample_weight : array-like of shape (n_samples,), default=None + Individual weights for each sample. + + .. versionadded:: 0.17 + parameter *sample_weight* support to LinearRegression. + + Returns + ------- + self : object + Fitted Estimator. + """ + n_jobs_ = self.n_jobs + + accept_sparse = False if self.positive else ["csr", "csc", "coo"] + + X, y = validate_data( + self, + X, + y, + accept_sparse=accept_sparse, + y_numeric=True, + multi_output=True, + force_writeable=True, + ) + + has_sw = sample_weight is not None + if has_sw: + sample_weight = _check_sample_weight( + sample_weight, X, dtype=X.dtype, ensure_non_negative=True + ) + + # Note that neither _rescale_data nor the rest of the fit method of + # LinearRegression can benefit from in-place operations when X is a + # sparse matrix. Therefore, let's not copy X when it is sparse. + copy_X_in_preprocess_data = self.copy_X and not sp.issparse(X) + + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, + y, + fit_intercept=self.fit_intercept, + copy=copy_X_in_preprocess_data, + sample_weight=sample_weight, + ) + + if has_sw: + # Sample weight can be implemented via a simple rescaling. Note + # that we safely do inplace rescaling when _preprocess_data has + # already made a copy if requested. + X, y, sample_weight_sqrt = _rescale_data( + X, y, sample_weight, inplace=copy_X_in_preprocess_data + ) + + if self.positive: + if y.ndim < 2: + self.coef_ = optimize.nnls(X, y)[0] + 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_ = np.vstack([out[0] for out in outs]) + elif sp.issparse(X): + X_offset_scale = X_offset / X_scale + + if has_sw: + + 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) + + else: + + def matvec(b): + return X.dot(b) - b.dot(X_offset_scale) + + def rmatvec(b): + return X.T.dot(b) - X_offset_scale * b.sum() + + X_centered = sparse.linalg.LinearOperator( + shape=X.shape, matvec=matvec, rmatvec=rmatvec + ) + + if y.ndim < 2: + self.coef_ = lsqr(X_centered, y, atol=self.tol, btol=self.tol)[0] + else: + # sparse_lstsq cannot handle y with shape (M, K) + outs = Parallel(n_jobs=n_jobs_)( + delayed(lsqr)( + X_centered, y[:, j].ravel(), atol=self.tol, btol=self.tol + ) + for j in range(y.shape[1]) + ) + self.coef_ = np.vstack([out[0] for out in outs]) + else: + # cut-off ratio for small singular values + cond = max(X.shape) * np.finfo(X.dtype).eps + self.coef_, _, self.rank_, self.singular_ = linalg.lstsq(X, y, cond=cond) + self.coef_ = self.coef_.T + + if y.ndim == 1: + self.coef_ = np.ravel(self.coef_) + self._set_intercept(X_offset, y_offset, X_scale) + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = not self.positive + return tags + + +def _check_precomputed_gram_matrix( + X, precompute, X_offset, X_scale, rtol=None, 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=None + Relative tolerance; see numpy.allclose + If None, it is set to 1e-4 for arrays of dtype numpy.float32 and 1e-7 + otherwise. + + 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] + + dtypes = [precompute.dtype, expected.dtype] + if rtol is None: + rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes] + rtol = max(rtols) + + 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, + fit_intercept, + copy, + check_input=True, + sample_weight=None, +): + """Function used at beginning of fit in linear models with L1 or L0 penalty. + + This function applies _preprocess_data and additionally computes the gram matrix + `precompute` as needed as well as `Xy`. + """ + n_samples, n_features = X.shape + + if sparse.issparse(X): + # copy is not needed here as X is not modified inplace when X is sparse + precompute = False + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, + y, + fit_intercept=fit_intercept, + copy=False, + check_input=check_input, + sample_weight=sample_weight, + ) + else: + # copy was done in fit if necessary + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, + y, + fit_intercept=fit_intercept, + copy=copy, + check_input=check_input, + 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) + + if hasattr(precompute, "__array__"): + if fit_intercept and not np.allclose(X_offset, np.zeros(n_features)): + warnings.warn( + ( + "Gram matrix was provided but X was centered to fit " + "intercept: recomputing Gram matrix." + ), + UserWarning, + ) + # TODO: instead of warning and recomputing, we could just center + # the user provided Gram matrix a-posteriori (after making a copy + # when `copy=True`). + # 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": + precompute = n_samples > n_features + + if precompute is True: + # make sure that the 'precompute' array is contiguous. + precompute = np.empty(shape=(n_features, n_features), dtype=X.dtype, order="C") + np.dot(X.T, X, out=precompute) + + if not hasattr(precompute, "__array__"): + Xy = None # cannot use Xy if precompute is not Gram + + if hasattr(precompute, "__array__") and Xy is None: + common_dtype = np.result_type(X.dtype, y.dtype) + if y.ndim == 1: + # Xy is 1d, make sure it is contiguous. + Xy = np.empty(shape=n_features, dtype=common_dtype, order="C") + np.dot(X.T, y, out=Xy) + else: + # Make sure that Xy is always F contiguous even if X or y are not + # contiguous: the goal is to make it fast to extract the data for a + # specific target. + n_targets = y.shape[1] + Xy = np.empty(shape=(n_features, n_targets), dtype=common_dtype, order="F") + np.dot(y.T, X, out=Xy.T) + + return X, y, X_offset, y_offset, X_scale, precompute, Xy diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py new file mode 100644 index 0000000000000000000000000000000000000000..e519660323d80f8d8f7f607451f59d26ecb62f19 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_bayes.py @@ -0,0 +1,826 @@ +""" +Various bayesian regression +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from math import log +from numbers import Integral, Real + +import numpy as np +from scipy import linalg +from scipy.linalg import pinvh + +from ..base import RegressorMixin, _fit_context +from ..utils import _safe_indexing +from ..utils._param_validation import Interval +from ..utils.extmath import fast_logdet +from ..utils.validation import _check_sample_weight, validate_data +from ._base import LinearModel, _preprocess_data, _rescale_data + +############################################################################### +# BayesianRidge regression + + +class BayesianRidge(RegressorMixin, LinearModel): + """Bayesian ridge regression. + + Fit a Bayesian ridge model. See the Notes section for details on this + implementation and the optimization of the regularization parameters + lambda (precision of the weights) and alpha (precision of the noise). + + Read more in the :ref:`User Guide `. + For an intuitive visualization of how the sinusoid is approximated by + a polynomial using different pairs of initial values, see + :ref:`sphx_glr_auto_examples_linear_model_plot_bayesian_ridge_curvefit.py`. + + Parameters + ---------- + max_iter : int, default=300 + Maximum number of iterations over the complete dataset before + stopping independently of any early stopping criterion. + + .. versionchanged:: 1.3 + + tol : float, default=1e-3 + Stop the algorithm if w has converged. + + alpha_1 : float, default=1e-6 + Hyper-parameter : shape parameter for the Gamma distribution prior + over the alpha parameter. + + alpha_2 : float, default=1e-6 + Hyper-parameter : inverse scale parameter (rate parameter) for the + Gamma distribution prior over the alpha parameter. + + lambda_1 : float, default=1e-6 + Hyper-parameter : shape parameter for the Gamma distribution prior + over the lambda parameter. + + lambda_2 : float, default=1e-6 + Hyper-parameter : inverse scale parameter (rate parameter) for the + Gamma distribution prior over the lambda parameter. + + alpha_init : float, default=None + Initial value for alpha (precision of the noise). + If not set, alpha_init is 1/Var(y). + + .. versionadded:: 0.22 + + lambda_init : float, default=None + Initial value for lambda (precision of the weights). + If not set, lambda_init is 1. + + .. versionadded:: 0.22 + + compute_score : bool, default=False + If True, compute the log marginal likelihood at each iteration of the + optimization. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. + The intercept is not treated as a probabilistic parameter + and thus has no associated variance. If set + to False, no intercept will be used in calculations + (i.e. data is expected to be centered). + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + verbose : bool, default=False + Verbose mode when fitting the model. + + Attributes + ---------- + coef_ : array-like of shape (n_features,) + Coefficients of the regression model (mean of distribution) + + intercept_ : float + Independent term in decision function. Set to 0.0 if + `fit_intercept = False`. + + alpha_ : float + Estimated precision of the noise. + + lambda_ : float + Estimated precision of the weights. + + sigma_ : array-like of shape (n_features, n_features) + Estimated variance-covariance matrix of the weights + + scores_ : array-like of shape (n_iter_+1,) + If computed_score is True, value of the log marginal likelihood (to be + maximized) at each iteration of the optimization. The array starts + with the value of the log marginal likelihood obtained for the initial + values of alpha and lambda and ends with the value obtained for the + estimated alpha and lambda. + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + + X_offset_ : ndarray of shape (n_features,) + If `fit_intercept=True`, offset subtracted for centering data to a + zero mean. Set to np.zeros(n_features) otherwise. + + X_scale_ : ndarray of shape (n_features,) + Set to np.ones(n_features). + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + ARDRegression : Bayesian ARD regression. + + Notes + ----- + There exist several strategies to perform Bayesian ridge regression. This + implementation is based on the algorithm described in Appendix A of + (Tipping, 2001) where updates of the regularization parameters are done as + suggested in (MacKay, 1992). Note that according to A New + View of Automatic Relevance Determination (Wipf and Nagarajan, 2008) these + update rules do not guarantee that the marginal likelihood is increasing + between two consecutive iterations of the optimization. + + References + ---------- + D. J. C. MacKay, Bayesian Interpolation, Computation and Neural Systems, + Vol. 4, No. 3, 1992. + + M. E. Tipping, Sparse Bayesian Learning and the Relevance Vector Machine, + Journal of Machine Learning Research, Vol. 1, 2001. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.BayesianRidge() + >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) + BayesianRidge() + >>> clf.predict([[1, 1]]) + array([1.]) + """ + + _parameter_constraints: dict = { + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="neither")], + "alpha_1": [Interval(Real, 0, None, closed="left")], + "alpha_2": [Interval(Real, 0, None, closed="left")], + "lambda_1": [Interval(Real, 0, None, closed="left")], + "lambda_2": [Interval(Real, 0, None, closed="left")], + "alpha_init": [None, Interval(Real, 0, None, closed="left")], + "lambda_init": [None, Interval(Real, 0, None, closed="left")], + "compute_score": ["boolean"], + "fit_intercept": ["boolean"], + "copy_X": ["boolean"], + "verbose": ["verbose"], + } + + def __init__( + self, + *, + max_iter=300, + tol=1.0e-3, + alpha_1=1.0e-6, + alpha_2=1.0e-6, + lambda_1=1.0e-6, + lambda_2=1.0e-6, + alpha_init=None, + lambda_init=None, + compute_score=False, + fit_intercept=True, + copy_X=True, + verbose=False, + ): + self.max_iter = max_iter + self.tol = tol + self.alpha_1 = alpha_1 + self.alpha_2 = alpha_2 + self.lambda_1 = lambda_1 + self.lambda_2 = lambda_2 + self.alpha_init = alpha_init + self.lambda_init = lambda_init + self.compute_score = compute_score + self.fit_intercept = fit_intercept + self.copy_X = copy_X + self.verbose = verbose + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit the model. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + y : ndarray of shape (n_samples,) + Target values. Will be cast to X's dtype if necessary. + + sample_weight : ndarray of shape (n_samples,), default=None + Individual weights for each sample. + + .. versionadded:: 0.20 + parameter *sample_weight* support to BayesianRidge. + + Returns + ------- + self : object + Returns the instance itself. + """ + X, y = validate_data( + self, + X, + y, + dtype=[np.float64, np.float32], + force_writeable=True, + y_numeric=True, + ) + dtype = X.dtype + n_samples, n_features = X.shape + + sw_sum = n_samples + y_var = y.var() + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=dtype) + sw_sum = sample_weight.sum() + y_mean = np.average(y, weights=sample_weight) + y_var = np.average((y - y_mean) ** 2, weights=sample_weight) + + X, y, X_offset_, y_offset_, X_scale_ = _preprocess_data( + X, + y, + fit_intercept=self.fit_intercept, + copy=self.copy_X, + sample_weight=sample_weight, + ) + + if sample_weight is not None: + # Sample weight can be implemented via a simple rescaling. + X, y, _ = _rescale_data(X, y, sample_weight) + + self.X_offset_ = X_offset_ + self.X_scale_ = X_scale_ + + # Initialization of the values of the parameters + eps = np.finfo(np.float64).eps + # Add `eps` in the denominator to omit division by zero + alpha_ = self.alpha_init + lambda_ = self.lambda_init + if alpha_ is None: + alpha_ = 1.0 / (y_var + eps) + if lambda_ is None: + lambda_ = 1.0 + + # Avoid unintended type promotion to float64 with numpy 2 + alpha_ = np.asarray(alpha_, dtype=dtype) + lambda_ = np.asarray(lambda_, dtype=dtype) + + verbose = self.verbose + lambda_1 = self.lambda_1 + lambda_2 = self.lambda_2 + alpha_1 = self.alpha_1 + alpha_2 = self.alpha_2 + + self.scores_ = list() + coef_old_ = None + + XT_y = np.dot(X.T, y) + # Let M, N = n_samples, n_features and K = min(M, N). + # The posterior covariance matrix needs Vh_full: (N, N). + # The full SVD is only required when n_samples < n_features. + # When n_samples < n_features, K=M and full_matrices=True + # U: (M, M), S: M, Vh_full: (N, N), Vh: (M, N) + # When n_samples > n_features, K=N and full_matrices=False + # U: (M, N), S: N, Vh_full: (N, N), Vh: (N, N) + U, S, Vh_full = linalg.svd(X, full_matrices=(n_samples < n_features)) + K = len(S) + eigen_vals_ = S**2 + eigen_vals_full = np.zeros(n_features, dtype=dtype) + eigen_vals_full[0:K] = eigen_vals_ + Vh = Vh_full[0:K, :] + + # Convergence loop of the bayesian ridge regression + for iter_ in range(self.max_iter): + # update posterior mean coef_ based on alpha_ and lambda_ and + # compute corresponding sse (sum of squared errors) + coef_, sse_ = self._update_coef_( + X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ + ) + if self.compute_score: + # compute the log marginal likelihood + s = self._log_marginal_likelihood( + n_samples, + n_features, + sw_sum, + eigen_vals_, + alpha_, + lambda_, + coef_, + sse_, + ) + self.scores_.append(s) + + # Update alpha and lambda according to (MacKay, 1992) + gamma_ = np.sum((alpha_ * eigen_vals_) / (lambda_ + alpha_ * eigen_vals_)) + lambda_ = (gamma_ + 2 * lambda_1) / (np.sum(coef_**2) + 2 * lambda_2) + alpha_ = (sw_sum - gamma_ + 2 * alpha_1) / (sse_ + 2 * alpha_2) + + # Check for convergence + if iter_ != 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: + if verbose: + print("Convergence after ", str(iter_), " iterations") + break + coef_old_ = np.copy(coef_) + + self.n_iter_ = iter_ + 1 + + # return regularization parameters and corresponding posterior mean, + # log marginal likelihood and posterior covariance + self.alpha_ = alpha_ + self.lambda_ = lambda_ + self.coef_, sse_ = self._update_coef_( + X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ + ) + if self.compute_score: + # compute the log marginal likelihood + s = self._log_marginal_likelihood( + n_samples, + n_features, + sw_sum, + eigen_vals_, + alpha_, + lambda_, + coef_, + sse_, + ) + self.scores_.append(s) + self.scores_ = np.array(self.scores_) + + # posterior covariance + self.sigma_ = np.dot( + Vh_full.T, Vh_full / (alpha_ * eigen_vals_full + lambda_)[:, np.newaxis] + ) + + self._set_intercept(X_offset_, y_offset_, X_scale_) + + return self + + def predict(self, X, return_std=False): + """Predict using the linear model. + + In addition to the mean of the predictive distribution, also its + standard deviation can be returned. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Samples. + + return_std : bool, default=False + Whether to return the standard deviation of posterior prediction. + + Returns + ------- + y_mean : array-like of shape (n_samples,) + Mean of predictive distribution of query points. + + y_std : array-like of shape (n_samples,) + Standard deviation of predictive distribution of query points. + """ + y_mean = self._decision_function(X) + if not return_std: + return y_mean + else: + sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1) + y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_)) + return y_mean, y_std + + def _update_coef_( + self, X, y, n_samples, n_features, XT_y, U, Vh, eigen_vals_, alpha_, lambda_ + ): + """Update posterior mean and compute corresponding sse (sum of squared errors). + + Posterior mean is given by coef_ = scaled_sigma_ * X.T * y where + scaled_sigma_ = (lambda_/alpha_ * np.eye(n_features) + + np.dot(X.T, X))^-1 + """ + + if n_samples > n_features: + coef_ = np.linalg.multi_dot( + [Vh.T, Vh / (eigen_vals_ + lambda_ / alpha_)[:, np.newaxis], XT_y] + ) + else: + coef_ = np.linalg.multi_dot( + [X.T, U / (eigen_vals_ + lambda_ / alpha_)[None, :], U.T, y] + ) + + # Note: we do not need to explicitly use the weights in this sum because + # y and X were preprocessed by _rescale_data to handle the weights. + sse_ = np.sum((y - np.dot(X, coef_)) ** 2) + + return coef_, sse_ + + def _log_marginal_likelihood( + self, n_samples, n_features, sw_sum, eigen_vals, alpha_, lambda_, coef, sse + ): + """Log marginal likelihood.""" + alpha_1 = self.alpha_1 + alpha_2 = self.alpha_2 + lambda_1 = self.lambda_1 + lambda_2 = self.lambda_2 + + # compute the log of the determinant of the posterior covariance. + # posterior covariance is given by + # sigma = (lambda_ * np.eye(n_features) + alpha_ * np.dot(X.T, X))^-1 + if n_samples > n_features: + logdet_sigma = -np.sum(np.log(lambda_ + alpha_ * eigen_vals)) + else: + logdet_sigma = np.full(n_features, lambda_, dtype=np.array(lambda_).dtype) + logdet_sigma[:n_samples] += alpha_ * eigen_vals + logdet_sigma = -np.sum(np.log(logdet_sigma)) + + score = lambda_1 * log(lambda_) - lambda_2 * lambda_ + score += alpha_1 * log(alpha_) - alpha_2 * alpha_ + score += 0.5 * ( + n_features * log(lambda_) + + sw_sum * log(alpha_) + - alpha_ * sse + - lambda_ * np.sum(coef**2) + + logdet_sigma + - sw_sum * log(2 * np.pi) + ) + + return score + + +############################################################################### +# ARD (Automatic Relevance Determination) regression + + +class ARDRegression(RegressorMixin, LinearModel): + """Bayesian ARD regression. + + Fit the weights of a regression model, using an ARD prior. The weights of + the regression model are assumed to be in Gaussian distributions. + Also estimate the parameters lambda (precisions of the distributions of the + weights) and alpha (precision of the distribution of the noise). + The estimation is done by an iterative procedures (Evidence Maximization) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + max_iter : int, default=300 + Maximum number of iterations. + + .. versionchanged:: 1.3 + + tol : float, default=1e-3 + Stop the algorithm if w has converged. + + alpha_1 : float, default=1e-6 + Hyper-parameter : shape parameter for the Gamma distribution prior + over the alpha parameter. + + alpha_2 : float, default=1e-6 + Hyper-parameter : inverse scale parameter (rate parameter) for the + Gamma distribution prior over the alpha parameter. + + lambda_1 : float, default=1e-6 + Hyper-parameter : shape parameter for the Gamma distribution prior + over the lambda parameter. + + lambda_2 : float, default=1e-6 + Hyper-parameter : inverse scale parameter (rate parameter) for the + Gamma distribution prior over the lambda parameter. + + compute_score : bool, default=False + If True, compute the objective function at each step of the model. + + threshold_lambda : float, default=10 000 + Threshold for removing (pruning) weights with high precision from + the computation. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + verbose : bool, default=False + Verbose mode when fitting the model. + + Attributes + ---------- + coef_ : array-like of shape (n_features,) + Coefficients of the regression model (mean of distribution) + + alpha_ : float + estimated precision of the noise. + + lambda_ : array-like of shape (n_features,) + estimated precisions of the weights. + + sigma_ : array-like of shape (n_features, n_features) + estimated variance-covariance matrix of the weights + + scores_ : float + if computed, value of the objective function (to be maximized) + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + + .. versionadded:: 1.3 + + intercept_ : float + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + + X_offset_ : float + If `fit_intercept=True`, offset subtracted for centering data to a + zero mean. Set to np.zeros(n_features) otherwise. + + X_scale_ : float + Set to np.ones(n_features). + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + BayesianRidge : Bayesian ridge regression. + + References + ---------- + D. J. C. MacKay, Bayesian nonlinear modeling for the prediction + competition, ASHRAE Transactions, 1994. + + R. Salakhutdinov, Lecture notes on Statistical Machine Learning, + http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=15 + Their beta is our ``self.alpha_`` + Their alpha is our ``self.lambda_`` + ARD is a little different than the slide: only dimensions/features for + which ``self.lambda_ < self.threshold_lambda`` are kept and the rest are + discarded. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.ARDRegression() + >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) + ARDRegression() + >>> clf.predict([[1, 1]]) + array([1.]) + + - :ref:`sphx_glr_auto_examples_linear_model_plot_ard.py` demonstrates ARD + Regression. + - :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` + showcases ARD Regression alongside Lasso and Elastic-Net for sparse, + correlated signals, in the presence of noise. + """ + + _parameter_constraints: dict = { + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "alpha_1": [Interval(Real, 0, None, closed="left")], + "alpha_2": [Interval(Real, 0, None, closed="left")], + "lambda_1": [Interval(Real, 0, None, closed="left")], + "lambda_2": [Interval(Real, 0, None, closed="left")], + "compute_score": ["boolean"], + "threshold_lambda": [Interval(Real, 0, None, closed="left")], + "fit_intercept": ["boolean"], + "copy_X": ["boolean"], + "verbose": ["verbose"], + } + + def __init__( + self, + *, + max_iter=300, + tol=1.0e-3, + alpha_1=1.0e-6, + alpha_2=1.0e-6, + lambda_1=1.0e-6, + lambda_2=1.0e-6, + compute_score=False, + threshold_lambda=1.0e4, + fit_intercept=True, + copy_X=True, + verbose=False, + ): + self.max_iter = max_iter + self.tol = tol + self.fit_intercept = fit_intercept + self.alpha_1 = alpha_1 + self.alpha_2 = alpha_2 + self.lambda_1 = lambda_1 + self.lambda_2 = lambda_2 + self.compute_score = compute_score + self.threshold_lambda = threshold_lambda + self.copy_X = copy_X + self.verbose = verbose + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit the model according to the given training data and parameters. + + Iterative procedure to maximize the evidence + + Parameters + ---------- + X : array-like of 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 of shape (n_samples,) + Target values (integers). Will be cast to X's dtype if necessary. + + Returns + ------- + self : object + Fitted estimator. + """ + X, y = validate_data( + self, + X, + y, + dtype=[np.float64, np.float32], + force_writeable=True, + y_numeric=True, + ensure_min_samples=2, + ) + dtype = X.dtype + + n_samples, n_features = X.shape + coef_ = np.zeros(n_features, dtype=dtype) + + X, y, X_offset_, y_offset_, X_scale_ = _preprocess_data( + X, y, fit_intercept=self.fit_intercept, copy=self.copy_X + ) + + self.X_offset_ = X_offset_ + self.X_scale_ = X_scale_ + + # Launch the convergence loop + keep_lambda = np.ones(n_features, dtype=bool) + + lambda_1 = self.lambda_1 + lambda_2 = self.lambda_2 + alpha_1 = self.alpha_1 + alpha_2 = self.alpha_2 + verbose = self.verbose + + # Initialization of the values of the parameters + eps = np.finfo(np.float64).eps + # Add `eps` in the denominator to omit division by zero if `np.var(y)` + # is zero. + # Explicitly set dtype to avoid unintended type promotion with numpy 2. + alpha_ = np.asarray(1.0 / (np.var(y) + eps), dtype=dtype) + lambda_ = np.ones(n_features, dtype=dtype) + + self.scores_ = list() + coef_old_ = None + + def update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_): + coef_[keep_lambda] = alpha_ * np.linalg.multi_dot( + [sigma_, X[:, keep_lambda].T, y] + ) + return coef_ + + update_sigma = ( + self._update_sigma + if n_samples >= n_features + else self._update_sigma_woodbury + ) + # Iterative procedure of ARDRegression + for iter_ in range(self.max_iter): + sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda) + coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_) + + # Update alpha and lambda + sse_ = np.sum((y - np.dot(X, coef_)) ** 2) + gamma_ = 1.0 - lambda_[keep_lambda] * np.diag(sigma_) + lambda_[keep_lambda] = (gamma_ + 2.0 * lambda_1) / ( + (coef_[keep_lambda]) ** 2 + 2.0 * lambda_2 + ) + alpha_ = (n_samples - gamma_.sum() + 2.0 * alpha_1) / (sse_ + 2.0 * alpha_2) + + # Prune the weights with a precision over a threshold + keep_lambda = lambda_ < self.threshold_lambda + coef_[~keep_lambda] = 0 + + # Compute the objective function + if self.compute_score: + s = (lambda_1 * np.log(lambda_) - lambda_2 * lambda_).sum() + s += alpha_1 * log(alpha_) - alpha_2 * alpha_ + s += 0.5 * ( + fast_logdet(sigma_) + + n_samples * log(alpha_) + + np.sum(np.log(lambda_)) + ) + s -= 0.5 * (alpha_ * sse_ + (lambda_ * coef_**2).sum()) + self.scores_.append(s) + + # Check for convergence + if iter_ > 0 and np.sum(np.abs(coef_old_ - coef_)) < self.tol: + if verbose: + print("Converged after %s iterations" % iter_) + break + coef_old_ = np.copy(coef_) + + if not keep_lambda.any(): + break + + self.n_iter_ = iter_ + 1 + + if keep_lambda.any(): + # update sigma and mu using updated params from the last iteration + sigma_ = update_sigma(X, alpha_, lambda_, keep_lambda) + coef_ = update_coeff(X, y, coef_, alpha_, keep_lambda, sigma_) + else: + sigma_ = np.array([]).reshape(0, 0) + + self.coef_ = coef_ + self.alpha_ = alpha_ + self.sigma_ = sigma_ + self.lambda_ = lambda_ + self._set_intercept(X_offset_, y_offset_, X_scale_) + return self + + def _update_sigma_woodbury(self, X, alpha_, lambda_, keep_lambda): + # See slides as referenced in the docstring note + # this function is used when n_samples < n_features and will invert + # a matrix of shape (n_samples, n_samples) making use of the + # woodbury formula: + # https://en.wikipedia.org/wiki/Woodbury_matrix_identity + n_samples = X.shape[0] + X_keep = X[:, keep_lambda] + inv_lambda = 1 / lambda_[keep_lambda].reshape(1, -1) + sigma_ = pinvh( + np.eye(n_samples, dtype=X.dtype) / alpha_ + + np.dot(X_keep * inv_lambda, X_keep.T) + ) + sigma_ = np.dot(sigma_, X_keep * inv_lambda) + sigma_ = -np.dot(inv_lambda.reshape(-1, 1) * X_keep.T, sigma_) + sigma_[np.diag_indices(sigma_.shape[1])] += 1.0 / lambda_[keep_lambda] + return sigma_ + + def _update_sigma(self, X, alpha_, lambda_, keep_lambda): + # See slides as referenced in the docstring note + # this function is used when n_samples >= n_features and will + # invert a matrix of shape (n_features, n_features) + X_keep = X[:, keep_lambda] + gram = np.dot(X_keep.T, X_keep) + eye = np.eye(gram.shape[0], dtype=X.dtype) + sigma_inv = lambda_[keep_lambda] * eye + alpha_ * gram + sigma_ = pinvh(sigma_inv) + return sigma_ + + def predict(self, X, return_std=False): + """Predict using the linear model. + + In addition to the mean of the predictive distribution, also its + standard deviation can be returned. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Samples. + + return_std : bool, default=False + Whether to return the standard deviation of posterior prediction. + + Returns + ------- + y_mean : array-like of shape (n_samples,) + Mean of predictive distribution of query points. + + y_std : array-like of shape (n_samples,) + Standard deviation of predictive distribution of query points. + """ + y_mean = self._decision_function(X) + if return_std is False: + return y_mean + else: + col_index = self.lambda_ < self.threshold_lambda + X = _safe_indexing(X, indices=col_index, axis=1) + sigmas_squared_data = (np.dot(X, self.sigma_) * X).sum(axis=1) + y_std = np.sqrt(sigmas_squared_data + (1.0 / self.alpha_)) + return y_mean, y_std diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx new file mode 100644 index 0000000000000000000000000000000000000000..ce598ebb011d216ffdbbd70cbed507ad14bdb848 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_cd_fast.pyx @@ -0,0 +1,962 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from libc.math cimport fabs +import numpy as np + +from cython cimport floating +import warnings +from ..exceptions import ConvergenceWarning + +from ..utils._cython_blas cimport ( + _axpy, _dot, _asum, _gemv, _nrm2, _copy, _scal +) +from ..utils._cython_blas cimport ColMajor, Trans, NoTrans +from ..utils._typedefs cimport uint32_t +from ..utils._random cimport our_rand_r + + +# The following two functions are shamelessly copied from the tree code. + +cdef enum: + # Max value for our rand_r replacement (near the bottom). + # We don't use RAND_MAX because it's different across platforms and + # particularly tiny on Windows/MSVC. + # It corresponds to the maximum representable value for + # 32-bit signed integers (i.e. 2^31 - 1). + RAND_R_MAX = 2147483647 + + +cdef inline uint32_t rand_int(uint32_t end, uint32_t* random_state) noexcept nogil: + """Generate a random integer in [0; end).""" + return our_rand_r(random_state) % end + + +cdef inline floating fmax(floating x, floating y) noexcept nogil: + if x > y: + return x + return y + + +cdef inline floating fsign(floating f) noexcept nogil: + if f == 0: + return 0 + elif f > 0: + return 1.0 + else: + return -1.0 + + +cdef floating abs_max(int n, const floating* a) noexcept nogil: + """np.max(np.abs(a))""" + cdef int i + cdef floating m = fabs(a[0]) + cdef floating d + for i in range(1, n): + d = fabs(a[i]) + if d > m: + m = d + return m + + +cdef floating max(int n, floating* a) noexcept nogil: + """np.max(a)""" + cdef int i + cdef floating m = a[0] + cdef floating d + for i in range(1, n): + d = a[i] + if d > m: + m = d + return m + + +cdef floating diff_abs_max(int n, const floating* a, floating* b) noexcept nogil: + """np.max(np.abs(a - b))""" + cdef int i + cdef floating m = fabs(a[0] - b[0]) + cdef floating d + for i in range(1, n): + d = fabs(a[i] - b[i]) + if d > m: + m = d + return m + + +message_conv = ( + "Objective did not converge. You might want to increase " + "the number of iterations, check the scale of the " + "features or consider increasing regularisation." +) + + +message_ridge = ( + "Linear regression models with a zero l1 penalization " + "strength are more efficiently fitted using one of the " + "solvers implemented in " + "sklearn.linear_model.Ridge/RidgeCV instead." +) + + +def enet_coordinate_descent( + floating[::1] w, + floating alpha, + floating beta, + const floating[::1, :] X, + const floating[::1] y, + unsigned int max_iter, + floating tol, + object rng, + bint random=0, + bint positive=0 +): + """Cython version of the coordinate descent algorithm + for Elastic-Net regression + + We minimize + + (1/2) * norm(y - X w, 2)^2 + alpha norm(w, 1) + (beta/2) norm(w, 2)^2 + + Returns + ------- + w : ndarray of shape (n_features,) + ElasticNet coefficients. + gap : float + Achieved dual gap. + tol : float + Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap. + n_iter : int + Number of coordinate descent iterations. + """ + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + # get the data information into easy vars + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + + # compute norms of the columns of X + cdef floating[::1] norm_cols_X = np.square(X).sum(axis=0) + + # initial value of the residuals + cdef floating[::1] R = np.empty(n_samples, dtype=dtype) + cdef floating[::1] XtA = np.empty(n_features, dtype=dtype) + + cdef floating tmp + cdef floating w_ii + cdef floating d_w_max + cdef floating w_max + cdef floating d_w_ii + cdef floating gap = tol + 1.0 + cdef floating d_w_tol = tol + cdef floating dual_norm_XtA + cdef floating R_norm2 + cdef floating w_norm2 + cdef floating l1_norm + cdef floating const_ + cdef floating A_norm2 + cdef unsigned int ii + cdef unsigned int n_iter = 0 + cdef unsigned int f_iter + cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef uint32_t* rand_r_state = &rand_r_state_seed + + if alpha == 0 and beta == 0: + warnings.warn("Coordinate descent with no regularization may lead to " + "unexpected results and is discouraged.") + + with nogil: + # R = y - np.dot(X, w) + _copy(n_samples, &y[0], 1, &R[0], 1) + _gemv(ColMajor, NoTrans, n_samples, n_features, -1.0, &X[0, 0], + n_samples, &w[0], 1, 1.0, &R[0], 1) + + # tol *= np.dot(y, y) + tol *= _dot(n_samples, &y[0], 1, &y[0], 1) + + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if norm_cols_X[ii] == 0.0: + continue + + w_ii = w[ii] # Store previous value + + if w_ii != 0.0: + # R += w_ii * X[:,ii] + _axpy(n_samples, w_ii, &X[0, ii], 1, &R[0], 1) + + # tmp = (X[:,ii]*R).sum() + tmp = _dot(n_samples, &X[0, ii], 1, &R[0], 1) + + if positive and tmp < 0: + w[ii] = 0.0 + else: + w[ii] = (fsign(tmp) * fmax(fabs(tmp) - alpha, 0) + / (norm_cols_X[ii] + beta)) + + if w[ii] != 0.0: + # R -= w[ii] * X[:,ii] # Update residual + _axpy(n_samples, -w[ii], &X[0, ii], 1, &R[0], 1) + + # update the maximum absolute coefficient update + d_w_ii = fabs(w[ii] - w_ii) + d_w_max = fmax(d_w_max, d_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 the tolerance: check the duality gap as ultimate + # stopping criterion + + # XtA = np.dot(X.T, R) - beta * w + _copy(n_features, &w[0], 1, &XtA[0], 1) + _gemv(ColMajor, Trans, + n_samples, n_features, 1.0, &X[0, 0], n_samples, + &R[0], 1, + -beta, &XtA[0], 1) + + if positive: + dual_norm_XtA = max(n_features, &XtA[0]) + else: + 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) + + # w_norm2 = np.dot(w, w) + w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1) + + if (dual_norm_XtA > alpha): + const_ = alpha / dual_norm_XtA + A_norm2 = R_norm2 * (const_ ** 2) + gap = 0.5 * (R_norm2 + A_norm2) + else: + const_ = 1.0 + gap = R_norm2 + + l1_norm = _asum(n_features, &w[0], 1) + + gap += (alpha * l1_norm + - const_ * _dot(n_samples, &R[0], 1, &y[0], 1) # np.dot(R.T, y) + + 0.5 * beta * (1 + const_ ** 2) * (w_norm2)) + + if gap < tol: + # return if we reached desired tolerance + break + + else: + # for/else, runs if for doesn't end with a `break` + with gil: + message = ( + message_conv + + f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}" + ) + if alpha < np.finfo(np.float64).eps: + message += "\n" + message_ridge + warnings.warn(message, ConvergenceWarning) + + return np.asarray(w), gap, tol, n_iter + 1 + + +def sparse_enet_coordinate_descent( + floating[::1] w, + floating alpha, + floating beta, + const floating[::1] X_data, + const int[::1] X_indices, + const int[::1] X_indptr, + const floating[::1] y, + const floating[::1] sample_weight, + const floating[::1] X_mean, + unsigned 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 - 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). + + Returns + ------- + w : ndarray of shape (n_features,) + ElasticNet coefficients. + gap : float + Achieved dual gap. + tol : float + Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap. + n_iter : int + Number of coordinate descent iterations. + """ + # 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 * y + # R = sample_weight * residual + # norm_cols_X = np.sum(sample_weight * (X - X_mean)**2, axis=0) + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + # get the data information into easy vars + cdef unsigned int n_samples = y.shape[0] + cdef unsigned int n_features = w.shape[0] + + # compute norms of the columns of X + cdef floating[:] norm_cols_X = np.zeros(n_features, dtype=dtype) + + # initial value of the residuals + # R = y - Zw, weighted version R = sample_weight * (y - Zw) + cdef floating[::1] R + cdef floating[::1] XtA = np.empty(n_features, dtype=dtype) + cdef const floating[::1] yw + + cdef floating tmp + cdef floating w_ii + cdef floating d_w_max + cdef floating w_max + cdef floating d_w_ii + cdef floating gap = tol + 1.0 + cdef floating d_w_tol = tol + cdef floating dual_norm_XtA + cdef floating X_mean_ii + cdef floating R_sum = 0.0 + cdef floating R_norm2 + cdef floating w_norm2 + cdef floating l1_norm + cdef floating const_ + cdef floating A_norm2 + cdef floating normalize_sum + cdef unsigned int ii + cdef unsigned int jj + cdef unsigned int n_iter = 0 + cdef unsigned int f_iter + cdef unsigned int startptr = X_indptr[0] + cdef unsigned int endptr + 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 + cdef int kk + + 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() + for ii in range(n_features): + if X_mean[ii]: + center = True + break + + # R = y - np.dot(X, w) + for ii in range(n_features): + X_mean_ii = X_mean[ii] + endptr = X_indptr[ii + 1] + normalize_sum = 0.0 + w_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 + R_sum += R[jj] + else: + # R = sw * (y - np.dot(X, w)) + 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 + R_sum += R[jj] + norm_cols_X[ii] = normalize_sum + startptr = endptr + + # Note: No need to update R_sum from here on because the update terms cancel + # each other: w_ii * np.sum(X[:,ii] - X_mean[ii]) = 0. R_sum is only ever + # needed and calculated if X_mean is provided. + + # tol *= np.dot(y, y) + # with sample weights: tol *= y @ (sw * y) + tol *= _dot(n_samples, &y[0], 1, &yw[0], 1) + + for n_iter in range(max_iter): + + w_max = 0.0 + d_w_max = 0.0 + + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if norm_cols_X[ii] == 0.0: + continue + + startptr = X_indptr[ii] + endptr = X_indptr[ii + 1] + w_ii = w[ii] # Store previous value + X_mean_ii = X_mean[ii] + + if w_ii != 0.0: + # R += w_ii * X[:,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 + for jj in range(startptr, endptr): + tmp += R[X_indices[jj]] * X_data[jj] + + if center: + tmp -= R_sum * X_mean_ii + + if positive and tmp < 0.0: + w[ii] = 0.0 + else: + w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + / (norm_cols_X[ii] + beta) + + if w[ii] != 0.0: + # R -= w[ii] * X[:,ii] # Update residual + 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) + d_w_max = fmax(d_w_max, d_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 + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # XtA = X.T @ R - beta * w + # sparse X.T / dense R dot product + for ii in range(n_features): + XtA[ii] = 0.0 + for kk in range(X_indptr[ii], X_indptr[ii + 1]): + XtA[ii] += X_data[kk] * R[X_indices[kk]] + + if center: + XtA[ii] -= X_mean[ii] * R_sum + XtA[ii] -= beta * w[ii] + + if positive: + dual_norm_XtA = max(n_features, &XtA[0]) + else: + dual_norm_XtA = abs_max(n_features, &XtA[0]) + + # R_norm2 = np.dot(R, R) + 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) + if (dual_norm_XtA > alpha): + const_ = alpha / dual_norm_XtA + A_norm2 = R_norm2 * const_**2 + gap = 0.5 * (R_norm2 + A_norm2) + else: + const_ = 1.0 + gap = R_norm2 + + l1_norm = _asum(n_features, &w[0], 1) + + gap += (alpha * l1_norm + - const_ * _dot(n_samples, &R[0], 1, &y[0], 1) # np.dot(R.T, y) + + 0.5 * beta * (1 + const_ ** 2) * w_norm2) + + if gap < tol: + # return if we reached desired tolerance + break + + else: + # for/else, runs if for doesn't end with a `break` + with gil: + message = ( + message_conv + + f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}" + ) + if alpha < np.finfo(np.float64).eps: + message += "\n" + message_ridge + warnings.warn(message, ConvergenceWarning) + + return np.asarray(w), gap, tol, n_iter + 1 + + +def enet_coordinate_descent_gram( + floating[::1] w, + floating alpha, + floating beta, + const floating[:, ::1] Q, + const floating[::1] q, + const floating[:] y, + unsigned int max_iter, + floating tol, + object rng, + bint random=0, + bint positive=0 +): + """Cython version of the coordinate descent algorithm + for Elastic-Net regression + + We minimize + + (1/2) * w^T Q w - q^T w + alpha norm(w, 1) + (beta/2) * norm(w, 2)^2 + + which amount to the Elastic-Net problem when: + Q = X^T X (Gram matrix) + q = X^T y + + Returns + ------- + w : ndarray of shape (n_features,) + ElasticNet coefficients. + gap : float + Achieved dual gap. + tol : float + Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap. + n_iter : int + Number of coordinate descent iterations. + """ + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + # get the data information into easy vars + cdef unsigned int n_features = Q.shape[0] + + # initial value "Q w" which will be kept of up to date in the iterations + cdef floating[:] H = np.dot(Q, w) + + cdef floating[:] XtA = np.zeros(n_features, dtype=dtype) + cdef floating tmp + cdef floating w_ii + cdef floating d_w_max + cdef floating w_max + cdef floating d_w_ii + cdef floating q_dot_w + cdef floating w_norm2 + cdef floating gap = tol + 1.0 + cdef floating d_w_tol = tol + cdef floating dual_norm_XtA + cdef unsigned int ii + cdef unsigned int n_iter = 0 + cdef unsigned int f_iter + cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef uint32_t* rand_r_state = &rand_r_state_seed + + cdef floating y_norm2 = np.dot(y, y) + cdef floating* w_ptr = &w[0] + cdef const floating* Q_ptr = &Q[0, 0] + cdef const floating* q_ptr = &q[0] + cdef floating* H_ptr = &H[0] + cdef floating* XtA_ptr = &XtA[0] + tol = tol * y_norm2 + + if alpha == 0: + warnings.warn( + "Coordinate descent without L1 regularization may " + "lead to unexpected results and is discouraged. " + "Set l1_ratio > 0 to add L1 regularization." + ) + + with nogil: + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if Q[ii, ii] == 0.0: + continue + + w_ii = w[ii] # Store previous value + + if w_ii != 0.0: + # H -= w_ii * Q[ii] + _axpy(n_features, -w_ii, Q_ptr + ii * n_features, 1, + H_ptr, 1) + + tmp = q[ii] - H[ii] + + if positive and tmp < 0: + w[ii] = 0.0 + else: + w[ii] = fsign(tmp) * fmax(fabs(tmp) - alpha, 0) \ + / (Q[ii, ii] + beta) + + if w[ii] != 0.0: + # H += w[ii] * Q[ii] # Update H = X.T X w + _axpy(n_features, w[ii], Q_ptr + ii * n_features, 1, + H_ptr, 1) + + # 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 + + if fabs(w[ii]) > w_max: + 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 + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # q_dot_w = np.dot(w, q) + q_dot_w = _dot(n_features, w_ptr, 1, q_ptr, 1) + + for ii in range(n_features): + XtA[ii] = q[ii] - H[ii] - beta * w[ii] + if positive: + dual_norm_XtA = max(n_features, XtA_ptr) + else: + dual_norm_XtA = abs_max(n_features, XtA_ptr) + + # temp = np.sum(w * H) + tmp = 0.0 + for ii in range(n_features): + tmp += w[ii] * H[ii] + R_norm2 = y_norm2 + tmp - 2.0 * q_dot_w + + # w_norm2 = np.dot(w, w) + w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1) + + if (dual_norm_XtA > alpha): + const_ = alpha / dual_norm_XtA + A_norm2 = R_norm2 * (const_ ** 2) + gap = 0.5 * (R_norm2 + A_norm2) + else: + const_ = 1.0 + gap = R_norm2 + + # The call to asum is equivalent to the L1 norm of w + gap += ( + alpha * _asum(n_features, &w[0], 1) + - const_ * y_norm2 + + const_ * q_dot_w + + 0.5 * beta * (1 + const_ ** 2) * w_norm2 + ) + + if gap < tol: + # return if we reached desired tolerance + break + + else: + # for/else, runs if for doesn't end with a `break` + with gil: + message = ( + message_conv + + f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}" + ) + warnings.warn(message, ConvergenceWarning) + + return np.asarray(w), gap, tol, n_iter + 1 + + +def enet_coordinate_descent_multi_task( + const floating[::1, :] W, + floating l1_reg, + floating l2_reg, + const floating[::1, :] X, + const floating[::1, :] Y, + unsigned int max_iter, + floating tol, + object rng, + bint random=0 +): + """Cython version of the coordinate descent algorithm + for Elastic-Net multi-task regression + + We minimize + + 0.5 * norm(Y - X W.T, 2)^2 + l1_reg ||W.T||_21 + 0.5 * l2_reg norm(W.T, 2)^2 + + Returns + ------- + W : ndarray of shape (n_tasks, n_features) + ElasticNet coefficients. + gap : float + Achieved dual gap. + tol : float + Equals input `tol` times `np.dot(y, y)`. The tolerance used for the dual gap. + n_iter : int + Number of coordinate descent iterations. + """ + + if floating is float: + dtype = np.float32 + else: + dtype = np.float64 + + # get the data information into easy vars + cdef unsigned int n_samples = X.shape[0] + cdef unsigned int n_features = X.shape[1] + cdef unsigned int n_tasks = Y.shape[1] + + # to store XtA + cdef floating[:, ::1] XtA = np.zeros((n_features, n_tasks), dtype=dtype) + cdef floating XtA_axis1norm + cdef floating dual_norm_XtA + + # initial value of the residuals + cdef floating[::1, :] R = np.zeros((n_samples, n_tasks), dtype=dtype, order='F') + + cdef floating[::1] norm_cols_X = np.zeros(n_features, dtype=dtype) + cdef floating[::1] tmp = np.zeros(n_tasks, dtype=dtype) + cdef floating[::1] w_ii = np.zeros(n_tasks, dtype=dtype) + cdef floating d_w_max + cdef floating w_max + cdef floating d_w_ii + cdef floating nn + cdef floating W_ii_abs_max + cdef floating gap = tol + 1.0 + cdef floating d_w_tol = tol + cdef floating R_norm + cdef floating w_norm + cdef floating ry_sum + cdef floating l21_norm + cdef unsigned int ii + cdef unsigned int jj + cdef unsigned int n_iter = 0 + cdef unsigned int f_iter + cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX) + cdef uint32_t* rand_r_state = &rand_r_state_seed + + cdef const floating* X_ptr = &X[0, 0] + cdef const floating* Y_ptr = &Y[0, 0] + + if l1_reg == 0: + warnings.warn( + "Coordinate descent with l1_reg=0 may lead to unexpected" + " results and is discouraged." + ) + + with nogil: + # norm_cols_X = (np.asarray(X) ** 2).sum(axis=0) + for ii in range(n_features): + norm_cols_X[ii] = _nrm2(n_samples, X_ptr + ii * n_samples, 1) ** 2 + + # R = Y - np.dot(X, W.T) + _copy(n_samples * n_tasks, Y_ptr, 1, &R[0, 0], 1) + for ii in range(n_features): + for jj in range(n_tasks): + if W[jj, ii] != 0: + _axpy(n_samples, -W[jj, ii], X_ptr + ii * n_samples, 1, + &R[0, jj], 1) + + # tol = tol * linalg.norm(Y, ord='fro') ** 2 + tol = tol * _nrm2(n_samples * n_tasks, Y_ptr, 1) ** 2 + + for n_iter in range(max_iter): + w_max = 0.0 + d_w_max = 0.0 + for f_iter in range(n_features): # Loop over coordinates + if random: + ii = rand_int(n_features, rand_r_state) + else: + ii = f_iter + + if norm_cols_X[ii] == 0.0: + continue + + # w_ii = W[:, ii] # Store previous value + _copy(n_tasks, &W[0, ii], 1, &w_ii[0], 1) + + # Using Numpy: + # R += np.dot(X[:, ii][:, None], w_ii[None, :]) # rank 1 update + # Using Blas Level2: + # _ger(RowMajor, n_samples, n_tasks, 1.0, + # &X[0, ii], 1, + # &w_ii[0], 1, &R[0, 0], n_tasks) + # Using Blas Level1 and for loop to avoid slower threads + # for such small vectors + for jj in range(n_tasks): + if w_ii[jj] != 0: + _axpy(n_samples, w_ii[jj], X_ptr + ii * n_samples, 1, + &R[0, jj], 1) + + # Using numpy: + # tmp = np.dot(X[:, ii][None, :], R).ravel() + # Using BLAS Level 2: + # _gemv(RowMajor, Trans, n_samples, n_tasks, 1.0, &R[0, 0], + # n_tasks, &X[0, ii], 1, 0.0, &tmp[0], 1) + # Using BLAS Level 1 (faster for small vectors like here): + for jj in range(n_tasks): + tmp[jj] = _dot(n_samples, X_ptr + ii * n_samples, 1, + &R[0, jj], 1) + + # nn = sqrt(np.sum(tmp ** 2)) + nn = _nrm2(n_tasks, &tmp[0], 1) + + # W[:, ii] = tmp * fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg) + _copy(n_tasks, &tmp[0], 1, &W[0, ii], 1) + _scal(n_tasks, fmax(1. - l1_reg / nn, 0) / (norm_cols_X[ii] + l2_reg), + &W[0, ii], 1) + + # Using numpy: + # R -= np.dot(X[:, ii][:, None], W[:, ii][None, :]) + # Using BLAS Level 2: + # Update residual : rank 1 update + # _ger(RowMajor, n_samples, n_tasks, -1.0, + # &X[0, ii], 1, &W[0, ii], 1, + # &R[0, 0], n_tasks) + # Using BLAS Level 1 (faster for small vectors like here): + for jj in range(n_tasks): + if W[jj, ii] != 0: + _axpy(n_samples, -W[jj, ii], X_ptr + ii * n_samples, 1, + &R[0, jj], 1) + + # update the maximum absolute coefficient update + d_w_ii = diff_abs_max(n_tasks, &W[0, ii], &w_ii[0]) + + if d_w_ii > d_w_max: + d_w_max = d_w_ii + + W_ii_abs_max = abs_max(n_tasks, &W[0, ii]) + if W_ii_abs_max > w_max: + w_max = W_ii_abs_max + + 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 + # the tolerance: check the duality gap as ultimate stopping + # criterion + + # XtA = np.dot(X.T, R) - l2_reg * W.T + for ii in range(n_features): + for jj in range(n_tasks): + XtA[ii, jj] = _dot( + n_samples, X_ptr + ii * n_samples, 1, &R[0, jj], 1 + ) - l2_reg * W[jj, ii] + + # dual_norm_XtA = np.max(np.sqrt(np.sum(XtA ** 2, axis=1))) + dual_norm_XtA = 0.0 + for ii in range(n_features): + # np.sqrt(np.sum(XtA ** 2, axis=1)) + XtA_axis1norm = _nrm2(n_tasks, &XtA[ii, 0], 1) + if XtA_axis1norm > dual_norm_XtA: + dual_norm_XtA = XtA_axis1norm + + # TODO: use squared L2 norm directly + # R_norm = linalg.norm(R, ord='fro') + # w_norm = linalg.norm(W, ord='fro') + R_norm = _nrm2(n_samples * n_tasks, &R[0, 0], 1) + w_norm = _nrm2(n_features * n_tasks, &W[0, 0], 1) + if (dual_norm_XtA > l1_reg): + const_ = l1_reg / dual_norm_XtA + A_norm = R_norm * const_ + gap = 0.5 * (R_norm ** 2 + A_norm ** 2) + else: + const_ = 1.0 + gap = R_norm ** 2 + + # ry_sum = np.sum(R * y) + ry_sum = _dot(n_samples * n_tasks, &R[0, 0], 1, &Y[0, 0], 1) + + # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum() + l21_norm = 0.0 + for ii in range(n_features): + l21_norm += _nrm2(n_tasks, &W[0, ii], 1) + + gap += ( + l1_reg * l21_norm + - const_ * ry_sum + + 0.5 * l2_reg * (1 + const_ ** 2) * (w_norm ** 2) + ) + + if gap <= tol: + # return if we reached desired tolerance + break + else: + # for/else, runs if for doesn't end with a `break` + with gil: + message = ( + message_conv + + f" Duality gap: {gap:.3e}, tolerance: {tol:.3e}" + ) + warnings.warn(message, ConvergenceWarning) + + return np.asarray(W), gap, tol, n_iter + 1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..940ae6f5e3a3010f7fe2f21d28d68f538d893d8c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_coordinate_descent.py @@ -0,0 +1,3403 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import sys +import warnings +from abc import ABC, abstractmethod +from functools import partial +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs +from scipy import sparse + +from sklearn.utils import metadata_routing + +from ..base import MultiOutputMixin, RegressorMixin, _fit_context +from ..model_selection import check_cv +from ..utils import Bunch, check_array, check_scalar +from ..utils._metadata_requests import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + get_routing_for_object, +) +from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params +from ..utils.extmath import safe_sparse_dot +from ..utils.metadata_routing import ( + _routing_enabled, + process_routing, +) +from ..utils.parallel import Parallel, delayed +from ..utils.validation import ( + _check_sample_weight, + check_consistent_length, + check_is_fitted, + check_random_state, + column_or_1d, + has_fit_parameter, + validate_data, +) + +# mypy error: Module 'sklearn.linear_model' has no attribute '_cd_fast' +from . import _cd_fast as cd_fast # type: ignore[attr-defined] +from ._base import LinearModel, _pre_fit, _preprocess_data + + +def _set_order(X, y, order="C"): + """Change the order of X and y if necessary. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + order : {None, 'C', 'F'} + If 'C', dense arrays are returned as C-ordered, sparse matrices in csr + format. If 'F', dense arrays are return as F-ordered, sparse matrices + in csc format. + + Returns + ------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data with guaranteed order. + + y : ndarray of shape (n_samples,) + Target values with guaranteed order. + """ + if order not in [None, "C", "F"]: + raise ValueError( + "Unknown value for order. Got {} instead of None, 'C' or 'F'.".format(order) + ) + sparse_X = sparse.issparse(X) + sparse_y = sparse.issparse(y) + if order is not None: + sparse_format = "csc" if order == "F" else "csr" + if sparse_X: + X = X.asformat(sparse_format, copy=False) + else: + X = np.asarray(X, order=order) + if sparse_y: + y = y.asformat(sparse_format) + else: + y = np.asarray(y, order=order) + return X, y + + +############################################################################### +# Paths functions + + +def _alpha_grid( + X, + y, + Xy=None, + l1_ratio=1.0, + fit_intercept=True, + eps=1e-3, + n_alphas=100, + copy_X=True, + sample_weight=None, +): + """Compute the grid of alpha values for elastic net parameter search + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication + + y : ndarray of shape (n_samples,) or (n_samples, n_outputs) + Target values + + Xy : array-like of shape (n_features,) or (n_features, n_outputs),\ + default=None + Xy = np.dot(X.T, y) that can be precomputed. + + l1_ratio : float, default=1.0 + The elastic net mixing parameter, with ``0 < l1_ratio <= 1``. + For ``l1_ratio = 0`` the penalty is an L2 penalty. (currently not + supported) ``For l1_ratio = 1`` it is an L1 penalty. For + ``0 < l1_ratio <1``, the penalty is a combination of L1 and L2. + + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3`` + + n_alphas : int, default=100 + Number of alphas along the regularization path + + fit_intercept : bool, default=True + Whether to fit an intercept or not + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + sample_weight : ndarray of shape (n_samples,), default=None + """ + if l1_ratio == 0: + raise ValueError( + "Automatic alpha grid generation is not supported for" + " l1_ratio=0. Please supply a grid by providing " + "your estimator with the appropriate `alphas=` " + "argument." + ) + if Xy is not None: + Xyw = Xy + else: + X, y, X_offset, _, _ = _preprocess_data( + X, + y, + fit_intercept=fit_intercept, + copy=copy_X, + sample_weight=sample_weight, + check_input=False, + ) + if sample_weight is not None: + if y.ndim > 1: + yw = y * sample_weight.reshape(-1, 1) + else: + yw = y * sample_weight + else: + yw = y + if sparse.issparse(X): + Xyw = safe_sparse_dot(X.T, yw, dense_output=True) - np.sum(yw) * X_offset + else: + Xyw = np.dot(X.T, yw) + + if Xyw.ndim == 1: + Xyw = Xyw[:, np.newaxis] + if sample_weight is not None: + n_samples = sample_weight.sum() + else: + n_samples = X.shape[0] + alpha_max = np.sqrt(np.sum(Xyw**2, axis=1)).max() / (n_samples * l1_ratio) + + if alpha_max <= np.finfo(np.float64).resolution: + return np.full(n_alphas, np.finfo(np.float64).resolution) + + return np.geomspace(alpha_max, alpha_max * eps, num=n_alphas) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like", "sparse matrix"], + "eps": [Interval(Real, 0, None, closed="neither")], + "n_alphas": [Interval(Integral, 1, None, closed="left")], + "alphas": ["array-like", None], + "precompute": [StrOptions({"auto"}), "boolean", "array-like"], + "Xy": ["array-like", None], + "copy_X": ["boolean"], + "coef_init": ["array-like", None], + "verbose": ["verbose"], + "return_n_iter": ["boolean"], + "positive": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def lasso_path( + X, + y, + *, + eps=1e-3, + n_alphas=100, + alphas=None, + precompute="auto", + Xy=None, + copy_X=True, + coef_init=None, + verbose=False, + return_n_iter=False, + positive=False, + **params, +): + """Compute Lasso path with coordinate descent. + + The Lasso optimization function varies for mono and multi-outputs. + + For mono-output tasks it is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + For multi-output tasks it is:: + + (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21 + + Where:: + + ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication. If ``y`` is mono-output then ``X`` + can be sparse. + + y : {array-like, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_targets) + Target values. + + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path. + + alphas : array-like, default=None + List of alphas where to compute the models. + If ``None`` alphas are set automatically. + + precompute : 'auto', bool or array-like of shape \ + (n_features, n_features), default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + Xy : array-like of shape (n_features,) or (n_features, n_targets),\ + default=None + Xy = np.dot(X.T, y) that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + coef_init : array-like of shape (n_features, ), default=None + The initial values of the coefficients. + + verbose : bool or int, default=False + Amount of verbosity. + + return_n_iter : bool, default=False + Whether to return the number of iterations or not. + + positive : bool, default=False + If set to True, forces coefficients to be positive. + (Only allowed when ``y.ndim == 1``). + + **params : kwargs + Keyword arguments passed to the coordinate descent solver. + + Returns + ------- + alphas : ndarray of shape (n_alphas,) + The alphas along the path where models are computed. + + coefs : ndarray of shape (n_features, n_alphas) or \ + (n_targets, n_features, n_alphas) + Coefficients along the path. + + dual_gaps : ndarray of shape (n_alphas,) + The dual gaps at the end of the optimization for each alpha. + + n_iters : list of int + The number of iterations taken by the coordinate descent optimizer to + reach the specified tolerance for each alpha. + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso path using LARS + algorithm. + Lasso : The Lasso is a linear model that estimates sparse coefficients. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + LassoCV : Lasso linear model with iterative fitting along a regularization + path. + LassoLarsCV : Cross-validated Lasso using the LARS algorithm. + sklearn.decomposition.sparse_encode : Estimator that can be used to + transform signals into sparse linear combination of atoms from a fixed. + + Notes + ----- + For an example, see + :ref:`examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py + `. + + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + + Note that in certain cases, the Lars solver may be significantly + faster to implement this functionality. In particular, linear + interpolation can be used to retrieve model coefficients between the + values output by lars_path + + Examples + -------- + + Comparing lasso_path and lars_path with interpolation: + + >>> import numpy as np + >>> from sklearn.linear_model import lasso_path + >>> X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T + >>> y = np.array([1, 2, 3.1]) + >>> # Use lasso_path to compute a coefficient path + >>> _, coef_path, _ = lasso_path(X, y, alphas=[5., 1., .5]) + >>> print(coef_path) + [[0. 0. 0.46874778] + [0.2159048 0.4425765 0.23689075]] + + >>> # Now use lars_path and 1D linear interpolation to compute the + >>> # same path + >>> from sklearn.linear_model import lars_path + >>> alphas, active, coef_path_lars = lars_path(X, y, method='lasso') + >>> from scipy import interpolate + >>> coef_path_continuous = interpolate.interp1d(alphas[::-1], + ... coef_path_lars[:, ::-1]) + >>> print(coef_path_continuous([5., 1., .5])) + [[0. 0. 0.46915237] + [0.2159048 0.4425765 0.23668876]] + """ + return enet_path( + X, + y, + l1_ratio=1.0, + eps=eps, + n_alphas=n_alphas, + alphas=alphas, + precompute=precompute, + Xy=Xy, + copy_X=copy_X, + coef_init=coef_init, + verbose=verbose, + positive=positive, + return_n_iter=return_n_iter, + **params, + ) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "y": ["array-like", "sparse matrix"], + "l1_ratio": [Interval(Real, 0.0, 1.0, closed="both")], + "eps": [Interval(Real, 0.0, None, closed="neither")], + "n_alphas": [Interval(Integral, 1, None, closed="left")], + "alphas": ["array-like", None], + "precompute": [StrOptions({"auto"}), "boolean", "array-like"], + "Xy": ["array-like", None], + "copy_X": ["boolean"], + "coef_init": ["array-like", None], + "verbose": ["verbose"], + "return_n_iter": ["boolean"], + "positive": ["boolean"], + "check_input": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def enet_path( + X, + y, + *, + l1_ratio=0.5, + eps=1e-3, + n_alphas=100, + alphas=None, + precompute="auto", + Xy=None, + copy_X=True, + coef_init=None, + verbose=False, + return_n_iter=False, + positive=False, + check_input=True, + **params, +): + """Compute elastic net path with coordinate descent. + + The elastic net optimization function varies for mono and multi-outputs. + + For mono-output tasks it is:: + + 1 / (2 * n_samples) * ||y - Xw||^2_2 + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 + + For multi-output tasks it is:: + + (1 / (2 * n_samples)) * ||Y - XW||_Fro^2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + + Where:: + + ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data to avoid + unnecessary memory duplication. If ``y`` is mono-output then ``X`` + can be sparse. + + y : {array-like, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_targets) + Target values. + + l1_ratio : float, default=0.5 + Number between 0 and 1 passed to elastic net (scaling between + l1 and l2 penalties). ``l1_ratio=1`` corresponds to the Lasso. + + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path. + + alphas : array-like, default=None + List of alphas where to compute the models. + If None alphas are set automatically. + + precompute : 'auto', bool or array-like of shape \ + (n_features, n_features), default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + Xy : array-like of shape (n_features,) or (n_features, n_targets),\ + default=None + Xy = np.dot(X.T, y) that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + coef_init : array-like of shape (n_features, ), default=None + The initial values of the coefficients. + + verbose : bool or int, default=False + Amount of verbosity. + + return_n_iter : bool, default=False + Whether to return the number of iterations or not. + + positive : bool, default=False + If set to True, forces coefficients to be positive. + (Only allowed when ``y.ndim == 1``). + + check_input : bool, default=True + If set to False, the input validation checks are skipped (including the + Gram matrix when provided). It is assumed that they are handled + by the caller. + + **params : kwargs + Keyword arguments passed to the coordinate descent solver. + + Returns + ------- + alphas : ndarray of shape (n_alphas,) + The alphas along the path where models are computed. + + coefs : ndarray of shape (n_features, n_alphas) or \ + (n_targets, n_features, n_alphas) + Coefficients along the path. + + dual_gaps : ndarray of shape (n_alphas,) + The dual gaps at the end of the optimization for each alpha. + + n_iters : list of int + The number of iterations taken by the coordinate descent optimizer to + reach the specified tolerance for each alpha. + (Is returned when ``return_n_iter`` is set to True). + + See Also + -------- + MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2 mixed-norm \ + as regularizer. + MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in cross-validation. + ElasticNet : Linear regression with combined L1 and L2 priors as regularizer. + ElasticNetCV : Elastic Net model with iterative fitting along a regularization path. + + Notes + ----- + For an example, see + :ref:`examples/linear_model/plot_lasso_lasso_lars_elasticnet_path.py + `. + + Examples + -------- + >>> from sklearn.linear_model import enet_path + >>> from sklearn.datasets import make_regression + >>> X, y, true_coef = make_regression( + ... n_samples=100, n_features=5, n_informative=2, coef=True, random_state=0 + ... ) + >>> true_coef + array([ 0. , 0. , 0. , 97.9, 45.7]) + >>> alphas, estimated_coef, _ = enet_path(X, y, n_alphas=3) + >>> alphas.shape + (3,) + >>> estimated_coef + array([[ 0., 0.787, 0.568], + [ 0., 1.120, 0.620], + [-0., -2.129, -1.128], + [ 0., 23.046, 88.939], + [ 0., 10.637, 41.566]]) + """ + 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) + selection = params.pop("selection", "cyclic") + + if len(params) > 0: + raise ValueError("Unexpected parameters in params", params.keys()) + + # We expect X and y to be already Fortran ordered when bypassing + # checks + if check_input: + X = check_array( + X, + accept_sparse="csc", + dtype=[np.float64, np.float32], + order="F", + copy=copy_X, + ) + y = check_array( + y, + accept_sparse="csc", + dtype=X.dtype.type, + order="F", + copy=False, + ensure_2d=False, + ) + if Xy is not None: + # Xy should be a 1d contiguous array or a 2D C ordered array + Xy = check_array( + Xy, dtype=X.dtype.type, order="C", copy=False, ensure_2d=False + ) + + n_samples, n_features = X.shape + + multi_output = False + if y.ndim != 1: + multi_output = True + n_targets = y.shape[1] + + if multi_output and positive: + raise ValueError("positive=True is not allowed for multi-output (y.ndim != 1)") + + # MultiTaskElasticNet does not support sparse matrices + if not multi_output and sparse.issparse(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. + 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 have been passed through _pre_fit already if function is called + # from ElasticNet.fit + if check_input: + X, y, _, _, _, precompute, Xy = _pre_fit( + X, + y, + Xy, + precompute, + fit_intercept=False, + copy=False, + check_input=check_input, + ) + if alphas is None: + # No need to normalize of fit_intercept: it has been done + # above + alphas = _alpha_grid( + X, + y, + Xy=Xy, + l1_ratio=l1_ratio, + fit_intercept=False, + eps=eps, + n_alphas=n_alphas, + copy_X=False, + ) + elif len(alphas) > 1: + alphas = np.sort(alphas)[::-1] # make sure alphas are properly ordered + + n_alphas = len(alphas) + dual_gaps = np.empty(n_alphas) + n_iters = [] + + rng = check_random_state(random_state) + if selection not in ["random", "cyclic"]: + raise ValueError("selection should be either random or cyclic.") + random = selection == "random" + + if not multi_output: + coefs = np.empty((n_features, n_alphas), dtype=X.dtype) + else: + coefs = np.empty((n_targets, n_features, n_alphas), dtype=X.dtype) + + if coef_init is None: + coef_ = np.zeros(coefs.shape[:-1], dtype=X.dtype, order="F") + else: + coef_ = np.asfortranarray(coef_init, dtype=X.dtype) + + for i, alpha in enumerate(alphas): + # account for n_samples scaling in objectives between here and cd_fast + l1_reg = alpha * l1_ratio * n_samples + l2_reg = alpha * (1.0 - l1_ratio) * n_samples + if not multi_output and sparse.issparse(X): + model = cd_fast.sparse_enet_coordinate_descent( + 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( + coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random + ) + elif isinstance(precompute, np.ndarray): + # We expect precompute to be already Fortran ordered when bypassing + # checks + if check_input: + precompute = check_array(precompute, dtype=X.dtype.type, order="C") + model = cd_fast.enet_coordinate_descent_gram( + coef_, + l1_reg, + l2_reg, + precompute, + Xy, + y, + max_iter, + tol, + rng, + random, + positive, + ) + elif precompute is False: + model = cd_fast.enet_coordinate_descent( + coef_, l1_reg, l2_reg, X, y, max_iter, tol, rng, random, positive + ) + else: + raise ValueError( + "Precompute should be one of True, False, 'auto' or array-like. Got %r" + % precompute + ) + coef_, dual_gap_, eps_, n_iter_ = model + coefs[..., i] = coef_ + # we correct the scale of the returned dual gap, as the objective + # in cd_fast is n_samples * the objective in this docstring. + dual_gaps[i] = dual_gap_ / n_samples + n_iters.append(n_iter_) + + if verbose: + if verbose > 2: + print(model) + elif verbose > 1: + print("Path: %03i out of %03i" % (i, n_alphas)) + else: + sys.stderr.write(".") + + if return_n_iter: + return alphas, coefs, dual_gaps, n_iters + return alphas, coefs, dual_gaps + + +############################################################################### +# ElasticNet model + + +class ElasticNet(MultiOutputMixin, RegressorMixin, LinearModel): + """Linear regression with combined L1 and L2 priors as regularizer. + + Minimizes the objective function:: + + 1 / (2 * n_samples) * ||y - Xw||^2_2 + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 + + If you are interested in controlling the L1 and L2 penalty + separately, keep in mind that this is equivalent to:: + + a * ||w||_1 + 0.5 * b * ||w||_2^2 + + where:: + + alpha = a + b and l1_ratio = a / (a + b) + + The parameter l1_ratio corresponds to alpha in the glmnet R package while + alpha corresponds to the lambda parameter in glmnet. Specifically, l1_ratio + = 1 is the lasso penalty. Currently, l1_ratio <= 0.01 is not reliable, + unless you supply your own sequence of alpha. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Constant that multiplies the penalty terms. Defaults to 1.0. + See the notes for the exact mathematical meaning of this + parameter. ``alpha = 0`` is equivalent to an ordinary least square, + solved by the :class:`LinearRegression` object. For numerical + reasons, using ``alpha = 0`` with the ``Lasso`` object is not advised. + Given this, you should use the :class:`LinearRegression` object. + + l1_ratio : float, default=0.5 + The ElasticNet mixing parameter, with ``0 <= l1_ratio <= 1``. For + ``l1_ratio = 0`` the penalty is an L2 penalty. ``For l1_ratio = 1`` it + is an L1 penalty. For ``0 < l1_ratio < 1``, the penalty is a + combination of L1 and L2. + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If ``False``, the + data is assumed to be already centered. + + precompute : bool or array-like of shape (n_features, n_features),\ + default=False + Whether to use a precomputed Gram matrix to speed up + calculations. The Gram matrix can also be passed as argument. + For sparse input this option is always ``False`` to preserve sparsity. + Check :ref:`an example on how to use a precomputed Gram Matrix in ElasticNet + ` + for details. + + max_iter : int, default=1000 + The maximum number of iterations. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``, see Notes below. + + warm_start : bool, default=False + 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 `. + + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the cost function formula). + + sparse_coef_ : sparse matrix of shape (n_features,) or \ + (n_targets, n_features) + Sparse representation of the `coef_`. + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. + + n_iter_ : list of int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance. + + dual_gap_ : float or ndarray of shape (n_targets,) + Given param alpha, the dual gaps at the end of the optimization, + same shape as each observation of y. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + ElasticNetCV : Elastic net model with best model selection by + cross-validation. + SGDRegressor : Implements elastic net regression with incremental training. + SGDClassifier : Implements logistic regression with elastic net penalty + (``SGDClassifier(loss="log_loss", penalty="elasticnet")``). + + Notes + ----- + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + + The precise stopping criteria based on `tol` are the following: First, check that + that maximum coordinate update, i.e. :math:`\\max_j |w_j^{new} - w_j^{old}|` + is smaller than `tol` times the maximum absolute coefficient, :math:`\\max_j |w_j|`. + If so, then additionally check whether the dual gap is smaller than `tol` times + :math:`||y||_2^2 / n_{\text{samples}}`. + + Examples + -------- + >>> from sklearn.linear_model import ElasticNet + >>> from sklearn.datasets import make_regression + + >>> X, y = make_regression(n_features=2, random_state=0) + >>> regr = ElasticNet(random_state=0) + >>> regr.fit(X, y) + ElasticNet(random_state=0) + >>> print(regr.coef_) + [18.83816048 64.55968825] + >>> print(regr.intercept_) + 1.451 + >>> print(regr.predict([[0, 0]])) + [1.451] + + - :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` + showcases ElasticNet alongside Lasso and ARD Regression for sparse + signal recovery in the presence of noise and feature correlation. + """ + + # "check_input" is used for optimisation and isn't something to be passed + # around in a pipeline. + __metadata_request__fit = {"check_input": metadata_routing.UNUSED} + + _parameter_constraints: dict = { + "alpha": [Interval(Real, 0, None, closed="left")], + "l1_ratio": [Interval(Real, 0, 1, closed="both")], + "fit_intercept": ["boolean"], + "precompute": ["boolean", "array-like"], + "max_iter": [Interval(Integral, 1, None, closed="left"), None], + "copy_X": ["boolean"], + "tol": [Interval(Real, 0, None, closed="left")], + "warm_start": ["boolean"], + "positive": ["boolean"], + "random_state": ["random_state"], + "selection": [StrOptions({"cyclic", "random"})], + } + + path = staticmethod(enet_path) + + def __init__( + self, + alpha=1.0, + *, + l1_ratio=0.5, + fit_intercept=True, + precompute=False, + max_iter=1000, + copy_X=True, + tol=1e-4, + warm_start=False, + positive=False, + random_state=None, + selection="cyclic", + ): + self.alpha = alpha + self.l1_ratio = l1_ratio + self.fit_intercept = fit_intercept + self.precompute = precompute + self.max_iter = max_iter + self.copy_X = copy_X + self.tol = tol + self.warm_start = warm_start + self.positive = positive + self.random_state = random_state + self.selection = selection + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None, check_input=True): + """Fit model with coordinate descent. + + Parameters + ---------- + X : {ndarray, sparse matrix, sparse array} of (n_samples, n_features) + Data. + + Note that large sparse matrices and arrays requiring `int64` + indices are not accepted. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Target. Will be cast to X's dtype if necessary. + + sample_weight : float or array-like of shape (n_samples,), default=None + Sample weights. Internally, the `sample_weight` vector will be + rescaled to sum to `n_samples`. + + .. versionadded:: 0.23 + + check_input : bool, default=True + Allow to bypass several input checking. + Don't use this parameter unless you know what you do. + + Returns + ------- + self : object + Fitted estimator. + + Notes + ----- + Coordinate descent is an algorithm that considers each column of + data at a time hence it will automatically convert the X input + as a Fortran-contiguous numpy array if necessary. + + To avoid memory re-allocation it is advised to allocate the + initial data in memory directly using that format. + """ + if self.alpha == 0: + warnings.warn( + ( + "With alpha=0, this algorithm does not converge " + "well. You are advised to use the LinearRegression " + "estimator" + ), + stacklevel=2, + ) + + # Remember if X is copied + X_copied = False + # We expect X and y to be float64 or float32 Fortran ordered arrays + # when bypassing checks + if check_input: + X_copied = self.copy_X and self.fit_intercept + X, y = validate_data( + self, + X, + y, + accept_sparse="csc", + order="F", + dtype=[np.float64, np.float32], + force_writeable=True, + accept_large_sparse=False, + copy=X_copied, + multi_output=True, + y_numeric=True, + ) + y = check_array( + y, order="F", copy=False, dtype=X.dtype.type, ensure_2d=False + ) + + n_samples, n_features = X.shape + alpha = self.alpha + + if isinstance(sample_weight, numbers.Number): + sample_weight = None + if sample_weight is not None: + if check_input: + 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 + # + # 1/2 * np.average(squared error, weights=sw) + # + alpha * penalty (1) + # + # is invariant under rescaling of sw. + # But enet_path coordinate descent minimizes + # + # 1/2 * sum(squared error) + alpha' * penalty (2) + # + # and therefore sets + # + # alpha' = n_samples * alpha (3) + # + # inside its function body, which results in objective (2) being + # equivalent to (1) in case of no sw. + # With sw, however, enet_path should set + # + # alpha' = sum(sw) * alpha (4) + # + # Therefore, we use the freedom of Eq. (1) to rescale sw before + # calling enet_path, i.e. + # + # sw *= n_samples / sum(sw) + # + # such that sum(sw) = n_samples. This way, (3) and (4) are the same. + sample_weight = sample_weight * (n_samples / np.sum(sample_weight)) + # Note: Alternatively, we could also have rescaled alpha instead + # of sample_weight: + # + # alpha *= np.sum(sample_weight) / n_samples + + # Ensure copying happens only once, don't do it again if done above. + # X and y will be rescaled if sample_weight is not None, order='F' + # ensures that the returned X and y are still F-contiguous. + should_copy = self.copy_X and not X_copied + X, y, X_offset, y_offset, X_scale, precompute, Xy = _pre_fit( + X, + y, + None, + self.precompute, + fit_intercept=self.fit_intercept, + copy=should_copy, + check_input=check_input, + sample_weight=sample_weight, + ) + # coordinate descent needs F-ordered arrays and _pre_fit might have + # called _rescale_data + if check_input or sample_weight is not None: + X, y = _set_order(X, y, order="F") + if y.ndim == 1: + y = y[:, np.newaxis] + if Xy is not None and Xy.ndim == 1: + Xy = Xy[:, np.newaxis] + + n_targets = y.shape[1] + + if not self.warm_start or not hasattr(self, "coef_"): + coef_ = np.zeros((n_targets, n_features), dtype=X.dtype, order="F") + else: + coef_ = self.coef_ + if coef_.ndim == 1: + coef_ = coef_[np.newaxis, :] + + dual_gaps_ = np.zeros(n_targets, dtype=X.dtype) + self.n_iter_ = [] + + for k in range(n_targets): + if Xy is not None: + this_Xy = Xy[:, k] + else: + this_Xy = None + _, this_coef, this_dual_gap, this_iter = self.path( + X, + y[:, k], + l1_ratio=self.l1_ratio, + eps=None, + n_alphas=None, + alphas=[alpha], + precompute=precompute, + Xy=this_Xy, + copy_X=True, + coef_init=coef_[k], + verbose=False, + 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, + max_iter=self.max_iter, + random_state=self.random_state, + selection=self.selection, + sample_weight=sample_weight, + ) + coef_[k] = this_coef[:, 0] + dual_gaps_[k] = this_dual_gap[0] + self.n_iter_.append(this_iter[0]) + + if n_targets == 1: + self.n_iter_ = self.n_iter_[0] + self.coef_ = coef_[0] + self.dual_gap_ = dual_gaps_[0] + else: + self.coef_ = coef_ + self.dual_gap_ = dual_gaps_ + + self._set_intercept(X_offset, y_offset, X_scale) + + # 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 + + @property + def sparse_coef_(self): + """Sparse representation of the fitted `coef_`.""" + return sparse.csr_matrix(self.coef_) + + def _decision_function(self, X): + """Decision function of the linear model. + + Parameters + ---------- + X : numpy array or scipy.sparse matrix of shape (n_samples, n_features) + + Returns + ------- + T : ndarray of shape (n_samples,) + The predicted decision function. + """ + check_is_fitted(self) + if sparse.issparse(X): + return safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ + else: + return super()._decision_function(X) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +############################################################################### +# Lasso model + + +class Lasso(ElasticNet): + """Linear Model trained with L1 prior as regularizer (aka the Lasso). + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + Technically the Lasso model is optimizing the same objective function as + the Elastic Net with ``l1_ratio=1.0`` (no L2 penalty). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Constant that multiplies the L1 term, controlling regularization + strength. `alpha` must be a non-negative float i.e. in `[0, inf)`. + + When `alpha = 0`, the objective is equivalent to ordinary least + squares, solved by the :class:`LinearRegression` object. For numerical + reasons, using `alpha = 0` with the `Lasso` object is not advised. + Instead, you should use the :class:`LinearRegression` object. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to False, no intercept will be used in calculations + (i.e. data is expected to be centered). + + precompute : bool or array-like of shape (n_features, n_features),\ + default=False + Whether to use a precomputed Gram matrix to speed up + calculations. The Gram matrix can also be passed as argument. + For sparse input this option is always ``False`` to preserve sparsity. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``, see Notes below. + + warm_start : bool, default=False + 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 `. + + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the cost function formula). + + dual_gap_ : float or ndarray of shape (n_targets,) + Given param alpha, the dual gaps at the end of the optimization, + same shape as each observation of y. + + sparse_coef_ : sparse matrix of shape (n_features, 1) or \ + (n_targets, n_features) + Readonly property derived from ``coef_``. + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. + + n_iter_ : int or list of int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Regularization path using LARS. + lasso_path : Regularization path using Lasso. + LassoLars : Lasso Path along the regularization parameter using LARS algorithm. + LassoCV : Lasso alpha parameter by cross-validation. + LassoLarsCV : Lasso least angle parameter algorithm by cross-validation. + sklearn.decomposition.sparse_encode : Sparse coding array estimator. + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + To avoid unnecessary memory duplication the X argument of the fit method + should be directly passed as a Fortran-contiguous numpy array. + + Regularization improves the conditioning of the problem and + reduces the variance of the estimates. Larger values specify stronger + regularization. Alpha corresponds to `1 / (2C)` in other linear + models such as :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. + + The precise stopping criteria based on `tol` are the following: First, check that + that maximum coordinate update, i.e. :math:`\\max_j |w_j^{new} - w_j^{old}|` + is smaller than `tol` times the maximum absolute coefficient, :math:`\\max_j |w_j|`. + If so, then additionally check whether the dual gap is smaller than `tol` times + :math:`||y||_2^2 / n_{\\text{samples}}`. + + The target can be a 2-dimensional array, resulting in the optimization of the + following objective:: + + (1 / (2 * n_samples)) * ||Y - XW||^2_F + alpha * ||W||_11 + + where :math:`||W||_{1,1}` is the sum of the magnitude of the matrix coefficients. + It should not be confused with :class:`~sklearn.linear_model.MultiTaskLasso` which + instead penalizes the :math:`L_{2,1}` norm of the coefficients, yielding row-wise + sparsity in the coefficients. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.Lasso(alpha=0.1) + >>> clf.fit([[0,0], [1, 1], [2, 2]], [0, 1, 2]) + Lasso(alpha=0.1) + >>> print(clf.coef_) + [0.85 0. ] + >>> print(clf.intercept_) + 0.15 + + - :ref:`sphx_glr_auto_examples_linear_model_plot_lasso_and_elasticnet.py` + compares Lasso with other L1-based regression models (ElasticNet and ARD + Regression) for sparse signal recovery in the presence of noise and + feature correlation. + """ + + _parameter_constraints: dict = { + **ElasticNet._parameter_constraints, + } + _parameter_constraints.pop("l1_ratio") + + path = staticmethod(enet_path) + + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + precompute=False, + copy_X=True, + max_iter=1000, + tol=1e-4, + warm_start=False, + positive=False, + random_state=None, + selection="cyclic", + ): + super().__init__( + alpha=alpha, + l1_ratio=1.0, + fit_intercept=fit_intercept, + precompute=precompute, + copy_X=copy_X, + max_iter=max_iter, + tol=tol, + warm_start=warm_start, + positive=positive, + random_state=random_state, + selection=selection, + ) + + +############################################################################### +# Functions for CV with paths functions + + +def _path_residuals( + X, + y, + sample_weight, + train, + test, + fit_intercept, + path, + path_params, + alphas=None, + l1_ratio=1, + X_order=None, + dtype=None, +): + """Returns the MSE for the models computed by 'path'. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + sample_weight : None or array-like of shape (n_samples,) + Sample weights. + + train : list of indices + The indices of the train set. + + test : list of indices + The indices of the test set. + + path : callable + Function returning a list of models on the path. See + enet_path for an example of signature. + + path_params : dictionary + Parameters passed to the path function. + + alphas : array-like, default=None + Array of float that is used for cross-validation. If not + provided, computed using 'path'. + + l1_ratio : float, default=1 + float between 0 and 1 passed to ElasticNet (scaling between + l1 and l2 penalties). For ``l1_ratio = 0`` the penalty is an + L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. For ``0 + < l1_ratio < 1``, the penalty is a combination of L1 and L2. + + X_order : {'F', 'C'}, default=None + The order of the arrays expected by the path function to + avoid memory copies. + + dtype : a numpy dtype, default=None + The dtype of the arrays expected by the path function to + avoid memory copies. + """ + X_train = X[train] + y_train = y[train] + X_test = X[test] + y_test = y[test] + if sample_weight is None: + sw_train, sw_test = None, None + else: + sw_train = sample_weight[train] + sw_test = sample_weight[test] + n_samples = X_train.shape[0] + # TLDR: Rescale sw_train to sum up to n_samples on the training set. + # See TLDR and long comment inside ElasticNet.fit. + sw_train *= n_samples / np.sum(sw_train) + # Note: Alternatively, we could also have rescaled alpha instead + # of sample_weight: + # + # alpha *= np.sum(sample_weight) / n_samples + + if not sparse.issparse(X): + for array, array_input in ( + (X_train, X), + (y_train, y), + (X_test, X), + (y_test, y), + ): + if array.base is not array_input and not array.flags["WRITEABLE"]: + # fancy indexing should create a writable copy but it doesn't + # for read-only memmaps (cf. numpy#14132). + array.setflags(write=True) + + if y.ndim == 1: + precompute = path_params["precompute"] + else: + # No Gram variant of multi-task exists right now. + # Fall back to default enet_multitask + precompute = False + + X_train, y_train, X_offset, y_offset, X_scale, precompute, Xy = _pre_fit( + X_train, + y_train, + None, + precompute, + fit_intercept=fit_intercept, + copy=False, + sample_weight=sw_train, + ) + + path_params = path_params.copy() + path_params["Xy"] = Xy + path_params["X_offset"] = X_offset + path_params["X_scale"] = X_scale + 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 + + # Do the ordering and type casting here, as if it is done in the path, + # X is copied and a reference is kept here + X_train = check_array(X_train, accept_sparse="csc", dtype=dtype, order=X_order) + alphas, coefs, _ = path(X_train, y_train, **path_params) + del X_train, y_train + + if y.ndim == 1: + # Doing this so that it becomes coherent with multioutput. + coefs = coefs[np.newaxis, :, :] + y_offset = np.atleast_1d(y_offset) + y_test = y_test[:, np.newaxis] + + intercepts = y_offset[:, np.newaxis] - np.dot(X_offset, coefs) + X_test_coefs = safe_sparse_dot(X_test, coefs) + residues = X_test_coefs - y_test[:, :, np.newaxis] + residues += intercepts + if sample_weight is None: + this_mse = (residues**2).mean(axis=0) + else: + this_mse = np.average(residues**2, weights=sw_test, axis=0) + + return this_mse.mean(axis=0) + + +class LinearModelCV(MultiOutputMixin, LinearModel, ABC): + """Base class for iterative model fitting along a regularization path.""" + + _parameter_constraints: dict = { + "eps": [Interval(Real, 0, None, closed="neither")], + "n_alphas": [ + Interval(Integral, 1, None, closed="left"), + Hidden(StrOptions({"deprecated"})), + ], + # TODO(1.9): remove "warn" and None options. + "alphas": [ + Interval(Integral, 1, None, closed="left"), + "array-like", + None, + Hidden(StrOptions({"warn"})), + ], + "fit_intercept": ["boolean"], + "precompute": [StrOptions({"auto"}), "array-like", "boolean"], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "copy_X": ["boolean"], + "cv": ["cv_object"], + "verbose": ["verbose"], + "n_jobs": [Integral, None], + "positive": ["boolean"], + "random_state": ["random_state"], + "selection": [StrOptions({"cyclic", "random"})], + } + + @abstractmethod + def __init__( + self, + eps=1e-3, + n_alphas="deprecated", + alphas="warn", + fit_intercept=True, + precompute="auto", + max_iter=1000, + tol=1e-4, + copy_X=True, + cv=None, + verbose=False, + n_jobs=None, + positive=False, + random_state=None, + selection="cyclic", + ): + self.eps = eps + self.n_alphas = n_alphas + self.alphas = alphas + self.fit_intercept = fit_intercept + self.precompute = precompute + self.max_iter = max_iter + self.tol = tol + self.copy_X = copy_X + self.cv = cv + self.verbose = verbose + self.n_jobs = n_jobs + self.positive = positive + self.random_state = random_state + self.selection = selection + + @abstractmethod + def _get_estimator(self): + """Model to be fitted after the best alpha has been determined.""" + + @abstractmethod + def _is_multitask(self): + """Bool indicating if class is meant for multidimensional target.""" + + @staticmethod + @abstractmethod + def path(X, y, **kwargs): + """Compute path with coordinate descent.""" + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None, **params): + """Fit linear model with coordinate descent. + + Fit is on grid of alphas and best alpha estimated by cross-validation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data + to avoid unnecessary memory duplication. If y is mono-output, + X can be sparse. Note that large sparse matrices and arrays + requiring `int64` indices are not accepted. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + sample_weight : float or array-like of shape (n_samples,), \ + default=None + Sample weights used for fitting and evaluation of the weighted + mean squared error of each cv-fold. Note that the cross validated + MSE that is finally used to find the best model is the unweighted + mean over the (weighted) MSEs of each test fold. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of fitted model. + """ + _raise_for_params(params, self, "fit") + + # TODO(1.9): remove n_alphas and alphas={"warn", None}; set alphas=100 by + # default. Remove these deprecations messages and use self.alphas directly + # instead of self._alphas. + if self.n_alphas == "deprecated": + self._alphas = 100 + else: + warnings.warn( + "'n_alphas' was deprecated in 1.7 and will be removed in 1.9. " + "'alphas' now accepts an integer value which removes the need to pass " + "'n_alphas'. The default value of 'alphas' will change from None to " + "100 in 1.9. Pass an explicit value to 'alphas' and leave 'n_alphas' " + "to its default value to silence this warning.", + FutureWarning, + ) + self._alphas = self.n_alphas + + if isinstance(self.alphas, str) and self.alphas == "warn": + # - If self.n_alphas == "deprecated", both are left to their default values + # so we don't warn since the future default behavior will be the same as + # the current default behavior. + # - If self.n_alphas != "deprecated", then we already warned about it + # and the warning message mentions the future self.alphas default, so + # no need to warn a second time. + pass + elif self.alphas is None: + warnings.warn( + "'alphas=None' is deprecated and will be removed in 1.9, at which " + "point the default value will be set to 100. Set 'alphas=100' " + "to silence this warning.", + FutureWarning, + ) + else: + self._alphas = self.alphas + + # This makes sure that there is no duplication in memory. + # Dealing right with copy_X is important in the following: + # Multiple functions touch X and subsamples of X and can induce a + # lot of duplication of memory + copy_X = self.copy_X and self.fit_intercept + + check_y_params = dict( + copy=False, dtype=[np.float64, np.float32], ensure_2d=False + ) + if isinstance(X, np.ndarray) or sparse.issparse(X): + # Keep a reference to X + reference_to_old_X = X + # Let us not impose fortran ordering so far: it is + # not useful for the cross-validation loop and will be done + # by the model fitting itself + + # Need to validate separately here. + # We can't pass multi_output=True because that would allow y to be + # csr. We also want to allow y to be 64 or 32 but check_X_y only + # allows to convert for 64. + check_X_params = dict( + accept_sparse="csc", + dtype=[np.float64, np.float32], + force_writeable=True, + copy=False, + accept_large_sparse=False, + ) + X, y = validate_data( + self, X, y, validate_separately=(check_X_params, check_y_params) + ) + if sparse.issparse(X): + if hasattr(reference_to_old_X, "data") and not np.may_share_memory( + reference_to_old_X.data, X.data + ): + # X is a sparse matrix and has been copied + copy_X = False + elif not np.may_share_memory(reference_to_old_X, X): + # X has been copied + copy_X = False + del reference_to_old_X + else: + # Need to validate separately here. + # We can't pass multi_output=True because that would allow y to be + # csr. We also want to allow y to be 64 or 32 but check_X_y only + # allows to convert for 64. + check_X_params = dict( + accept_sparse="csc", + dtype=[np.float64, np.float32], + order="F", + force_writeable=True, + copy=copy_X, + ) + X, y = validate_data( + self, X, y, validate_separately=(check_X_params, check_y_params) + ) + copy_X = False + + check_consistent_length(X, y) + + if not self._is_multitask(): + if y.ndim > 1 and y.shape[1] > 1: + raise ValueError( + "For multi-task outputs, use MultiTask%s" % self.__class__.__name__ + ) + y = column_or_1d(y, warn=True) + else: + if sparse.issparse(X): + raise TypeError("X should be dense but a sparse matrix waspassed") + elif y.ndim == 1: + raise ValueError( + "For mono-task outputs, use %sCV" % self.__class__.__name__[9:] + ) + + if isinstance(sample_weight, numbers.Number): + sample_weight = None + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + model = self._get_estimator() + + # All LinearModelCV parameters except 'cv' are acceptable + path_params = self.get_params() + + # Pop `intercept` that is not parameter of the path function + path_params.pop("fit_intercept", None) + + if "l1_ratio" in path_params: + l1_ratios = np.atleast_1d(path_params["l1_ratio"]) + # For the first path, we need to set l1_ratio + path_params["l1_ratio"] = l1_ratios[0] + else: + l1_ratios = [ + 1, + ] + path_params.pop("cv", None) + path_params.pop("n_jobs", None) + + n_l1_ratio = len(l1_ratios) + + check_scalar_alpha = partial( + check_scalar, + target_type=Real, + min_val=0.0, + include_boundaries="left", + ) + + if isinstance(self._alphas, Integral): + alphas = [ + _alpha_grid( + X, + y, + l1_ratio=l1_ratio, + fit_intercept=self.fit_intercept, + eps=self.eps, + n_alphas=self._alphas, + copy_X=self.copy_X, + sample_weight=sample_weight, + ) + for l1_ratio in l1_ratios + ] + else: + # Making sure alphas entries are scalars. + for index, alpha in enumerate(self._alphas): + check_scalar_alpha(alpha, f"alphas[{index}]") + # Making sure alphas is properly ordered. + alphas = np.tile(np.sort(self._alphas)[::-1], (n_l1_ratio, 1)) + + # We want n_alphas to be the number of alphas used for each l1_ratio. + n_alphas = len(alphas[0]) + path_params.update({"n_alphas": n_alphas}) + + path_params["copy_X"] = copy_X + # We are not computing in parallel, we can modify X + # inplace in the folds + if effective_n_jobs(self.n_jobs) > 1: + path_params["copy_X"] = False + + # init cross-validation generator + cv = check_cv(self.cv) + + if _routing_enabled(): + splitter_supports_sample_weight = get_routing_for_object(cv).consumes( + method="split", params=["sample_weight"] + ) + if ( + sample_weight is not None + and not splitter_supports_sample_weight + and not has_fit_parameter(self, "sample_weight") + ): + raise ValueError( + "The CV splitter and underlying estimator do not support" + " sample weights." + ) + + if splitter_supports_sample_weight: + params["sample_weight"] = sample_weight + + routed_params = process_routing(self, "fit", **params) + + if sample_weight is not None and not has_fit_parameter( + self, "sample_weight" + ): + # MultiTaskElasticNetCV does not (yet) support sample_weight + sample_weight = None + else: + routed_params = Bunch() + routed_params.splitter = Bunch(split=Bunch()) + + # Compute path for all folds and compute MSE to get the best alpha + folds = list(cv.split(X, y, **routed_params.splitter.split)) + best_mse = np.inf + + # We do a double for loop folded in one, in order to be able to + # iterate in parallel on l1_ratio and folds + jobs = ( + delayed(_path_residuals)( + X, + y, + sample_weight, + train, + test, + self.fit_intercept, + self.path, + path_params, + alphas=this_alphas, + l1_ratio=this_l1_ratio, + X_order="F", + dtype=X.dtype.type, + ) + for this_l1_ratio, this_alphas in zip(l1_ratios, alphas) + for train, test in folds + ) + mse_paths = Parallel( + n_jobs=self.n_jobs, + verbose=self.verbose, + prefer="threads", + )(jobs) + mse_paths = np.reshape(mse_paths, (n_l1_ratio, len(folds), -1)) + # The mean is computed over folds. + mean_mse = np.mean(mse_paths, axis=1) + self.mse_path_ = np.squeeze(np.moveaxis(mse_paths, 2, 1)) + for l1_ratio, l1_alphas, mse_alphas in zip(l1_ratios, alphas, mean_mse): + i_best_alpha = np.argmin(mse_alphas) + this_best_mse = mse_alphas[i_best_alpha] + if this_best_mse < best_mse: + best_alpha = l1_alphas[i_best_alpha] + best_l1_ratio = l1_ratio + best_mse = this_best_mse + + self.l1_ratio_ = best_l1_ratio + self.alpha_ = best_alpha + if isinstance(self._alphas, Integral): + self.alphas_ = np.asarray(alphas) + if n_l1_ratio == 1: + self.alphas_ = self.alphas_[0] + # Remove duplicate alphas in case alphas is provided. + else: + self.alphas_ = np.asarray(alphas[0]) + + # Refit the model with the parameters selected + common_params = { + name: value + for name, value in self.get_params().items() + if name in model.get_params() + } + model.set_params(**common_params) + model.alpha = best_alpha + model.l1_ratio = best_l1_ratio + model.copy_X = copy_X + precompute = getattr(self, "precompute", None) + if isinstance(precompute, str) and precompute == "auto": + model.precompute = False + + if sample_weight is None: + # MultiTaskElasticNetCV does not (yet) support sample_weight, even + # not sample_weight=None. + model.fit(X, y) + else: + model.fit(X, y, sample_weight=sample_weight) + if not hasattr(self, "l1_ratio"): + del self.l1_ratio_ + self.coef_ = model.coef_ + self.intercept_ = model.intercept_ + self.dual_gap_ = model.dual_gap_ + self.n_iter_ = model.n_iter_ + return self + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.4 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = ( + MetadataRouter(owner=self.__class__.__name__) + .add_self_request(self) + .add( + splitter=check_cv(self.cv), + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + ) + return router + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + multitask = self._is_multitask() + tags.input_tags.sparse = not multitask + tags.target_tags.multi_output = multitask + return tags + + +class LassoCV(RegressorMixin, LinearModelCV): + """Lasso linear model with iterative fitting along a regularization path. + + See glossary entry for :term:`cross-validation estimator`. + + The best model is selected by cross-validation. + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path. + + .. deprecated:: 1.7 + `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas` + instead. + + alphas : array-like or int, default=None + Values of alphas to test along the regularization path. + If int, `alphas` values are generated automatically. + If array-like, list of alpha values to use. + + .. versionchanged:: 1.7 + `alphas` accepts an integer value which removes the need to pass + `n_alphas`. + + .. deprecated:: 1.7 + `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which + point the default value will be set to 100. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + precompute : 'auto', bool or array-like of shape \ + (n_features, n_features), default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + cv : int, cross-validation generator or iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - int, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + verbose : bool or int, default=False + Amount of verbosity. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + positive : bool, default=False + If positive, restrict regression coefficients to be positive. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + alpha_ : float + The amount of penalization chosen by cross validation. + + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the cost function formula). + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. + + mse_path_ : ndarray of shape (n_alphas, n_folds) + Mean square error for the test set on each fold, varying alpha. + + alphas_ : ndarray of shape (n_alphas,) + The grid of alphas used for fitting. + + dual_gap_ : float or ndarray of shape (n_targets,) + The dual gap at the end of the optimization for the optimal alpha + (``alpha_``). + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso path using LARS + algorithm. + lasso_path : Compute Lasso path with coordinate descent. + Lasso : The Lasso is a linear model that estimates sparse coefficients. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + LassoCV : Lasso linear model with iterative fitting along a regularization + path. + LassoLarsCV : Cross-validated Lasso using the LARS algorithm. + + Notes + ----- + In `fit`, once the best parameter `alpha` is found through + cross-validation, the model is fit again using the entire training set. + + To avoid unnecessary memory duplication the `X` argument of the `fit` + method should be directly passed as a Fortran-contiguous numpy array. + + For an example, see :ref:`examples/linear_model/plot_lasso_model_selection.py + `. + + :class:`LassoCV` leads to different results than a hyperparameter + search using :class:`~sklearn.model_selection.GridSearchCV` with a + :class:`Lasso` model. In :class:`LassoCV`, a model for a given + penalty `alpha` is warm started using the coefficients of the + closest model (trained at the previous iteration) on the + regularization path. It tends to speed up the hyperparameter + search. + + Examples + -------- + >>> from sklearn.linear_model import LassoCV + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression(noise=4, random_state=0) + >>> reg = LassoCV(cv=5, random_state=0).fit(X, y) + >>> reg.score(X, y) + 0.9993 + >>> reg.predict(X[:1,]) + array([-78.4951]) + """ + + path = staticmethod(lasso_path) + + def __init__( + self, + *, + eps=1e-3, + n_alphas="deprecated", + alphas="warn", + fit_intercept=True, + precompute="auto", + max_iter=1000, + tol=1e-4, + copy_X=True, + cv=None, + verbose=False, + n_jobs=None, + positive=False, + random_state=None, + selection="cyclic", + ): + super().__init__( + eps=eps, + n_alphas=n_alphas, + alphas=alphas, + fit_intercept=fit_intercept, + precompute=precompute, + max_iter=max_iter, + tol=tol, + copy_X=copy_X, + cv=cv, + verbose=verbose, + n_jobs=n_jobs, + positive=positive, + random_state=random_state, + selection=selection, + ) + + def _get_estimator(self): + return Lasso() + + def _is_multitask(self): + return False + + def fit(self, X, y, sample_weight=None, **params): + """Fit Lasso model with coordinate descent. + + Fit is on grid of alphas and best alpha estimated by cross-validation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data + to avoid unnecessary memory duplication. If y is mono-output, + X can be sparse. Note that large sparse matrices and arrays + requiring `int64` indices are not accepted. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : float or array-like of shape (n_samples,), \ + default=None + Sample weights used for fitting and evaluation of the weighted + mean squared error of each cv-fold. Note that the cross validated + MSE that is finally used to find the best model is the unweighted + mean over the (weighted) MSEs of each test fold. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of fitted model. + """ + return super().fit(X, y, sample_weight=sample_weight, **params) + + +class ElasticNetCV(RegressorMixin, LinearModelCV): + """Elastic Net model with iterative fitting along a regularization path. + + See glossary entry for :term:`cross-validation estimator`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + l1_ratio : float or list of float, default=0.5 + Float between 0 and 1 passed to ElasticNet (scaling between + l1 and l2 penalties). For ``l1_ratio = 0`` + the penalty is an L2 penalty. For ``l1_ratio = 1`` it is an L1 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1 and L2 + This parameter can be a list, in which case the different + values are tested by cross-validation and the one giving the best + prediction score is used. Note that a good choice of list of + values for l1_ratio is often to put more values close to 1 + (i.e. Lasso) and less close to 0 (i.e. Ridge), as in ``[.1, .5, .7, + .9, .95, .99, 1]``. + + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path, used for each l1_ratio. + + .. deprecated:: 1.7 + `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas` + instead. + + alphas : array-like or int, default=None + Values of alphas to test along the regularization path, used for each l1_ratio. + If int, `alphas` values are generated automatically. + If array-like, list of alpha values to use. + + .. versionchanged:: 1.7 + `alphas` accepts an integer value which removes the need to pass + `n_alphas`. + + .. deprecated:: 1.7 + `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which + point the default value will be set to 100. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + precompute : 'auto', bool or array-like of shape \ + (n_features, n_features), default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + cv : int, cross-validation generator or iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - int, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + verbose : bool or int, default=0 + Amount of verbosity. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + positive : bool, default=False + When set to ``True``, forces the coefficients to be positive. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + alpha_ : float + The amount of penalization chosen by cross validation. + + l1_ratio_ : float + The compromise between l1 and l2 penalization chosen by + cross validation. + + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the cost function formula). + + intercept_ : float or ndarray of shape (n_targets, n_features) + Independent term in the decision function. + + mse_path_ : ndarray of shape (n_l1_ratio, n_alpha, n_folds) + Mean square error for the test set on each fold, varying l1_ratio and + alpha. + + alphas_ : ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas) + The grid of alphas used for fitting, for each l1_ratio. + + dual_gap_ : float + The dual gaps at the end of the optimization for the optimal alpha. + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + enet_path : Compute elastic net path with coordinate descent. + ElasticNet : Linear regression with combined L1 and L2 priors as regularizer. + + Notes + ----- + In `fit`, once the best parameters `l1_ratio` and `alpha` are found through + cross-validation, the model is fit again using the entire training set. + + To avoid unnecessary memory duplication the `X` argument of the `fit` + method should be directly passed as a Fortran-contiguous numpy array. + + The parameter `l1_ratio` corresponds to alpha in the glmnet R package + while alpha corresponds to the lambda parameter in glmnet. + More specifically, the optimization objective is:: + + 1 / (2 * n_samples) * ||y - Xw||^2_2 + + alpha * l1_ratio * ||w||_1 + + 0.5 * alpha * (1 - l1_ratio) * ||w||^2_2 + + If you are interested in controlling the L1 and L2 penalty + separately, keep in mind that this is equivalent to:: + + a * L1 + b * L2 + + for:: + + alpha = a + b and l1_ratio = a / (a + b). + + For an example, see + :ref:`examples/linear_model/plot_lasso_model_selection.py + `. + + Examples + -------- + >>> from sklearn.linear_model import ElasticNetCV + >>> from sklearn.datasets import make_regression + + >>> X, y = make_regression(n_features=2, random_state=0) + >>> regr = ElasticNetCV(cv=5, random_state=0) + >>> regr.fit(X, y) + ElasticNetCV(cv=5, random_state=0) + >>> print(regr.alpha_) + 0.199 + >>> print(regr.intercept_) + 0.398 + >>> print(regr.predict([[0, 0]])) + [0.398] + """ + + _parameter_constraints: dict = { + **LinearModelCV._parameter_constraints, + "l1_ratio": [Interval(Real, 0, 1, closed="both"), "array-like"], + } + + path = staticmethod(enet_path) + + def __init__( + self, + *, + l1_ratio=0.5, + eps=1e-3, + n_alphas="deprecated", + alphas="warn", + fit_intercept=True, + precompute="auto", + max_iter=1000, + tol=1e-4, + cv=None, + copy_X=True, + verbose=0, + n_jobs=None, + positive=False, + random_state=None, + selection="cyclic", + ): + self.l1_ratio = l1_ratio + self.eps = eps + self.n_alphas = n_alphas + self.alphas = alphas + self.fit_intercept = fit_intercept + self.precompute = precompute + self.max_iter = max_iter + self.tol = tol + self.cv = cv + self.copy_X = copy_X + self.verbose = verbose + self.n_jobs = n_jobs + self.positive = positive + self.random_state = random_state + self.selection = selection + + def _get_estimator(self): + return ElasticNet() + + def _is_multitask(self): + return False + + def fit(self, X, y, sample_weight=None, **params): + """Fit ElasticNet model with coordinate descent. + + Fit is on grid of alphas and best alpha estimated by cross-validation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. Pass directly as Fortran-contiguous data + to avoid unnecessary memory duplication. If y is mono-output, + X can be sparse. Note that large sparse matrices and arrays + requiring `int64` indices are not accepted. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : float or array-like of shape (n_samples,), \ + default=None + Sample weights used for fitting and evaluation of the weighted + mean squared error of each cv-fold. Note that the cross validated + MSE that is finally used to find the best model is the unweighted + mean over the (weighted) MSEs of each test fold. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of fitted model. + """ + return super().fit(X, y, sample_weight=sample_weight, **params) + + +############################################################################### +# Multi Task ElasticNet and Lasso models (with joint feature selection) + + +class MultiTaskElasticNet(Lasso): + """Multi-task ElasticNet model trained with L1/L2 mixed-norm as regularizer. + + The optimization objective for MultiTaskElasticNet is:: + + (1 / (2 * n_samples)) * ||Y - XW||_Fro^2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + + Where:: + + ||W||_21 = sum_i sqrt(sum_j W_ij ^ 2) + + i.e. the sum of norms of each row. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Constant that multiplies the L1/L2 term. Defaults to 1.0. + + l1_ratio : float, default=0.5 + The ElasticNet mixing parameter, with 0 < l1_ratio <= 1. + For l1_ratio = 1 the penalty is an L1/L2 penalty. For l1_ratio = 0 it + is an L2 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + warm_start : bool, default=False + 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 `. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + intercept_ : ndarray of shape (n_targets,) + Independent term in decision function. + + coef_ : ndarray of shape (n_targets, n_features) + Parameter vector (W in the cost function formula). If a 1D y is + passed in at fit (non multi-task usage), ``coef_`` is then a 1D array. + Note that ``coef_`` stores the transpose of ``W``, ``W.T``. + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance. + + dual_gap_ : float + The dual gaps at the end of the optimization. + + eps_ : float + The tolerance scaled scaled by the variance of the target `y`. + + sparse_coef_ : sparse matrix of shape (n_features,) or \ + (n_targets, n_features) + Sparse representation of the `coef_`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in + cross-validation. + ElasticNet : Linear regression with combined L1 and L2 priors as regularizer. + MultiTaskLasso : Multi-task Lasso model trained with L1/L2 + mixed-norm as regularizer. + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + To avoid unnecessary memory duplication the X and y arguments of the fit + method should be directly passed as Fortran-contiguous numpy arrays. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.MultiTaskElasticNet(alpha=0.1) + >>> clf.fit([[0,0], [1, 1], [2, 2]], [[0, 0], [1, 1], [2, 2]]) + MultiTaskElasticNet(alpha=0.1) + >>> print(clf.coef_) + [[0.45663524 0.45612256] + [0.45663524 0.45612256]] + >>> print(clf.intercept_) + [0.0872422 0.0872422] + """ + + _parameter_constraints: dict = { + **ElasticNet._parameter_constraints, + } + for param in ("precompute", "positive"): + _parameter_constraints.pop(param) + + def __init__( + self, + alpha=1.0, + *, + l1_ratio=0.5, + fit_intercept=True, + copy_X=True, + max_iter=1000, + tol=1e-4, + warm_start=False, + random_state=None, + selection="cyclic", + ): + self.l1_ratio = l1_ratio + self.alpha = alpha + self.fit_intercept = fit_intercept + self.max_iter = max_iter + self.copy_X = copy_X + self.tol = tol + self.warm_start = warm_start + self.random_state = random_state + self.selection = selection + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit MultiTaskElasticNet model with coordinate descent. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Data. + y : ndarray of shape (n_samples, n_targets) + Target. Will be cast to X's dtype if necessary. + + Returns + ------- + self : object + Fitted estimator. + + Notes + ----- + Coordinate descent is an algorithm that considers each column of + data at a time hence it will automatically convert the X input + as a Fortran-contiguous numpy array if necessary. + + To avoid memory re-allocation it is advised to allocate the + initial data in memory directly using that format. + """ + # Need to validate separately here. + # We can't pass multi_output=True because that would allow y to be csr. + check_X_params = dict( + dtype=[np.float64, np.float32], + order="F", + force_writeable=True, + copy=self.copy_X and self.fit_intercept, + ) + check_y_params = dict(ensure_2d=False, order="F") + X, y = validate_data( + self, X, y, validate_separately=(check_X_params, check_y_params) + ) + check_consistent_length(X, y) + y = y.astype(X.dtype) + + if hasattr(self, "l1_ratio"): + model_str = "ElasticNet" + else: + model_str = "Lasso" + if y.ndim == 1: + raise ValueError("For mono-task outputs, use %s" % model_str) + + n_samples, n_features = X.shape + n_targets = y.shape[1] + + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, y, fit_intercept=self.fit_intercept, copy=False + ) + + if not self.warm_start or not hasattr(self, "coef_"): + self.coef_ = np.zeros( + (n_targets, n_features), dtype=X.dtype.type, order="F" + ) + + l1_reg = self.alpha * self.l1_ratio * n_samples + l2_reg = self.alpha * (1.0 - self.l1_ratio) * n_samples + + self.coef_ = np.asfortranarray(self.coef_) # coef contiguous in memory + + random = self.selection == "random" + + ( + self.coef_, + self.dual_gap_, + self.eps_, + self.n_iter_, + ) = cd_fast.enet_coordinate_descent_multi_task( + self.coef_, + l1_reg, + l2_reg, + X, + y, + self.max_iter, + self.tol, + check_random_state(self.random_state), + random, + ) + + # account for different objective scaling here and in cd_fast + self.dual_gap_ /= n_samples + + self._set_intercept(X_offset, y_offset, X_scale) + + # return self for chaining fit and predict calls + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = False + tags.target_tags.multi_output = True + tags.target_tags.single_output = False + return tags + + +class MultiTaskLasso(MultiTaskElasticNet): + """Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer. + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||Y - XW||^2_Fro + alpha * ||W||_21 + + Where:: + + ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Constant that multiplies the L1/L2 term. Defaults to 1.0. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + warm_start : bool, default=False + 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 `. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + coef_ : ndarray of shape (n_targets, n_features) + Parameter vector (W in the cost function formula). + Note that ``coef_`` stores the transpose of ``W``, ``W.T``. + + intercept_ : ndarray of shape (n_targets,) + Independent term in decision function. + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance. + + dual_gap_ : ndarray of shape (n_alphas,) + The dual gaps at the end of the optimization for each alpha. + + eps_ : float + The tolerance scaled scaled by the variance of the target `y`. + + sparse_coef_ : sparse matrix of shape (n_features,) or \ + (n_targets, n_features) + Sparse representation of the `coef_`. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + Lasso: Linear Model trained with L1 prior as regularizer (aka the Lasso). + MultiTaskLassoCV: Multi-task L1 regularized linear model with built-in + cross-validation. + MultiTaskElasticNetCV: Multi-task L1/L2 ElasticNet with built-in cross-validation. + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + To avoid unnecessary memory duplication the X and y arguments of the fit + method should be directly passed as Fortran-contiguous numpy arrays. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.MultiTaskLasso(alpha=0.1) + >>> clf.fit([[0, 1], [1, 2], [2, 4]], [[0, 0], [1, 1], [2, 3]]) + MultiTaskLasso(alpha=0.1) + >>> print(clf.coef_) + [[0. 0.60809415] + [0. 0.94592424]] + >>> print(clf.intercept_) + [-0.41888636 -0.87382323] + """ + + _parameter_constraints: dict = { + **MultiTaskElasticNet._parameter_constraints, + } + _parameter_constraints.pop("l1_ratio") + + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + copy_X=True, + max_iter=1000, + tol=1e-4, + warm_start=False, + random_state=None, + selection="cyclic", + ): + self.alpha = alpha + self.fit_intercept = fit_intercept + self.max_iter = max_iter + self.copy_X = copy_X + self.tol = tol + self.warm_start = warm_start + self.l1_ratio = 1.0 + self.random_state = random_state + self.selection = selection + + +class MultiTaskElasticNetCV(RegressorMixin, LinearModelCV): + """Multi-task L1/L2 ElasticNet with built-in cross-validation. + + See glossary entry for :term:`cross-validation estimator`. + + The optimization objective for MultiTaskElasticNet is:: + + (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + + alpha * l1_ratio * ||W||_21 + + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2 + + Where:: + + ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.15 + + Parameters + ---------- + l1_ratio : float or list of float, default=0.5 + The ElasticNet mixing parameter, with 0 < l1_ratio <= 1. + For l1_ratio = 1 the penalty is an L1/L2 penalty. For l1_ratio = 0 it + is an L2 penalty. + For ``0 < l1_ratio < 1``, the penalty is a combination of L1/L2 and L2. + This parameter can be a list, in which case the different + values are tested by cross-validation and the one giving the best + prediction score is used. Note that a good choice of list of + values for l1_ratio is often to put more values close to 1 + (i.e. Lasso) and less close to 0 (i.e. Ridge), as in ``[.1, .5, .7, + .9, .95, .99, 1]``. + + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path. + + .. deprecated:: 1.7 + `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas` + instead. + + alphas : array-like or int, default=None + Values of alphas to test along the regularization path, used for each l1_ratio. + If int, `alphas` values are generated automatically. + If array-like, list of alpha values to use. + + .. versionchanged:: 1.7 + `alphas` accepts an integer value which removes the need to pass + `n_alphas`. + + .. deprecated:: 1.7 + `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which + point the default value will be set to 100. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + cv : int, cross-validation generator or iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - int, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + verbose : bool or int, default=0 + Amount of verbosity. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. Note that this is + used only if multiple values for l1_ratio are given. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + intercept_ : ndarray of shape (n_targets,) + Independent term in decision function. + + coef_ : ndarray of shape (n_targets, n_features) + Parameter vector (W in the cost function formula). + Note that ``coef_`` stores the transpose of ``W``, ``W.T``. + + alpha_ : float + The amount of penalization chosen by cross validation. + + mse_path_ : ndarray of shape (n_alphas, n_folds) or \ + (n_l1_ratio, n_alphas, n_folds) + Mean square error for the test set on each fold, varying alpha. + + alphas_ : ndarray of shape (n_alphas,) or (n_l1_ratio, n_alphas) + The grid of alphas used for fitting, for each l1_ratio. + + l1_ratio_ : float + Best l1_ratio obtained by cross-validation. + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + dual_gap_ : float + The dual gap at the end of the optimization for the optimal alpha. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MultiTaskElasticNet : Multi-task L1/L2 ElasticNet with built-in cross-validation. + ElasticNetCV : Elastic net model with best model selection by + cross-validation. + MultiTaskLassoCV : Multi-task Lasso model trained with L1 norm + as regularizer and built-in cross-validation. + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + In `fit`, once the best parameters `l1_ratio` and `alpha` are found through + cross-validation, the model is fit again using the entire training set. + + To avoid unnecessary memory duplication the `X` and `y` arguments of the + `fit` method should be directly passed as Fortran-contiguous numpy arrays. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.MultiTaskElasticNetCV(cv=3) + >>> clf.fit([[0,0], [1, 1], [2, 2]], + ... [[0, 0], [1, 1], [2, 2]]) + MultiTaskElasticNetCV(cv=3) + >>> print(clf.coef_) + [[0.52875032 0.46958558] + [0.52875032 0.46958558]] + >>> print(clf.intercept_) + [0.00166409 0.00166409] + """ + + _parameter_constraints: dict = { + **LinearModelCV._parameter_constraints, + "l1_ratio": [Interval(Real, 0, 1, closed="both"), "array-like"], + } + _parameter_constraints.pop("precompute") + _parameter_constraints.pop("positive") + + path = staticmethod(enet_path) + + def __init__( + self, + *, + l1_ratio=0.5, + eps=1e-3, + n_alphas="deprecated", + alphas="warn", + fit_intercept=True, + max_iter=1000, + tol=1e-4, + cv=None, + copy_X=True, + verbose=0, + n_jobs=None, + random_state=None, + selection="cyclic", + ): + self.l1_ratio = l1_ratio + self.eps = eps + self.n_alphas = n_alphas + self.alphas = alphas + self.fit_intercept = fit_intercept + self.max_iter = max_iter + self.tol = tol + self.cv = cv + self.copy_X = copy_X + self.verbose = verbose + self.n_jobs = n_jobs + self.random_state = random_state + self.selection = selection + + def _get_estimator(self): + return MultiTaskElasticNet() + + def _is_multitask(self): + return True + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.single_output = False + return tags + + # This is necessary as LinearModelCV now supports sample_weight while + # MultiTaskElasticNetCV does not (yet). + def fit(self, X, y, **params): + """Fit MultiTaskElasticNet model with coordinate descent. + + Fit is on grid of alphas and best alpha estimated by cross-validation. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + y : ndarray of shape (n_samples, n_targets) + Training target variable. Will be cast to X's dtype if necessary. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns MultiTaskElasticNet instance. + """ + return super().fit(X, y, **params) + + +class MultiTaskLassoCV(RegressorMixin, LinearModelCV): + """Multi-task Lasso model trained with L1/L2 mixed-norm as regularizer. + + See glossary entry for :term:`cross-validation estimator`. + + The optimization objective for MultiTaskLasso is:: + + (1 / (2 * n_samples)) * ||Y - XW||^Fro_2 + alpha * ||W||_21 + + Where:: + + ||W||_21 = \\sum_i \\sqrt{\\sum_j w_{ij}^2} + + i.e. the sum of norm of each row. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.15 + + Parameters + ---------- + eps : float, default=1e-3 + Length of the path. ``eps=1e-3`` means that + ``alpha_min / alpha_max = 1e-3``. + + n_alphas : int, default=100 + Number of alphas along the regularization path. + + .. deprecated:: 1.7 + `n_alphas` was deprecated in 1.7 and will be removed in 1.9. Use `alphas` + instead. + + alphas : array-like or int, default=None + Values of alphas to test along the regularization path. + If int, `alphas` values are generated automatically. + If array-like, list of alpha values to use. + + .. versionchanged:: 1.7 + `alphas` accepts an integer value which removes the need to pass + `n_alphas`. + + .. deprecated:: 1.7 + `alphas=None` was deprecated in 1.7 and will be removed in 1.9, at which + point the default value will be set to 100. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + max_iter : int, default=1000 + The maximum number of iterations. + + tol : float, default=1e-4 + The tolerance for the optimization: if the updates are + smaller than ``tol``, the optimization code checks the + dual gap for optimality and continues until it is smaller + than ``tol``. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + cv : int, cross-validation generator or iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - int, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + verbose : bool or int, default=False + Amount of verbosity. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. Note that this is + used only if multiple values for l1_ratio are given. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + The seed of the pseudo random number generator that selects a random + feature to update. Used when ``selection`` == 'random'. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + selection : {'cyclic', 'random'}, default='cyclic' + If set to 'random', a random coefficient is updated every iteration + rather than looping over features sequentially by default. This + (setting to 'random') often leads to significantly faster convergence + especially when tol is higher than 1e-4. + + Attributes + ---------- + intercept_ : ndarray of shape (n_targets,) + Independent term in decision function. + + coef_ : ndarray of shape (n_targets, n_features) + Parameter vector (W in the cost function formula). + Note that ``coef_`` stores the transpose of ``W``, ``W.T``. + + alpha_ : float + The amount of penalization chosen by cross validation. + + mse_path_ : ndarray of shape (n_alphas, n_folds) + Mean square error for the test set on each fold, varying alpha. + + alphas_ : ndarray of shape (n_alphas,) + The grid of alphas used for fitting. + + n_iter_ : int + Number of iterations run by the coordinate descent solver to reach + the specified tolerance for the optimal alpha. + + dual_gap_ : float + The dual gap at the end of the optimization for the optimal alpha. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + MultiTaskElasticNet : Multi-task ElasticNet model trained with L1/L2 + mixed-norm as regularizer. + ElasticNetCV : Elastic net model with best model selection by + cross-validation. + MultiTaskElasticNetCV : Multi-task L1/L2 ElasticNet with built-in + cross-validation. + + Notes + ----- + The algorithm used to fit the model is coordinate descent. + + In `fit`, once the best parameter `alpha` is found through + cross-validation, the model is fit again using the entire training set. + + To avoid unnecessary memory duplication the `X` and `y` arguments of the + `fit` method should be directly passed as Fortran-contiguous numpy arrays. + + Examples + -------- + >>> from sklearn.linear_model import MultiTaskLassoCV + >>> from sklearn.datasets import make_regression + >>> from sklearn.metrics import r2_score + >>> X, y = make_regression(n_targets=2, noise=4, random_state=0) + >>> reg = MultiTaskLassoCV(cv=5, random_state=0).fit(X, y) + >>> r2_score(y, reg.predict(X)) + 0.9994 + >>> reg.alpha_ + np.float64(0.5713) + >>> reg.predict(X[:1,]) + array([[153.7971, 94.9015]]) + """ + + _parameter_constraints: dict = { + **LinearModelCV._parameter_constraints, + } + _parameter_constraints.pop("precompute") + _parameter_constraints.pop("positive") + + path = staticmethod(lasso_path) + + def __init__( + self, + *, + eps=1e-3, + n_alphas="deprecated", + alphas="warn", + fit_intercept=True, + max_iter=1000, + tol=1e-4, + copy_X=True, + cv=None, + verbose=False, + n_jobs=None, + random_state=None, + selection="cyclic", + ): + super().__init__( + eps=eps, + n_alphas=n_alphas, + alphas=alphas, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + copy_X=copy_X, + cv=cv, + verbose=verbose, + n_jobs=n_jobs, + random_state=random_state, + selection=selection, + ) + + def _get_estimator(self): + return MultiTaskLasso() + + def _is_multitask(self): + return True + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.single_output = False + return tags + + # This is necessary as LinearModelCV now supports sample_weight while + # MultiTaskLassoCV does not (yet). + def fit(self, X, y, **params): + """Fit MultiTaskLasso model with coordinate descent. + + Fit is on grid of alphas and best alpha estimated by cross-validation. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Data. + y : ndarray of shape (n_samples, n_targets) + Target. Will be cast to X's dtype if necessary. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of fitted model. + """ + return super().fit(X, y, **params) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c471c35096f8ab59d042ea4c0758d88d8819282 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/__init__.py @@ -0,0 +1,16 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from .glm import ( + GammaRegressor, + PoissonRegressor, + TweedieRegressor, + _GeneralizedLinearRegressor, +) + +__all__ = [ + "GammaRegressor", + "PoissonRegressor", + "TweedieRegressor", + "_GeneralizedLinearRegressor", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/_newton_solver.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/_newton_solver.py new file mode 100644 index 0000000000000000000000000000000000000000..cfef023692d68102d6aee9602f31fd90854bb89d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/_newton_solver.py @@ -0,0 +1,631 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +""" +Newton solver for Generalized Linear Models +""" + +import warnings +from abc import ABC, abstractmethod + +import numpy as np +import scipy.linalg +import scipy.optimize + +from ..._loss.loss import HalfSquaredError +from ...exceptions import ConvergenceWarning +from ...utils.fixes import _get_additional_lbfgs_options_dict +from ...utils.optimize import _check_optimize_result +from .._linear_loss import LinearModelLoss + + +class NewtonSolver(ABC): + """Newton solver for GLMs. + + This class implements Newton/2nd-order optimization routines for GLMs. Each Newton + iteration aims at finding the Newton step which is done by the inner solver. With + Hessian H, gradient g and coefficients coef, one step solves: + + H @ coef_newton = -g + + For our GLM / LinearModelLoss, we have gradient g and Hessian H: + + g = X.T @ loss.gradient + l2_reg_strength * coef + H = X.T @ diag(loss.hessian) @ X + l2_reg_strength * identity + + Backtracking line search updates coef = coef_old + t * coef_newton for some t in + (0, 1]. + + This is a base class, actual implementations (child classes) may deviate from the + above pattern and use structure specific tricks. + + Usage pattern: + - initialize solver: sol = NewtonSolver(...) + - solve the problem: sol.solve(X, y, sample_weight) + + References + ---------- + - Jorge Nocedal, Stephen J. Wright. (2006) "Numerical Optimization" + 2nd edition + https://doi.org/10.1007/978-0-387-40065-5 + + - Stephen P. Boyd, Lieven Vandenberghe. (2004) "Convex Optimization." + Cambridge University Press, 2004. + https://web.stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf + + Parameters + ---------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Initial 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"). + + linear_loss : LinearModelLoss + The loss to be minimized. + + l2_reg_strength : float, default=0.0 + L2 regularization strength. + + tol : float, default=1e-4 + The optimization problem is solved when each of the following condition is + fulfilled: + 1. maximum |gradient| <= tol + 2. Newton decrement d: 1/2 * d^2 <= tol + + max_iter : int, default=100 + Maximum number of Newton steps allowed. + + n_threads : int, default=1 + Number of OpenMP threads to use for the computation of the Hessian and gradient + of the loss function. + + Attributes + ---------- + coef_old : ndarray of shape coef.shape + Coefficient of previous iteration. + + coef_newton : ndarray of shape coef.shape + Newton step. + + gradient : ndarray of shape coef.shape + Gradient of the loss w.r.t. the coefficients. + + gradient_old : ndarray of shape coef.shape + Gradient of previous iteration. + + loss_value : float + Value of objective function = loss + penalty. + + loss_value_old : float + Value of objective function of previous itertion. + + raw_prediction : ndarray of shape (n_samples,) or (n_samples, n_classes) + + converged : bool + Indicator for convergence of the solver. + + iteration : int + Number of Newton steps, i.e. calls to inner_solve + + use_fallback_lbfgs_solve : bool + If set to True, the solver will resort to call LBFGS to finish the optimisation + procedure in case of convergence issues. + + gradient_times_newton : float + gradient @ coef_newton, set in inner_solve and used by line_search. If the + Newton step is a descent direction, this is negative. + """ + + def __init__( + self, + *, + coef, + linear_loss=LinearModelLoss(base_loss=HalfSquaredError(), fit_intercept=True), + l2_reg_strength=0.0, + tol=1e-4, + max_iter=100, + n_threads=1, + verbose=0, + ): + self.coef = coef + self.linear_loss = linear_loss + self.l2_reg_strength = l2_reg_strength + self.tol = tol + self.max_iter = max_iter + self.n_threads = n_threads + self.verbose = verbose + + def setup(self, X, y, sample_weight): + """Precomputations + + If None, initializes: + - self.coef + Sets: + - self.raw_prediction + - self.loss_value + """ + _, _, self.raw_prediction = self.linear_loss.weight_intercept_raw(self.coef, X) + self.loss_value = self.linear_loss.loss( + coef=self.coef, + X=X, + y=y, + sample_weight=sample_weight, + l2_reg_strength=self.l2_reg_strength, + n_threads=self.n_threads, + raw_prediction=self.raw_prediction, + ) + + @abstractmethod + def update_gradient_hessian(self, X, y, sample_weight): + """Update gradient and Hessian.""" + + @abstractmethod + def inner_solve(self, X, y, sample_weight): + """Compute Newton step. + + Sets: + - self.coef_newton + - self.gradient_times_newton + """ + + def fallback_lbfgs_solve(self, X, y, sample_weight): + """Fallback solver in case of emergency. + + If a solver detects convergence problems, it may fall back to this methods in + the hope to exit with success instead of raising an error. + + Sets: + - self.coef + - self.converged + """ + max_iter = self.max_iter - self.iteration + opt_res = scipy.optimize.minimize( + self.linear_loss.loss_gradient, + self.coef, + method="L-BFGS-B", + jac=True, + options={ + "maxiter": max_iter, + "maxls": 50, # default is 20 + "gtol": self.tol, + "ftol": 64 * np.finfo(np.float64).eps, + **_get_additional_lbfgs_options_dict("iprint", self.verbose - 1), + }, + args=(X, y, sample_weight, self.l2_reg_strength, self.n_threads), + ) + self.iteration += _check_optimize_result("lbfgs", opt_res, max_iter=max_iter) + self.coef = opt_res.x + self.converged = opt_res.status == 0 + + def line_search(self, X, y, sample_weight): + """Backtracking line search. + + Sets: + - self.coef_old + - self.coef + - self.loss_value_old + - self.loss_value + - self.gradient_old + - self.gradient + - self.raw_prediction + """ + # line search parameters + beta, sigma = 0.5, 0.00048828125 # 1/2, 1/2**11 + eps = 16 * np.finfo(self.loss_value.dtype).eps + t = 1 # step size + + # gradient_times_newton = self.gradient @ self.coef_newton + # was computed in inner_solve. + armijo_term = sigma * self.gradient_times_newton + _, _, raw_prediction_newton = self.linear_loss.weight_intercept_raw( + self.coef_newton, X + ) + + self.coef_old = self.coef + self.loss_value_old = self.loss_value + self.gradient_old = self.gradient + + # np.sum(np.abs(self.gradient_old)) + sum_abs_grad_old = -1 + + is_verbose = self.verbose >= 2 + if is_verbose: + print(" Backtracking Line Search") + print(f" eps=16 * finfo.eps={eps}") + + for i in range(21): # until and including t = beta**20 ~ 1e-6 + self.coef = self.coef_old + t * self.coef_newton + raw = self.raw_prediction + t * raw_prediction_newton + self.loss_value, self.gradient = self.linear_loss.loss_gradient( + coef=self.coef, + X=X, + y=y, + sample_weight=sample_weight, + l2_reg_strength=self.l2_reg_strength, + n_threads=self.n_threads, + raw_prediction=raw, + ) + # Note: If coef_newton is too large, loss_gradient may produce inf values, + # potentially accompanied by a RuntimeWarning. + # This case will be captured by the Armijo condition. + + # 1. Check Armijo / sufficient decrease condition. + # The smaller (more negative) the better. + loss_improvement = self.loss_value - self.loss_value_old + check = loss_improvement <= t * armijo_term + if is_verbose: + print( + f" line search iteration={i + 1}, step size={t}\n" + f" check loss improvement <= armijo term: {loss_improvement} " + f"<= {t * armijo_term} {check}" + ) + if check: + break + # 2. Deal with relative loss differences around machine precision. + tiny_loss = np.abs(self.loss_value_old * eps) + check = np.abs(loss_improvement) <= tiny_loss + if is_verbose: + print( + " check loss |improvement| <= eps * |loss_old|:" + f" {np.abs(loss_improvement)} <= {tiny_loss} {check}" + ) + if check: + if sum_abs_grad_old < 0: + sum_abs_grad_old = scipy.linalg.norm(self.gradient_old, ord=1) + # 2.1 Check sum of absolute gradients as alternative condition. + sum_abs_grad = scipy.linalg.norm(self.gradient, ord=1) + check = sum_abs_grad < sum_abs_grad_old + if is_verbose: + print( + " check sum(|gradient|) < sum(|gradient_old|): " + f"{sum_abs_grad} < {sum_abs_grad_old} {check}" + ) + if check: + break + + t *= beta + else: + warnings.warn( + ( + f"Line search of Newton solver {self.__class__.__name__} at" + f" iteration #{self.iteration} did no converge after 21 line search" + " refinement iterations. It will now resort to lbfgs instead." + ), + ConvergenceWarning, + ) + if self.verbose: + print(" Line search did not converge and resorts to lbfgs instead.") + self.use_fallback_lbfgs_solve = True + return + + self.raw_prediction = raw + if is_verbose: + print( + f" line search successful after {i + 1} iterations with " + f"loss={self.loss_value}." + ) + + def check_convergence(self, X, y, sample_weight): + """Check for convergence. + + Sets self.converged. + """ + if self.verbose: + print(" Check Convergence") + # Note: Checking maximum relative change of coefficient <= tol is a bad + # convergence criterion because even a large step could have brought us close + # to the true minimum. + # coef_step = self.coef - self.coef_old + # change = np.max(np.abs(coef_step) / np.maximum(1, np.abs(self.coef_old))) + # check = change <= tol + + # 1. Criterion: maximum |gradient| <= tol + # The gradient was already updated in line_search() + g_max_abs = np.max(np.abs(self.gradient)) + check = g_max_abs <= self.tol + if self.verbose: + print(f" 1. max |gradient| {g_max_abs} <= {self.tol} {check}") + if not check: + return + + # 2. Criterion: For Newton decrement d, check 1/2 * d^2 <= tol + # d = sqrt(grad @ hessian^-1 @ grad) + # = sqrt(coef_newton @ hessian @ coef_newton) + # See Boyd, Vanderberghe (2009) "Convex Optimization" Chapter 9.5.1. + d2 = self.coef_newton @ self.hessian @ self.coef_newton + check = 0.5 * d2 <= self.tol + if self.verbose: + print(f" 2. Newton decrement {0.5 * d2} <= {self.tol} {check}") + if not check: + return + + if self.verbose: + loss_value = self.linear_loss.loss( + coef=self.coef, + X=X, + y=y, + sample_weight=sample_weight, + l2_reg_strength=self.l2_reg_strength, + n_threads=self.n_threads, + ) + print(f" Solver did converge at loss = {loss_value}.") + self.converged = True + + def finalize(self, X, y, sample_weight): + """Finalize the solvers results. + + Some solvers may need this, others not. + """ + pass + + def solve(self, X, y, sample_weight): + """Solve the optimization problem. + + This is the main routine. + + Order of calls: + self.setup() + while iteration: + self.update_gradient_hessian() + self.inner_solve() + self.line_search() + self.check_convergence() + self.finalize() + + Returns + ------- + coef : ndarray of shape (n_dof,), (n_classes, n_dof) or (n_classes * n_dof,) + Solution of the optimization problem. + """ + # setup usually: + # - initializes self.coef if needed + # - initializes and calculates self.raw_predictions, self.loss_value + self.setup(X=X, y=y, sample_weight=sample_weight) + + self.iteration = 1 + self.converged = False + self.use_fallback_lbfgs_solve = False + + while self.iteration <= self.max_iter and not self.converged: + if self.verbose: + print(f"Newton iter={self.iteration}") + + self.use_fallback_lbfgs_solve = False # Fallback solver. + + # 1. Update Hessian and gradient + self.update_gradient_hessian(X=X, y=y, sample_weight=sample_weight) + + # TODO: + # if iteration == 1: + # We might stop early, e.g. we already are close to the optimum, + # usually detected by zero gradients at this stage. + + # 2. Inner solver + # Calculate Newton step/direction + # This usually sets self.coef_newton and self.gradient_times_newton. + self.inner_solve(X=X, y=y, sample_weight=sample_weight) + if self.use_fallback_lbfgs_solve: + break + + # 3. Backtracking line search + # This usually sets self.coef_old, self.coef, self.loss_value_old + # self.loss_value, self.gradient_old, self.gradient, + # self.raw_prediction. + self.line_search(X=X, y=y, sample_weight=sample_weight) + if self.use_fallback_lbfgs_solve: + break + + # 4. Check convergence + # Sets self.converged. + self.check_convergence(X=X, y=y, sample_weight=sample_weight) + + # 5. Next iteration + self.iteration += 1 + + if not self.converged: + if self.use_fallback_lbfgs_solve: + # Note: The fallback solver circumvents check_convergence and relies on + # the convergence checks of lbfgs instead. Enough warnings have been + # raised on the way. + self.fallback_lbfgs_solve(X=X, y=y, sample_weight=sample_weight) + else: + warnings.warn( + ( + f"Newton solver did not converge after {self.iteration - 1} " + "iterations." + ), + ConvergenceWarning, + ) + + self.iteration -= 1 + self.finalize(X=X, y=y, sample_weight=sample_weight) + return self.coef + + +class NewtonCholeskySolver(NewtonSolver): + """Cholesky based Newton solver. + + Inner solver for finding the Newton step H w_newton = -g uses Cholesky based linear + solver. + """ + + def setup(self, X, y, sample_weight): + super().setup(X=X, y=y, sample_weight=sample_weight) + if self.linear_loss.base_loss.is_multiclass: + # Easier with ravelled arrays, e.g., for scipy.linalg.solve. + # As with LinearModelLoss, we always are contiguous in n_classes. + self.coef = self.coef.ravel(order="F") + # Note that the computation of gradient in LinearModelLoss follows the shape of + # coef. + self.gradient = np.empty_like(self.coef) + # But the hessian is always 2d. + n = self.coef.size + self.hessian = np.empty_like(self.coef, shape=(n, n)) + # To help case distinctions. + self.is_multinomial_with_intercept = ( + self.linear_loss.base_loss.is_multiclass and self.linear_loss.fit_intercept + ) + self.is_multinomial_no_penalty = ( + self.linear_loss.base_loss.is_multiclass and self.l2_reg_strength == 0 + ) + if self.is_multinomial_no_penalty: + # See inner_solve. The provided coef might not adhere to the convention + # that the last class is set to zero. + # This is done by the usual freedom of a (overparametrized) multinomial to + # add a constant to all classes which doesn't change predictions. + n_classes = self.linear_loss.base_loss.n_classes + coef = self.coef.reshape(n_classes, -1, order="F") # easier as 2d + coef -= coef[-1, :] # coef -= coef of last class + elif self.is_multinomial_with_intercept: + # See inner_solve. Same as above, but only for the intercept. + n_classes = self.linear_loss.base_loss.n_classes + # intercept -= intercept of last class + self.coef[-n_classes:] -= self.coef[-1] + + def update_gradient_hessian(self, X, y, sample_weight): + _, _, self.hessian_warning = self.linear_loss.gradient_hessian( + coef=self.coef, + X=X, + y=y, + sample_weight=sample_weight, + l2_reg_strength=self.l2_reg_strength, + n_threads=self.n_threads, + gradient_out=self.gradient, + hessian_out=self.hessian, + raw_prediction=self.raw_prediction, # this was updated in line_search + ) + + def inner_solve(self, X, y, sample_weight): + if self.hessian_warning: + warnings.warn( + ( + f"The inner solver of {self.__class__.__name__} detected a " + "pointwise hessian with many negative values at iteration " + f"#{self.iteration}. It will now resort to lbfgs instead." + ), + ConvergenceWarning, + ) + if self.verbose: + print( + " The inner solver detected a pointwise Hessian with many " + "negative values and resorts to lbfgs instead." + ) + self.use_fallback_lbfgs_solve = True + return + + # Note: The following case distinction could also be shifted to the + # implementation of HalfMultinomialLoss instead of here within the solver. + if self.is_multinomial_no_penalty: + # The multinomial loss is overparametrized for each unpenalized feature, so + # at least the intercepts. This can be seen by noting that predicted + # probabilities are invariant under shifting all coefficients of a single + # feature j for all classes by the same amount c: + # coef[k, :] -> coef[k, :] + c => proba stays the same + # where we have assumed coef.shape = (n_classes, n_features). + # Therefore, also the loss (-log-likelihood), gradient and hessian stay the + # same, see + # Noah Simon and Jerome Friedman and Trevor Hastie. (2013) "A Blockwise + # Descent Algorithm for Group-penalized Multiresponse and Multinomial + # Regression". https://doi.org/10.48550/arXiv.1311.6529 + # + # We choose the standard approach and set all the coefficients of the last + # class to zero, for all features including the intercept. + # Note that coef was already dealt with in setup. + n_classes = self.linear_loss.base_loss.n_classes + n_dof = self.coef.size // n_classes # degree of freedom per class + n = self.coef.size - n_dof # effective size + self.gradient[n_classes - 1 :: n_classes] = 0 + self.hessian[n_classes - 1 :: n_classes, :] = 0 + self.hessian[:, n_classes - 1 :: n_classes] = 0 + # We also need the reduced variants of gradient and hessian where the + # entries set to zero are removed. For 2 features and 3 classes with + # arbitrary values, "x" means removed: + # gradient = [0, 1, x, 3, 4, x] + # + # hessian = [0, 1, x, 3, 4, x] + # [1, 7, x, 9, 10, x] + # [x, x, x, x, x, x] + # [3, 9, x, 21, 22, x] + # [4, 10, x, 22, 28, x] + # [x, x, x, x, x, x] + # The following slicing triggers copies of gradient and hessian. + gradient = self.gradient.reshape(-1, n_classes)[:, :-1].flatten() + hessian = self.hessian.reshape(n_dof, n_classes, n_dof, n_classes)[ + :, :-1, :, :-1 + ].reshape(n, n) + elif self.is_multinomial_with_intercept: + # Here, only intercepts are unpenalized. We again choose the last class and + # set its intercept to zero. + # Note that coef was already dealt with in setup. + self.gradient[-1] = 0 + self.hessian[-1, :] = 0 + self.hessian[:, -1] = 0 + gradient, hessian = self.gradient[:-1], self.hessian[:-1, :-1] + else: + gradient, hessian = self.gradient, self.hessian + + try: + with warnings.catch_warnings(): + warnings.simplefilter("error", scipy.linalg.LinAlgWarning) + self.coef_newton = scipy.linalg.solve( + hessian, -gradient, check_finite=False, assume_a="sym" + ) + if self.is_multinomial_no_penalty: + self.coef_newton = np.c_[ + self.coef_newton.reshape(n_dof, n_classes - 1), np.zeros(n_dof) + ].reshape(-1) + assert self.coef_newton.flags.f_contiguous + elif self.is_multinomial_with_intercept: + self.coef_newton = np.r_[self.coef_newton, 0] + self.gradient_times_newton = self.gradient @ self.coef_newton + if self.gradient_times_newton > 0: + if self.verbose: + print( + " The inner solver found a Newton step that is not a " + "descent direction and resorts to LBFGS steps instead." + ) + self.use_fallback_lbfgs_solve = True + return + except (np.linalg.LinAlgError, scipy.linalg.LinAlgWarning) as e: + warnings.warn( + f"The inner solver of {self.__class__.__name__} stumbled upon a " + "singular or very ill-conditioned Hessian matrix at iteration " + f"{self.iteration}. It will now resort to lbfgs instead.\n" + "Further options are to use another solver or to avoid such situation " + "in the first place. Possible remedies are removing collinear features" + " of X or increasing the penalization strengths.\n" + "The original Linear Algebra message was:\n" + str(e), + scipy.linalg.LinAlgWarning, + ) + # Possible causes: + # 1. hess_pointwise is negative. But this is already taken care in + # LinearModelLoss.gradient_hessian. + # 2. X is singular or ill-conditioned + # This might be the most probable cause. + # + # There are many possible ways to deal with this situation. Most of them + # add, explicitly or implicitly, a matrix to the hessian to make it + # positive definite, confer to Chapter 3.4 of Nocedal & Wright 2nd ed. + # Instead, we resort to lbfgs. + if self.verbose: + print( + " The inner solver stumbled upon an singular or ill-conditioned " + "Hessian matrix and resorts to LBFGS instead." + ) + self.use_fallback_lbfgs_solve = True + return + + def finalize(self, X, y, sample_weight): + if self.is_multinomial_no_penalty: + # Our convention is usually the symmetric parametrization where + # sum(coef[classes, features], axis=0) = 0. + # We convert now to this convention. Note that it does not change + # the predicted probabilities. + n_classes = self.linear_loss.base_loss.n_classes + self.coef = self.coef.reshape(n_classes, -1, order="F") + self.coef -= np.mean(self.coef, axis=0) + elif self.is_multinomial_with_intercept: + # Only the intercept needs an update to the symmetric parametrization. + n_classes = self.linear_loss.base_loss.n_classes + self.coef[-n_classes:] -= np.mean(self.coef[-n_classes:]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/glm.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/glm.py new file mode 100644 index 0000000000000000000000000000000000000000..8ba24878b95b2dedbbc7bee89be5616fb5928359 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/glm.py @@ -0,0 +1,911 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +""" +Generalized Linear Models with Exponential Dispersion Family +""" + +from numbers import Integral, Real + +import numpy as np +import scipy.optimize + +from ..._loss.loss import ( + HalfGammaLoss, + HalfPoissonLoss, + HalfSquaredError, + HalfTweedieLoss, + HalfTweedieLossIdentity, +) +from ...base import BaseEstimator, RegressorMixin, _fit_context +from ...utils import check_array +from ...utils._openmp_helpers import _openmp_effective_n_threads +from ...utils._param_validation import Hidden, Interval, StrOptions +from ...utils.fixes import _get_additional_lbfgs_options_dict +from ...utils.optimize import _check_optimize_result +from ...utils.validation import _check_sample_weight, check_is_fitted, validate_data +from .._linear_loss import LinearModelLoss +from ._newton_solver import NewtonCholeskySolver, NewtonSolver + + +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) with coefficients w. + Therefore, the fit minimizes the following objective function with L2 priors as + regularizer:: + + 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, 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 separately, 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 `. + + .. versionadded:: 0.23 + + Parameters + ---------- + alpha : float, default=1 + Constant that multiplies the penalty term and thus determines the + regularization strength. ``alpha = 0`` is equivalent to unpenalized + GLMs. In this case, the design matrix `X` must have full column rank + (no collinearities). + Values must be in the range `[0.0, inf)`. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the linear predictor (X @ coef + intercept). + + solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs' + Algorithm to use in the optimization problem: + + 'lbfgs' + Calls scipy's L-BFGS-B optimizer. + + 'newton-cholesky' + Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to + iterated reweighted least squares) with an inner Cholesky based solver. + This solver is a good choice for `n_samples` >> `n_features`, especially + with one-hot encoded categorical features with rare categories. Be aware + that the memory usage of this solver has a quadratic dependency on + `n_features` because it explicitly computes the Hessian matrix. + + .. versionadded:: 1.2 + + max_iter : int, default=100 + The maximal number of iterations for the solver. + Values must be in the range `[1, inf)`. + + tol : float, default=1e-4 + Stopping criterion. For the lbfgs solver, + the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol`` + where ``g_j`` is the j-th component of the gradient (derivative) of + the objective function. + Values must be in the range `(0.0, inf)`. + + warm_start : bool, default=False + If set to ``True``, reuse the solution of the previous call to ``fit`` + as initialization for ``coef_`` and ``intercept_``. + + verbose : int, default=0 + For the lbfgs solver set verbose to any positive number for verbosity. + Values must be in the range `[0, inf)`. + + Attributes + ---------- + coef_ : array of shape (n_features,) + Estimated coefficients for the linear predictor (`X @ coef_ + + intercept_`) in the GLM. + + intercept_ : float + Intercept (a.k.a. bias) added to linear predictor. + + 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 dependent on tweedie power + HalfTweedieLossIdentity identity dependent 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)`. + """ + + # We allow for NewtonSolver classes for the "solver" parameter but do not + # make them public in the docstrings. This facilitates testing and + # benchmarking. + _parameter_constraints: dict = { + "alpha": [Interval(Real, 0.0, None, closed="left")], + "fit_intercept": ["boolean"], + "solver": [ + StrOptions({"lbfgs", "newton-cholesky"}), + Hidden(type), + ], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0.0, None, closed="neither")], + "warm_start": ["boolean"], + "verbose": ["verbose"], + } + + def __init__( + self, + *, + alpha=1.0, + fit_intercept=True, + solver="lbfgs", + max_iter=100, + tol=1e-4, + warm_start=False, + verbose=0, + ): + self.alpha = alpha + self.fit_intercept = fit_intercept + self.solver = solver + self.max_iter = max_iter + self.tol = tol + self.warm_start = warm_start + self.verbose = verbose + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit a Generalized Linear Model. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + self : object + Fitted model. + """ + X, y = validate_data( + self, + X, + y, + accept_sparse=["csc", "csr"], + dtype=[np.float64, np.float32], + y_numeric=True, + multi_output=False, + ) + + # required by losses + if self.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) + + 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=loss_dtype) + + n_samples, n_features = X.shape + self._base_loss = self._get_loss() + + linear_loss = LinearModelLoss( + base_loss=self._base_loss, + fit_intercept=self.fit_intercept, + ) + + if not linear_loss.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.__class__.__name__!r}." + ) + + # TODO: if alpha=0 check that X is not rank deficient + + # 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 + # could choose this constant such that sum(sample_weight) = 1 in order to end + # up with + # obj = sum(sample_weight * loss) + 1/2 * alpha * L2. + # But LinearModelLoss.loss() already computes + # average(loss, weights=sample_weight) + # Thus, without rescaling, we have + # obj = LinearModelLoss.loss(...) + + if self.warm_start and hasattr(self, "coef_"): + if self.fit_intercept: + # 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: + coef = linear_loss.init_zero_coef(X, dtype=loss_dtype) + if self.fit_intercept: + coef[-1] = linear_loss.base_loss.link.link( + np.average(y, weights=sample_weight) + ) + + l2_reg_strength = self.alpha + n_threads = _openmp_effective_n_threads() + + # Algorithms for optimization: + # Note again that our losses implement 1/2 * deviance. + if self.solver == "lbfgs": + func = linear_loss.loss_gradient + + opt_res = scipy.optimize.minimize( + func, + coef, + method="L-BFGS-B", + jac=True, + options={ + "maxiter": self.max_iter, + "maxls": 50, # default is 20 + "gtol": self.tol, + # The constant 64 was found empirically to pass the test suite. + # The point is that ftol is very small, but a bit larger than + # machine precision for float64, which is the dtype used by lbfgs. + "ftol": 64 * np.finfo(float).eps, + **_get_additional_lbfgs_options_dict("iprint", self.verbose - 1), + }, + args=(X, y, sample_weight, l2_reg_strength, n_threads), + ) + self.n_iter_ = _check_optimize_result( + "lbfgs", opt_res, max_iter=self.max_iter + ) + coef = opt_res.x + elif self.solver == "newton-cholesky": + sol = NewtonCholeskySolver( + coef=coef, + linear_loss=linear_loss, + l2_reg_strength=l2_reg_strength, + tol=self.tol, + max_iter=self.max_iter, + n_threads=n_threads, + verbose=self.verbose, + ) + coef = sol.solve(X, y, sample_weight) + self.n_iter_ = sol.iteration + elif issubclass(self.solver, NewtonSolver): + sol = self.solver( + coef=coef, + linear_loss=linear_loss, + l2_reg_strength=l2_reg_strength, + tol=self.tol, + max_iter=self.max_iter, + n_threads=n_threads, + ) + coef = sol.solve(X, y, sample_weight) + self.n_iter_ = sol.iteration + else: + raise ValueError(f"Invalid solver={self.solver}.") + + if self.fit_intercept: + self.intercept_ = coef[-1] + self.coef_ = coef[:-1] + else: + # set intercept to zero as the other linear models do + self.intercept_ = 0.0 + self.coef_ = coef + + return self + + 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) + Samples. + + Returns + ------- + y_pred : array of shape (n_samples,) + Returns predicted values of linear predictor. + """ + check_is_fitted(self) + X = validate_data( + self, + X, + accept_sparse=["csr", "csc", "coo"], + dtype=[np.float64, np.float32], + ensure_2d=True, + allow_nd=False, + reset=False, + ) + return X @ self.coef_ + self.intercept_ + + def predict(self, X): + """Predict using GLM with feature matrix X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Samples. + + Returns + ------- + y_pred : array of shape (n_samples,) + Returns predicted values. + """ + # check_array is done in _linear_predictor + raw_prediction = self._linear_predictor(X) + y_pred = self._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 uses the deviance of this GLM, see the + :ref:`User Guide `. + + D^2 is defined as + :math:`D^2 = 1-\\frac{D(y_{true},y_{pred})}{D_{null}}`, + :math:`D_{null}` is the null deviance, i.e. the deviance of a model + with intercept alone, which corresponds to :math:`y_{pred} = \\bar{y}`. + The mean :math:`\\bar{y}` is averaged by sample_weight. + Best possible score is 1.0 and it can be negative (because the model + can be arbitrarily worse). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Test samples. + + y : array-like of shape (n_samples,) + True values of target. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + 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) + 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._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" {base_loss.__name__}." + ) + + constant = np.average( + base_loss.constant_to_optimal_zero(y_true=y, sample_weight=None), + weights=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 __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + try: + # 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() + tags.target_tags.positive_only = not base_loss.in_y_true_range(-1.0) + except (ValueError, AttributeError, TypeError): + # This happens when the link or power parameter of TweedieRegressor is + # invalid. We fallback on the default tags in that case. + pass # pragma: no cover + return tags + + 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() + + +class PoissonRegressor(_GeneralizedLinearRegressor): + """Generalized Linear Model with a Poisson distribution. + + This regressor uses the 'log' link function. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.23 + + Parameters + ---------- + alpha : float, default=1 + Constant that multiplies the L2 penalty term and determines the + regularization strength. ``alpha = 0`` is equivalent to unpenalized + GLMs. In this case, the design matrix `X` must have full column rank + (no collinearities). + Values of `alpha` must be in the range `[0.0, inf)`. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the linear predictor (`X @ coef + intercept`). + + solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs' + Algorithm to use in the optimization problem: + + 'lbfgs' + Calls scipy's L-BFGS-B optimizer. + + 'newton-cholesky' + Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to + iterated reweighted least squares) with an inner Cholesky based solver. + This solver is a good choice for `n_samples` >> `n_features`, especially + with one-hot encoded categorical features with rare categories. Be aware + that the memory usage of this solver has a quadratic dependency on + `n_features` because it explicitly computes the Hessian matrix. + + .. versionadded:: 1.2 + + max_iter : int, default=100 + The maximal number of iterations for the solver. + Values must be in the range `[1, inf)`. + + tol : float, default=1e-4 + Stopping criterion. For the lbfgs solver, + the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol`` + where ``g_j`` is the j-th component of the gradient (derivative) of + the objective function. + Values must be in the range `(0.0, inf)`. + + warm_start : bool, default=False + If set to ``True``, reuse the solution of the previous call to ``fit`` + as initialization for ``coef_`` and ``intercept_`` . + + verbose : int, default=0 + For the lbfgs solver set verbose to any positive number for verbosity. + Values must be in the range `[0, inf)`. + + Attributes + ---------- + coef_ : array of shape (n_features,) + Estimated coefficients for the linear predictor (`X @ coef_ + + intercept_`) in the GLM. + + intercept_ : float + Intercept (a.k.a. bias) added to linear predictor. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + Actual number of iterations used in the solver. + + See Also + -------- + TweedieRegressor : Generalized Linear Model with a Tweedie distribution. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.PoissonRegressor() + >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]] + >>> y = [12, 17, 22, 21] + >>> clf.fit(X, y) + PoissonRegressor() + >>> clf.score(X, y) + np.float64(0.990) + >>> clf.coef_ + array([0.121, 0.158]) + >>> clf.intercept_ + np.float64(2.088) + >>> clf.predict([[1, 1], [3, 4]]) + array([10.676, 21.875]) + """ + + _parameter_constraints: dict = { + **_GeneralizedLinearRegressor._parameter_constraints + } + + def __init__( + self, + *, + alpha=1.0, + fit_intercept=True, + solver="lbfgs", + max_iter=100, + tol=1e-4, + warm_start=False, + verbose=0, + ): + super().__init__( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + max_iter=max_iter, + tol=tol, + warm_start=warm_start, + verbose=verbose, + ) + + def _get_loss(self): + return HalfPoissonLoss() + + +class GammaRegressor(_GeneralizedLinearRegressor): + """Generalized Linear Model with a Gamma distribution. + + This regressor uses the 'log' link function. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.23 + + Parameters + ---------- + alpha : float, default=1 + Constant that multiplies the L2 penalty term and determines the + regularization strength. ``alpha = 0`` is equivalent to unpenalized + GLMs. In this case, the design matrix `X` must have full column rank + (no collinearities). + Values of `alpha` must be in the range `[0.0, inf)`. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the linear predictor `X @ coef_ + intercept_`. + + solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs' + Algorithm to use in the optimization problem: + + 'lbfgs' + Calls scipy's L-BFGS-B optimizer. + + 'newton-cholesky' + Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to + iterated reweighted least squares) with an inner Cholesky based solver. + This solver is a good choice for `n_samples` >> `n_features`, especially + with one-hot encoded categorical features with rare categories. Be aware + that the memory usage of this solver has a quadratic dependency on + `n_features` because it explicitly computes the Hessian matrix. + + .. versionadded:: 1.2 + + max_iter : int, default=100 + The maximal number of iterations for the solver. + Values must be in the range `[1, inf)`. + + tol : float, default=1e-4 + Stopping criterion. For the lbfgs solver, + the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol`` + where ``g_j`` is the j-th component of the gradient (derivative) of + the objective function. + Values must be in the range `(0.0, inf)`. + + warm_start : bool, default=False + If set to ``True``, reuse the solution of the previous call to ``fit`` + as initialization for `coef_` and `intercept_`. + + verbose : int, default=0 + For the lbfgs solver set verbose to any positive number for verbosity. + Values must be in the range `[0, inf)`. + + Attributes + ---------- + coef_ : array of shape (n_features,) + Estimated coefficients for the linear predictor (`X @ coef_ + + intercept_`) in the GLM. + + intercept_ : float + Intercept (a.k.a. bias) added to linear predictor. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + n_iter_ : int + Actual number of iterations used in the solver. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + PoissonRegressor : Generalized Linear Model with a Poisson distribution. + TweedieRegressor : Generalized Linear Model with a Tweedie distribution. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.GammaRegressor() + >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]] + >>> y = [19, 26, 33, 30] + >>> clf.fit(X, y) + GammaRegressor() + >>> clf.score(X, y) + np.float64(0.773) + >>> clf.coef_ + array([0.073, 0.067]) + >>> clf.intercept_ + np.float64(2.896) + >>> clf.predict([[1, 0], [2, 8]]) + array([19.483, 35.795]) + """ + + _parameter_constraints: dict = { + **_GeneralizedLinearRegressor._parameter_constraints + } + + def __init__( + self, + *, + alpha=1.0, + fit_intercept=True, + solver="lbfgs", + max_iter=100, + tol=1e-4, + warm_start=False, + verbose=0, + ): + super().__init__( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + max_iter=max_iter, + tol=tol, + warm_start=warm_start, + verbose=verbose, + ) + + def _get_loss(self): + return HalfGammaLoss() + + +class TweedieRegressor(_GeneralizedLinearRegressor): + """Generalized Linear Model with a Tweedie distribution. + + This estimator can be used to model different GLMs depending on the + ``power`` parameter, which determines the underlying distribution. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.23 + + Parameters + ---------- + power : float, default=0 + The power determines the underlying target distribution according + to the following table: + + +-------+------------------------+ + | Power | Distribution | + +=======+========================+ + | 0 | Normal | + +-------+------------------------+ + | 1 | Poisson | + +-------+------------------------+ + | (1,2) | Compound Poisson Gamma | + +-------+------------------------+ + | 2 | Gamma | + +-------+------------------------+ + | 3 | Inverse Gaussian | + +-------+------------------------+ + + For ``0 < power < 1``, no distribution exists. + + alpha : float, default=1 + Constant that multiplies the L2 penalty term and determines the + regularization strength. ``alpha = 0`` is equivalent to unpenalized + GLMs. In this case, the design matrix `X` must have full column rank + (no collinearities). + Values of `alpha` must be in the range `[0.0, inf)`. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the linear predictor (`X @ coef + intercept`). + + 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 `power` parameter as follows: + + - 'identity' for ``power <= 0``, e.g. for the Normal distribution + - 'log' for ``power > 0``, e.g. for Poisson, Gamma and Inverse Gaussian + distributions + + solver : {'lbfgs', 'newton-cholesky'}, default='lbfgs' + Algorithm to use in the optimization problem: + + 'lbfgs' + Calls scipy's L-BFGS-B optimizer. + + 'newton-cholesky' + Uses Newton-Raphson steps (in arbitrary precision arithmetic equivalent to + iterated reweighted least squares) with an inner Cholesky based solver. + This solver is a good choice for `n_samples` >> `n_features`, especially + with one-hot encoded categorical features with rare categories. Be aware + that the memory usage of this solver has a quadratic dependency on + `n_features` because it explicitly computes the Hessian matrix. + + .. versionadded:: 1.2 + + max_iter : int, default=100 + The maximal number of iterations for the solver. + Values must be in the range `[1, inf)`. + + tol : float, default=1e-4 + Stopping criterion. For the lbfgs solver, + the iteration will stop when ``max{|g_j|, j = 1, ..., d} <= tol`` + where ``g_j`` is the j-th component of the gradient (derivative) of + the objective function. + Values must be in the range `(0.0, inf)`. + + warm_start : bool, default=False + If set to ``True``, reuse the solution of the previous call to ``fit`` + as initialization for ``coef_`` and ``intercept_`` . + + verbose : int, default=0 + For the lbfgs solver set verbose to any positive number for verbosity. + Values must be in the range `[0, inf)`. + + Attributes + ---------- + coef_ : array of shape (n_features,) + Estimated coefficients for the linear predictor (`X @ coef_ + + intercept_`) in the GLM. + + intercept_ : float + Intercept (a.k.a. bias) added to linear predictor. + + n_iter_ : int + Actual number of iterations used in the solver. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + PoissonRegressor : Generalized Linear Model with a Poisson distribution. + GammaRegressor : Generalized Linear Model with a Gamma distribution. + + Examples + -------- + >>> from sklearn import linear_model + >>> clf = linear_model.TweedieRegressor() + >>> X = [[1, 2], [2, 3], [3, 4], [4, 3]] + >>> y = [2, 3.5, 5, 5.5] + >>> clf.fit(X, y) + TweedieRegressor() + >>> clf.score(X, y) + np.float64(0.839) + >>> clf.coef_ + array([0.599, 0.299]) + >>> clf.intercept_ + np.float64(1.600) + >>> clf.predict([[1, 1], [3, 4]]) + array([2.500, 4.599]) + """ + + _parameter_constraints: dict = { + **_GeneralizedLinearRegressor._parameter_constraints, + "power": [Interval(Real, None, None, closed="neither")], + "link": [StrOptions({"auto", "identity", "log"})], + } + + def __init__( + self, + *, + power=0.0, + alpha=1.0, + fit_intercept=True, + link="auto", + solver="lbfgs", + max_iter=100, + tol=1e-4, + warm_start=False, + verbose=0, + ): + super().__init__( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + max_iter=max_iter, + tol=tol, + warm_start=warm_start, + verbose=verbose, + ) + self.link = link + self.power = 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) + + if self.link == "log": + return HalfTweedieLoss(power=self.power) + + if self.link == "identity": + return HalfTweedieLossIdentity(power=self.power) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd18fb94b593f0a3125c1f5833f3b9597614ba --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/__init__.py @@ -0,0 +1,2 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/test_glm.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/test_glm.py new file mode 100644 index 0000000000000000000000000000000000000000..535651f3242f531b6ef244bd1142681b96c873ff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_glm/tests/test_glm.py @@ -0,0 +1,1142 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +import warnings +from functools import partial + +import numpy as np +import pytest +import scipy +from scipy import linalg +from scipy.optimize import minimize, root + +from sklearn._loss import HalfBinomialLoss, HalfPoissonLoss, HalfTweedieLoss +from sklearn._loss.link import IdentityLink, LogLink +from sklearn.base import clone +from sklearn.datasets import make_low_rank_matrix, make_regression +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ( + GammaRegressor, + PoissonRegressor, + Ridge, + TweedieRegressor, +) +from sklearn.linear_model._glm import _GeneralizedLinearRegressor +from sklearn.linear_model._glm._newton_solver import NewtonCholeskySolver +from sklearn.linear_model._linear_loss import LinearModelLoss +from sklearn.metrics import d2_tweedie_score, mean_poisson_deviance +from sklearn.model_selection import train_test_split +from sklearn.utils._testing import assert_allclose + +SOLVERS = ["lbfgs", "newton-cholesky"] + + +class BinomialRegressor(_GeneralizedLinearRegressor): + def _get_loss(self): + return HalfBinomialLoss() + + +def _special_minimize(fun, grad, x, tol_NM, tol): + # Find good starting point by Nelder-Mead + res_NM = minimize( + fun, x, method="Nelder-Mead", options={"xatol": tol_NM, "fatol": tol_NM} + ) + # Now refine via root finding on the gradient of the function, which is + # more precise than minimizing the function itself. + res = root( + grad, + res_NM.x, + method="lm", + options={"ftol": tol, "xtol": tol, "gtol": tol}, + ) + return res.x + + +@pytest.fixture(scope="module") +def regression_data(): + X, y = make_regression( + n_samples=107, n_features=10, n_informative=80, noise=0.5, random_state=2 + ) + return X, y + + +@pytest.fixture( + params=itertools.product( + ["long", "wide"], + [ + BinomialRegressor(), + PoissonRegressor(), + GammaRegressor(), + # TweedieRegressor(power=3.0), # too difficult + # TweedieRegressor(power=0, link="log"), # too difficult + TweedieRegressor(power=1.5), + ], + ), + ids=lambda param: f"{param[0]}-{param[1]}", +) +def glm_dataset(global_random_seed, request): + """Dataset with GLM solutions, well conditioned X. + + This is inspired by ols_ridge_dataset in test_ridge.py. + + The construction is based on the SVD decomposition of X = U S V'. + + Parameters + ---------- + type : {"long", "wide"} + If "long", then n_samples > n_features. + If "wide", then n_features > n_samples. + model : a GLM model + + For "wide", we return the minimum norm solution: + + min ||w||_2 subject to w = argmin deviance(X, y, w) + + Note that the deviance is always minimized if y = inverse_link(X w) is possible to + achieve, which it is in the wide data case. Therefore, we can construct the + solution with minimum norm like (wide) OLS: + + min ||w||_2 subject to link(y) = raw_prediction = X w + + Returns + ------- + model : GLM model + X : ndarray + Last column of 1, i.e. intercept. + y : ndarray + coef_unpenalized : ndarray + Minimum norm solutions, i.e. min sum(loss(w)) (with minimum ||w||_2 in + case of ambiguity) + Last coefficient is intercept. + coef_penalized : ndarray + GLM solution with alpha=l2_reg_strength=1, i.e. + min 1/n * sum(loss) + ||w[:-1]||_2^2. + Last coefficient is intercept. + l2_reg_strength : float + Always equal 1. + """ + data_type, model = request.param + # Make larger dim more than double as big as the smaller one. + # This helps when constructing singular matrices like (X, X). + if data_type == "long": + n_samples, n_features = 12, 4 + else: + n_samples, n_features = 4, 12 + k = min(n_samples, n_features) + rng = np.random.RandomState(global_random_seed) + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features, + effective_rank=k, + tail_strength=0.1, + random_state=rng, + ) + X[:, -1] = 1 # last columns acts as intercept + U, s, Vt = linalg.svd(X, full_matrices=False) + assert np.all(s > 1e-3) # to be sure + assert np.max(s) / np.min(s) < 100 # condition number of X + + if data_type == "long": + coef_unpenalized = rng.uniform(low=1, high=3, size=n_features) + coef_unpenalized *= rng.choice([-1, 1], size=n_features) + raw_prediction = X @ coef_unpenalized + else: + raw_prediction = rng.uniform(low=-3, high=3, size=n_samples) + # minimum norm solution min ||w||_2 such that raw_prediction = X w: + # w = X'(XX')^-1 raw_prediction = V s^-1 U' raw_prediction + coef_unpenalized = Vt.T @ np.diag(1 / s) @ U.T @ raw_prediction + + linear_loss = LinearModelLoss(base_loss=model._get_loss(), fit_intercept=True) + sw = np.full(shape=n_samples, fill_value=1 / n_samples) + y = linear_loss.base_loss.link.inverse(raw_prediction) + + # Add penalty l2_reg_strength * ||coef||_2^2 for l2_reg_strength=1 and solve with + # optimizer. Note that the problem is well conditioned such that we get accurate + # results. + l2_reg_strength = 1 + fun = partial( + linear_loss.loss, + X=X[:, :-1], + y=y, + sample_weight=sw, + l2_reg_strength=l2_reg_strength, + ) + grad = partial( + linear_loss.gradient, + X=X[:, :-1], + y=y, + sample_weight=sw, + l2_reg_strength=l2_reg_strength, + ) + coef_penalized_with_intercept = _special_minimize( + fun, grad, coef_unpenalized, tol_NM=1e-6, tol=1e-14 + ) + + linear_loss = LinearModelLoss(base_loss=model._get_loss(), fit_intercept=False) + fun = partial( + linear_loss.loss, + X=X[:, :-1], + y=y, + sample_weight=sw, + l2_reg_strength=l2_reg_strength, + ) + grad = partial( + linear_loss.gradient, + X=X[:, :-1], + y=y, + sample_weight=sw, + l2_reg_strength=l2_reg_strength, + ) + coef_penalized_without_intercept = _special_minimize( + fun, grad, coef_unpenalized[:-1], tol_NM=1e-6, tol=1e-14 + ) + + # To be sure + assert np.linalg.norm(coef_penalized_with_intercept) < np.linalg.norm( + coef_unpenalized + ) + + return ( + model, + X, + y, + coef_unpenalized, + coef_penalized_with_intercept, + coef_penalized_without_intercept, + l2_reg_strength, + ) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_glm_regression(solver, fit_intercept, glm_dataset): + """Test that GLM converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + """ + model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + X = X[:, :-1] # remove intercept + if fit_intercept: + coef = coef_with_intercept + intercept = coef[-1] + coef = coef[:-1] + else: + coef = coef_without_intercept + intercept = 0 + + model.fit(X, y) + + rtol = 5e-5 if solver == "lbfgs" else 1e-9 + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, coef, rtol=rtol) + + # Same with sample_weight. + model = ( + clone(model).set_params(**params).fit(X, y, sample_weight=np.ones(X.shape[0])) + ) + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, coef, rtol=rtol) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_glm_regression_hstacked_X(solver, fit_intercept, glm_dataset): + """Test that GLM converges for all solvers to correct solution on hstacked data. + + We work with a simple constructed data set with known solution. + Fit on [X] with alpha is the same as fit on [X, X]/2 with alpha/2. + For long X, [X, X] is still a long but singular matrix. + """ + model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset + n_samples, n_features = X.shape + params = dict( + alpha=alpha / 2, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + X = X[:, :-1] # remove intercept + X = 0.5 * np.concatenate((X, X), axis=1) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features - 1) + if fit_intercept: + coef = coef_with_intercept + intercept = coef[-1] + coef = coef[:-1] + else: + coef = coef_without_intercept + intercept = 0 + + with warnings.catch_warnings(): + # XXX: Investigate if the ConvergenceWarning that can appear in some + # cases should be considered a bug or not. In the mean time we don't + # fail when the assertions below pass irrespective of the presence of + # the warning. + warnings.simplefilter("ignore", ConvergenceWarning) + model.fit(X, y) + + rtol = 2e-4 if solver == "lbfgs" else 5e-9 + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, np.r_[coef, coef], rtol=rtol) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_glm_regression_vstacked_X(solver, fit_intercept, glm_dataset): + """Test that GLM converges for all solvers to correct solution on vstacked data. + + We work with a simple constructed data set with known solution. + Fit on [X] with alpha is the same as fit on [X], [y] + [X], [y] with 1 * alpha. + It is the same alpha as the average loss stays the same. + For wide X, [X', X'] is a singular matrix. + """ + model, X, y, _, coef_with_intercept, coef_without_intercept, alpha = glm_dataset + n_samples, n_features = X.shape + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + X = X[:, :-1] # remove intercept + X = np.concatenate((X, X), axis=0) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + y = np.r_[y, y] + if fit_intercept: + coef = coef_with_intercept + intercept = coef[-1] + coef = coef[:-1] + else: + coef = coef_without_intercept + intercept = 0 + model.fit(X, y) + + rtol = 3e-5 if solver == "lbfgs" else 5e-9 + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, coef, rtol=rtol) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_glm_regression_unpenalized(solver, fit_intercept, glm_dataset): + """Test that unpenalized GLM converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + Note: This checks the minimum norm solution for wide X, i.e. + n_samples < n_features: + min ||w||_2 subject to w = argmin deviance(X, y, w) + """ + model, X, y, coef, _, _, _ = glm_dataset + n_samples, n_features = X.shape + alpha = 0 # unpenalized + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + if fit_intercept: + X = X[:, :-1] # remove intercept + intercept = coef[-1] + coef = coef[:-1] + else: + intercept = 0 + + with warnings.catch_warnings(): + if solver.startswith("newton") and n_samples < n_features: + # The newton solvers should warn and automatically fallback to LBFGS + # in this case. The model should still converge. + warnings.filterwarnings("ignore", category=scipy.linalg.LinAlgWarning) + # XXX: Investigate if the ConvergenceWarning that can appear in some + # cases should be considered a bug or not. In the mean time we don't + # fail when the assertions below pass irrespective of the presence of + # the warning. + warnings.filterwarnings("ignore", category=ConvergenceWarning) + model.fit(X, y) + + # FIXME: `assert_allclose(model.coef_, coef)` should work for all cases but fails + # for the wide/fat case with n_features > n_samples. Most current GLM solvers do + # NOT return the minimum norm solution with fit_intercept=True. + if n_samples > n_features: + rtol = 5e-5 if solver == "lbfgs" else 1e-7 + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef, rtol=rtol) + else: + # As it is an underdetermined problem, prediction = y. The following shows that + # we get a solution, i.e. a (non-unique) minimum of the objective function ... + rtol = 5e-5 + if solver == "newton-cholesky": + rtol = 5e-4 + assert_allclose(model.predict(X), y, rtol=rtol) + + norm_solution = np.linalg.norm(np.r_[intercept, coef]) + norm_model = np.linalg.norm(np.r_[model.intercept_, model.coef_]) + if solver == "newton-cholesky": + # XXX: This solver shows random behaviour. Sometimes it finds solutions + # with norm_model <= norm_solution! So we check conditionally. + if norm_model < (1 + 1e-12) * norm_solution: + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef, rtol=rtol) + elif solver == "lbfgs" and fit_intercept: + # But it is not the minimum norm solution. Otherwise the norms would be + # equal. + assert norm_model > (1 + 1e-12) * norm_solution + + # See https://github.com/scikit-learn/scikit-learn/issues/23670. + # Note: Even adding a tiny penalty does not give the minimal norm solution. + # XXX: We could have naively expected LBFGS to find the minimal norm + # solution by adding a very small penalty. Even that fails for a reason we + # do not properly understand at this point. + else: + # When `fit_intercept=False`, LBFGS naturally converges to the minimum norm + # solution on this problem. + # XXX: Do we have any theoretical guarantees why this should be the case? + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, coef, rtol=rtol) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_glm_regression_unpenalized_hstacked_X(solver, fit_intercept, glm_dataset): + """Test that unpenalized GLM converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + GLM fit on [X] is the same as fit on [X, X]/2. + For long X, [X, X] is a singular matrix and we check against the minimum norm + solution: + min ||w||_2 subject to w = argmin deviance(X, y, w) + """ + model, X, y, coef, _, _, _ = glm_dataset + n_samples, n_features = X.shape + alpha = 0 # unpenalized + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + if fit_intercept: + intercept = coef[-1] + coef = coef[:-1] + if n_samples > n_features: + X = X[:, :-1] # remove intercept + X = 0.5 * np.concatenate((X, X), axis=1) + else: + # To know the minimum norm solution, we keep one intercept column and do + # not divide by 2. Later on, we must take special care. + X = np.c_[X[:, :-1], X[:, :-1], X[:, -1]] + else: + intercept = 0 + X = 0.5 * np.concatenate((X, X), axis=1) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + + with warnings.catch_warnings(): + if solver.startswith("newton"): + # The newton solvers should warn and automatically fallback to LBFGS + # in this case. The model should still converge. + warnings.filterwarnings("ignore", category=scipy.linalg.LinAlgWarning) + # XXX: Investigate if the ConvergenceWarning that can appear in some + # cases should be considered a bug or not. In the mean time we don't + # fail when the assertions below pass irrespective of the presence of + # the warning. + warnings.filterwarnings("ignore", category=ConvergenceWarning) + model.fit(X, y) + + if fit_intercept and n_samples < n_features: + # Here we take special care. + model_intercept = 2 * model.intercept_ + model_coef = 2 * model.coef_[:-1] # exclude the other intercept term. + # For minimum norm solution, we would have + # assert model.intercept_ == pytest.approx(model.coef_[-1]) + else: + model_intercept = model.intercept_ + model_coef = model.coef_ + + if n_samples > n_features: + assert model_intercept == pytest.approx(intercept) + rtol = 1e-4 + assert_allclose(model_coef, np.r_[coef, coef], rtol=rtol) + else: + # As it is an underdetermined problem, prediction = y. The following shows that + # we get a solution, i.e. a (non-unique) minimum of the objective function ... + rtol = 1e-6 if solver == "lbfgs" else 5e-6 + assert_allclose(model.predict(X), y, rtol=rtol) + if (solver == "lbfgs" and fit_intercept) or solver == "newton-cholesky": + # Same as in test_glm_regression_unpenalized. + # But it is not the minimum norm solution. Otherwise the norms would be + # equal. + norm_solution = np.linalg.norm( + 0.5 * np.r_[intercept, intercept, coef, coef] + ) + norm_model = np.linalg.norm(np.r_[model.intercept_, model.coef_]) + assert norm_model > (1 + 1e-12) * norm_solution + # For minimum norm solution, we would have + # assert model.intercept_ == pytest.approx(model.coef_[-1]) + else: + assert model_intercept == pytest.approx(intercept, rel=5e-6) + assert_allclose(model_coef, np.r_[coef, coef], rtol=1e-4) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_glm_regression_unpenalized_vstacked_X(solver, fit_intercept, glm_dataset): + """Test that unpenalized GLM converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + GLM fit on [X] is the same as fit on [X], [y] + [X], [y]. + For wide X, [X', X'] is a singular matrix and we check against the minimum norm + solution: + min ||w||_2 subject to w = argmin deviance(X, y, w) + """ + model, X, y, coef, _, _, _ = glm_dataset + n_samples, n_features = X.shape + alpha = 0 # unpenalized + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-12, + max_iter=1000, + ) + + model = clone(model).set_params(**params) + if fit_intercept: + X = X[:, :-1] # remove intercept + intercept = coef[-1] + coef = coef[:-1] + else: + intercept = 0 + X = np.concatenate((X, X), axis=0) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + y = np.r_[y, y] + + with warnings.catch_warnings(): + if solver.startswith("newton") and n_samples < n_features: + # The newton solvers should warn and automatically fallback to LBFGS + # in this case. The model should still converge. + warnings.filterwarnings("ignore", category=scipy.linalg.LinAlgWarning) + # XXX: Investigate if the ConvergenceWarning that can appear in some + # cases should be considered a bug or not. In the mean time we don't + # fail when the assertions below pass irrespective of the presence of + # the warning. + warnings.filterwarnings("ignore", category=ConvergenceWarning) + model.fit(X, y) + + if n_samples > n_features: + rtol = 5e-5 if solver == "lbfgs" else 1e-6 + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef, rtol=rtol) + else: + # As it is an underdetermined problem, prediction = y. The following shows that + # we get a solution, i.e. a (non-unique) minimum of the objective function ... + rtol = 1e-6 if solver == "lbfgs" else 5e-6 + assert_allclose(model.predict(X), y, rtol=rtol) + + norm_solution = np.linalg.norm(np.r_[intercept, coef]) + norm_model = np.linalg.norm(np.r_[model.intercept_, model.coef_]) + if solver == "newton-cholesky": + # XXX: This solver shows random behaviour. Sometimes it finds solutions + # with norm_model <= norm_solution! So we check conditionally. + if not (norm_model > (1 + 1e-12) * norm_solution): + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef, rtol=1e-4) + elif solver == "lbfgs" and fit_intercept: + # Same as in test_glm_regression_unpenalized. + # But it is not the minimum norm solution. Otherwise the norms would be + # equal. + assert norm_model > (1 + 1e-12) * norm_solution + else: + rtol = 1e-5 if solver == "newton-cholesky" else 1e-4 + assert model.intercept_ == pytest.approx(intercept, rel=rtol) + assert_allclose(model.coef_, coef, rtol=rtol) + + +def test_sample_weights_validation(): + """Test the raised errors in the validation of sample_weight.""" + # scalar value but not positive + X = [[1]] + y = [1] + weights = 0 + glm = _GeneralizedLinearRegressor() + + # Positive weights are accepted + glm.fit(X, y, sample_weight=1) + + # 2d array + weights = [[0]] + with pytest.raises(ValueError, match="must be 1D array or scalar"): + glm.fit(X, y, weights) + + # 1d but wrong length + weights = [1, 0] + msg = r"sample_weight.shape == \(2,\), expected \(1,\)!" + with pytest.raises(ValueError, match=msg): + glm.fit(X, y, weights) + + +@pytest.mark.parametrize( + "glm", + [ + TweedieRegressor(power=3), + PoissonRegressor(), + GammaRegressor(), + TweedieRegressor(power=1.5), + ], +) +def test_glm_wrong_y_range(glm): + """ + Test that fitting a GLM model raises a ValueError when `y` contains + values outside the valid range for the given distribution. + + Generalized Linear Models (GLMs) with certain distributions, such as + Poisson, Gamma, and Tweedie (with power > 1), require `y` to be + non-negative. This test ensures that passing a `y` array containing + negative values triggers the expected ValueError with the correct message. + """ + 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( + alpha=0, + fit_intercept=fit_intercept, + tol=1e-12, + ) + if fit_intercept: + glm.fit(X[:, 1:], y) + assert_allclose(glm.coef_, coef[1:]) + assert_allclose(glm.intercept_, coef[0]) + else: + glm.fit(X, y) + assert_allclose(glm.coef_, coef) + + +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("alpha", [0.0, 1.0]) +@pytest.mark.parametrize( + "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, fit_intercept=fit_intercept) + + glm = GLMEstimator(**glm_params).fit(X, y) + coef = glm.coef_.copy() + + # sample_weight=np.ones(..) should be equivalent to sample_weight=None + sample_weight = np.ones(y.shape) + glm.fit(X, y, sample_weight=sample_weight) + assert_allclose(glm.coef_, coef) + + # sample_weight are normalized to 1 so, scaling them has no effect + sample_weight = 2 * np.ones(y.shape) + glm.fit(X, y, sample_weight=sample_weight) + assert_allclose(glm.coef_, coef) + + # setting one element of sample_weight to 0 is equivalent to removing + # the corresponding sample + sample_weight = np.ones(y.shape) + sample_weight[-1] = 0 + glm.fit(X, y, sample_weight=sample_weight) + coef1 = glm.coef_.copy() + glm.fit(X[:-1], y[:-1]) + assert_allclose(glm.coef_, coef1) + + # check that multiplying sample_weight by 2 is equivalent + # to repeating corresponding samples twice + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + y2 = np.concatenate([y, y[: n_samples // 2]]) + sample_weight_1 = np.ones(len(y)) + sample_weight_1[: n_samples // 2] = 2 + + glm1 = GLMEstimator(**glm_params).fit(X, y, sample_weight=sample_weight_1) + + glm2 = GLMEstimator(**glm_params).fit(X2, y2, sample_weight=None) + assert_allclose(glm1.coef_, glm2.coef_) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize( + "estimator", + [ + PoissonRegressor(), + GammaRegressor(), + TweedieRegressor(power=3.0), + TweedieRegressor(power=0, link="log"), + TweedieRegressor(power=1.5), + TweedieRegressor(power=4.5), + ], +) +def test_glm_log_regression(solver, fit_intercept, estimator): + """Test GLM regression with log link on a simple dataset.""" + coef = [0.2, -0.1] + X = np.array([[0, 1, 2, 3, 4], [1, 1, 1, 1, 1]]).T + y = np.exp(np.dot(X, coef)) + glm = clone(estimator).set_params( + alpha=0, + fit_intercept=fit_intercept, + solver=solver, + 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[-1], rtol=1e-6) + else: + res = glm.fit(X, y) + assert_allclose(res.coef_, coef, rtol=2e-6) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_warm_start(solver, fit_intercept, global_random_seed): + """ + Test that `warm_start=True` enables incremental fitting in PoissonRegressor. + + This test verifies that when using `warm_start=True`, the model continues + optimizing from previous coefficients instead of restarting from scratch. + It ensures that after an initial fit with `max_iter=1`, the model has a + higher objective function value (indicating incomplete optimization). + The test then checks whether allowing additional iterations enables + convergence to a solution comparable to a fresh training run (`warm_start=False`). + """ + n_samples, n_features = 100, 10 + X, y = make_regression( + n_samples=n_samples, + n_features=n_features, + n_informative=n_features - 2, + bias=fit_intercept * 1.0, + noise=1.0, + random_state=global_random_seed, + ) + y = np.abs(y) # Poisson requires non-negative targets. + alpha = 1 + params = { + "solver": solver, + "fit_intercept": fit_intercept, + "tol": 1e-10, + } + + glm1 = PoissonRegressor(warm_start=False, max_iter=1000, alpha=alpha, **params) + glm1.fit(X, y) + + glm2 = PoissonRegressor(warm_start=True, max_iter=1, alpha=alpha, **params) + # As we intentionally set max_iter=1 such that the solver should raise a + # ConvergenceWarning. + with pytest.warns(ConvergenceWarning): + glm2.fit(X, y) + + linear_loss = LinearModelLoss( + base_loss=glm1._get_loss(), + fit_intercept=fit_intercept, + ) + sw = np.full_like(y, fill_value=1 / n_samples) + + objective_glm1 = linear_loss.loss( + coef=np.r_[glm1.coef_, glm1.intercept_] if fit_intercept else glm1.coef_, + X=X, + y=y, + sample_weight=sw, + l2_reg_strength=alpha, + ) + objective_glm2 = linear_loss.loss( + coef=np.r_[glm2.coef_, glm2.intercept_] if fit_intercept else glm2.coef_, + X=X, + y=y, + sample_weight=sw, + l2_reg_strength=alpha, + ) + assert objective_glm1 < objective_glm2 + + glm2.set_params(max_iter=1000) + glm2.fit(X, y) + # The two models are not exactly identical since the lbfgs solver + # computes the approximate hessian from previous iterations, which + # will not be strictly identical in the case of a warm start. + rtol = 2e-4 if solver == "lbfgs" else 1e-9 + assert_allclose(glm1.coef_, glm2.coef_, rtol=rtol) + assert_allclose(glm1.score(X, y), glm2.score(X, y), rtol=1e-5) + + +@pytest.mark.parametrize("n_samples, n_features", [(100, 10), (10, 100)]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("sample_weight", [None, True]) +def test_normal_ridge_comparison( + n_samples, n_features, fit_intercept, sample_weight, request +): + """Compare with Ridge regression for Normal distributions.""" + test_size = 10 + X, y = make_regression( + n_samples=n_samples + test_size, + n_features=n_features, + n_informative=n_features - 2, + noise=0.5, + random_state=42, + ) + + if n_samples > n_features: + ridge_params = {"solver": "svd"} + else: + ridge_params = {"solver": "saga", "max_iter": 1000000, "tol": 1e-7} + + ( + X_train, + X_test, + y_train, + y_test, + ) = train_test_split(X, y, test_size=test_size, random_state=0) + + alpha = 1.0 + if sample_weight is None: + sw_train = None + alpha_ridge = alpha * n_samples + else: + sw_train = np.random.RandomState(0).rand(len(y_train)) + alpha_ridge = alpha * sw_train.sum() + + # GLM has 1/(2*n) * Loss + 1/2*L2, Ridge has Loss + L2 + ridge = Ridge( + alpha=alpha_ridge, + random_state=42, + fit_intercept=fit_intercept, + **ridge_params, + ) + ridge.fit(X_train, y_train, sample_weight=sw_train) + + glm = _GeneralizedLinearRegressor( + alpha=alpha, + fit_intercept=fit_intercept, + max_iter=300, + tol=1e-5, + ) + glm.fit(X_train, y_train, sample_weight=sw_train) + assert glm.coef_.shape == (X.shape[1],) + assert_allclose(glm.coef_, ridge.coef_, atol=5e-5) + assert_allclose(glm.intercept_, ridge.intercept_, rtol=1e-5) + assert_allclose(glm.predict(X_train), ridge.predict(X_train), rtol=2e-4) + assert_allclose(glm.predict(X_test), ridge.predict(X_test), rtol=2e-4) + + +@pytest.mark.parametrize("solver", ["lbfgs", "newton-cholesky"]) +def test_poisson_glmnet(solver): + """Compare Poisson regression with L2 regularization and LogLink to glmnet""" + # library("glmnet") + # options(digits=10) + # df <- data.frame(a=c(-2,-1,1,2), b=c(0,0,1,1), y=c(0,1,1,2)) + # x <- data.matrix(df[,c("a", "b")]) + # y <- df$y + # fit <- glmnet(x=x, y=y, alpha=0, intercept=T, family="poisson", + # standardize=F, thresh=1e-10, nlambda=10000) + # coef(fit, s=1) + # (Intercept) -0.12889386979 + # a 0.29019207995 + # b 0.03741173122 + X = np.array([[-2, -1, 1, 2], [0, 0, 1, 1]]).T + y = np.array([0, 1, 1, 2]) + glm = PoissonRegressor( + alpha=1, + fit_intercept=True, + tol=1e-7, + max_iter=300, + solver=solver, + ) + glm.fit(X, y) + assert_allclose(glm.intercept_, -0.12889386979, rtol=1e-5) + assert_allclose(glm.coef_, [0.29019207995, 0.03741173122], rtol=1e-5) + + +def test_convergence_warning(regression_data): + X, y = regression_data + + est = _GeneralizedLinearRegressor(max_iter=1, tol=1e-20) + with pytest.warns(ConvergenceWarning): + est.fit(X, y) + + +@pytest.mark.parametrize( + "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._base_loss.link, link_class) + + +@pytest.mark.parametrize( + "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._base_loss.link, expected_link_class) + + +@pytest.mark.parametrize("power", [0, 1, 1.5, 2, 3]) +@pytest.mark.parametrize("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( + "estimator, value", + [ + (PoissonRegressor(), True), + (GammaRegressor(), True), + (TweedieRegressor(power=1.5), True), + (TweedieRegressor(power=0), False), + ], +) +def test_tags(estimator, value): + """Test that `positive_only` tag is correctly set for different estimators.""" + assert estimator.__sklearn_tags__().target_tags.positive_only is value + + +def test_linalg_warning_with_newton_solver(global_random_seed): + """ + Test that the Newton solver raises a warning and falls back to LBFGS when + encountering a singular or ill-conditioned Hessian matrix. + + This test assess the behavior of `PoissonRegressor` with the "newton-cholesky" + solver. + It verifies the following:- + - The model significantly improves upon the constant baseline deviance. + - LBFGS remains robust on collinear data. + - The Newton solver raises a `LinAlgWarning` on collinear data and falls + back to LBFGS. + """ + newton_solver = "newton-cholesky" + rng = np.random.RandomState(global_random_seed) + # Use at least 20 samples to reduce the likelihood of getting a degenerate + # dataset for any global_random_seed. + X_orig = rng.normal(size=(20, 3)) + y = rng.poisson( + np.exp(X_orig @ np.ones(X_orig.shape[1])), size=X_orig.shape[0] + ).astype(np.float64) + + # Collinear variation of the same input features. + X_collinear = np.hstack([X_orig] * 10) + + # Let's consider the deviance of a constant baseline on this problem. + baseline_pred = np.full_like(y, y.mean()) + constant_model_deviance = mean_poisson_deviance(y, baseline_pred) + assert constant_model_deviance > 1.0 + + # No warning raised on well-conditioned design, even without regularization. + tol = 1e-10 + with warnings.catch_warnings(): + warnings.simplefilter("error") + reg = PoissonRegressor(solver=newton_solver, alpha=0.0, tol=tol).fit(X_orig, y) + original_newton_deviance = mean_poisson_deviance(y, reg.predict(X_orig)) + + # On this dataset, we should have enough data points to not make it + # possible to get a near zero deviance (for the any of the admissible + # random seeds). This will make it easier to interpret meaning of rtol in + # the subsequent assertions: + assert original_newton_deviance > 0.2 + + # We check that the model could successfully fit information in X_orig to + # improve upon the constant baseline by a large margin (when evaluated on + # the traing set). + assert constant_model_deviance - original_newton_deviance > 0.1 + + # LBFGS is robust to a collinear design because its approximation of the + # Hessian is Symmeric Positive Definite by construction. Let's record its + # solution + with warnings.catch_warnings(): + warnings.simplefilter("error") + reg = PoissonRegressor(solver="lbfgs", alpha=0.0, tol=tol).fit(X_collinear, y) + collinear_lbfgs_deviance = mean_poisson_deviance(y, reg.predict(X_collinear)) + + # The LBFGS solution on the collinear is expected to reach a comparable + # solution to the Newton solution on the original data. + rtol = 1e-6 + assert collinear_lbfgs_deviance == pytest.approx(original_newton_deviance, rel=rtol) + + # Fitting a Newton solver on the collinear version of the training data + # without regularization should raise an informative warning and fallback + # to the LBFGS solver. + msg = ( + "The inner solver of .*Newton.*Solver stumbled upon a singular or very " + "ill-conditioned Hessian matrix" + ) + with pytest.warns(scipy.linalg.LinAlgWarning, match=msg): + reg = PoissonRegressor(solver=newton_solver, alpha=0.0, tol=tol).fit( + X_collinear, y + ) + # As a result we should still automatically converge to a good solution. + collinear_newton_deviance = mean_poisson_deviance(y, reg.predict(X_collinear)) + assert collinear_newton_deviance == pytest.approx( + original_newton_deviance, rel=rtol + ) + + # Increasing the regularization slightly should make the problem go away: + with warnings.catch_warnings(): + warnings.simplefilter("error", scipy.linalg.LinAlgWarning) + reg = PoissonRegressor(solver=newton_solver, alpha=1e-10).fit(X_collinear, y) + + # The slightly penalized model on the collinear data should be close enough + # to the unpenalized model on the original data. + penalized_collinear_newton_deviance = mean_poisson_deviance( + y, reg.predict(X_collinear) + ) + assert penalized_collinear_newton_deviance == pytest.approx( + original_newton_deviance, rel=rtol + ) + + +@pytest.mark.parametrize("verbose", [0, 1, 2]) +def test_newton_solver_verbosity(capsys, verbose): + """Test the std output of verbose newton solvers.""" + y = np.array([1, 2], dtype=float) + X = np.array([[1.0, 0], [0, 1]], dtype=float) + linear_loss = LinearModelLoss(base_loss=HalfPoissonLoss(), fit_intercept=False) + sol = NewtonCholeskySolver( + coef=linear_loss.init_zero_coef(X), + linear_loss=linear_loss, + l2_reg_strength=0, + verbose=verbose, + ) + sol.solve(X, y, None) # returns array([0., 0.69314758]) + captured = capsys.readouterr() + + if verbose == 0: + assert captured.out == "" + else: + msg = [ + "Newton iter=1", + "Check Convergence", + "1. max |gradient|", + "2. Newton decrement", + "Solver did converge at loss = ", + ] + for m in msg: + assert m in captured.out + + if verbose >= 2: + msg = ["Backtracking Line Search", "line search iteration="] + for m in msg: + assert m in captured.out + + # Set the Newton solver to a state with a completely wrong Newton step. + sol = NewtonCholeskySolver( + coef=linear_loss.init_zero_coef(X), + linear_loss=linear_loss, + l2_reg_strength=0, + verbose=verbose, + ) + sol.setup(X=X, y=y, sample_weight=None) + sol.iteration = 1 + sol.update_gradient_hessian(X=X, y=y, sample_weight=None) + sol.coef_newton = np.array([1.0, 0]) + sol.gradient_times_newton = sol.gradient @ sol.coef_newton + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + sol.line_search(X=X, y=y, sample_weight=None) + captured = capsys.readouterr() + if verbose >= 1: + assert ( + "Line search did not converge and resorts to lbfgs instead." in captured.out + ) + + # Set the Newton solver to a state with bad Newton step such that the loss + # improvement in line search is tiny. + sol = NewtonCholeskySolver( + coef=np.array([1e-12, 0.69314758]), + linear_loss=linear_loss, + l2_reg_strength=0, + verbose=verbose, + ) + sol.setup(X=X, y=y, sample_weight=None) + sol.iteration = 1 + sol.update_gradient_hessian(X=X, y=y, sample_weight=None) + sol.coef_newton = np.array([1e-6, 0]) + sol.gradient_times_newton = sol.gradient @ sol.coef_newton + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + sol.line_search(X=X, y=y, sample_weight=None) + captured = capsys.readouterr() + if verbose >= 2: + msg = [ + "line search iteration=", + "check loss improvement <= armijo term:", + "check loss |improvement| <= eps * |loss_old|:", + "check sum(|gradient|) < sum(|gradient_old|):", + ] + for m in msg: + assert m in captured.out + + # Test for a case with negative hessian. We badly initialize coef for a Tweedie + # loss with non-canonical link, e.g. Inverse Gaussian deviance with a log link. + linear_loss = LinearModelLoss( + base_loss=HalfTweedieLoss(power=3), fit_intercept=False + ) + sol = NewtonCholeskySolver( + coef=linear_loss.init_zero_coef(X) + 1, + linear_loss=linear_loss, + l2_reg_strength=0, + verbose=verbose, + ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + sol.solve(X, y, None) + captured = capsys.readouterr() + if verbose >= 1: + assert ( + "The inner solver detected a pointwise Hessian with many negative values" + " and resorts to lbfgs instead." in captured.out + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_huber.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_huber.py new file mode 100644 index 0000000000000000000000000000000000000000..87e735ec998db226235f22f33477f50dc9e4152e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_huber.py @@ -0,0 +1,363 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral, Real + +import numpy as np +from scipy import optimize + +from ..base import BaseEstimator, RegressorMixin, _fit_context +from ..utils._mask import axis0_safe_slice +from ..utils._param_validation import Interval +from ..utils.extmath import safe_sparse_dot +from ..utils.fixes import _get_additional_lbfgs_options_dict +from ..utils.optimize import _check_optimize_result +from ..utils.validation import _check_sample_weight, validate_data +from ._base import LinearModel + + +def _huber_loss_and_gradient(w, X, y, epsilon, alpha, sample_weight=None): + """Returns the Huber loss and the gradient. + + Parameters + ---------- + w : ndarray, shape (n_features + 1,) or (n_features + 2,) + Feature vector. + w[:n_features] gives the coefficients + w[-1] gives the scale factor and if the intercept is fit w[-2] + gives the intercept factor. + + X : ndarray of shape (n_samples, n_features) + Input data. + + y : ndarray of shape (n_samples,) + Target vector. + + epsilon : float + Robustness of the Huber estimator. + + alpha : float + Regularization parameter. + + sample_weight : ndarray of shape (n_samples,), default=None + Weight assigned to each sample. + + Returns + ------- + loss : float + Huber loss. + + gradient : ndarray, shape (len(w)) + Returns the derivative of the Huber loss with respect to each + coefficient, intercept and the scale as a vector. + """ + _, n_features = X.shape + fit_intercept = n_features + 2 == w.shape[0] + if fit_intercept: + intercept = w[-2] + sigma = w[-1] + w = w[:n_features] + n_samples = np.sum(sample_weight) + + # Calculate the values where |y - X'w -c / sigma| > epsilon + # The values above this threshold are outliers. + linear_loss = y - safe_sparse_dot(X, w) + if fit_intercept: + linear_loss -= intercept + abs_linear_loss = np.abs(linear_loss) + outliers_mask = abs_linear_loss > epsilon * sigma + + # Calculate the linear loss due to the outliers. + # This is equal to (2 * M * |y - X'w -c / sigma| - M**2) * sigma + outliers = abs_linear_loss[outliers_mask] + num_outliers = np.count_nonzero(outliers_mask) + n_non_outliers = X.shape[0] - num_outliers + + # n_sq_outliers includes the weight give to the outliers while + # num_outliers is just the number of outliers. + outliers_sw = sample_weight[outliers_mask] + n_sw_outliers = np.sum(outliers_sw) + outlier_loss = ( + 2.0 * epsilon * np.sum(outliers_sw * outliers) + - sigma * n_sw_outliers * epsilon**2 + ) + + # Calculate the quadratic loss due to the non-outliers.- + # This is equal to |(y - X'w - c)**2 / sigma**2| * sigma + non_outliers = linear_loss[~outliers_mask] + weighted_non_outliers = sample_weight[~outliers_mask] * non_outliers + weighted_loss = np.dot(weighted_non_outliers.T, non_outliers) + squared_loss = weighted_loss / sigma + + if fit_intercept: + grad = np.zeros(n_features + 2) + else: + grad = np.zeros(n_features + 1) + + # Gradient due to the squared loss. + X_non_outliers = -axis0_safe_slice(X, ~outliers_mask, n_non_outliers) + grad[:n_features] = ( + 2.0 / sigma * safe_sparse_dot(weighted_non_outliers, X_non_outliers) + ) + + # Gradient due to the linear loss. + signed_outliers = np.ones_like(outliers) + signed_outliers_mask = linear_loss[outliers_mask] < 0 + signed_outliers[signed_outliers_mask] = -1.0 + X_outliers = axis0_safe_slice(X, outliers_mask, num_outliers) + sw_outliers = sample_weight[outliers_mask] * signed_outliers + grad[:n_features] -= 2.0 * epsilon * (safe_sparse_dot(sw_outliers, X_outliers)) + + # Gradient due to the penalty. + grad[:n_features] += alpha * 2.0 * w + + # Gradient due to sigma. + grad[-1] = n_samples + grad[-1] -= n_sw_outliers * epsilon**2 + grad[-1] -= squared_loss / sigma + + # Gradient due to the intercept. + if fit_intercept: + grad[-2] = -2.0 * np.sum(weighted_non_outliers) / sigma + grad[-2] -= 2.0 * epsilon * np.sum(sw_outliers) + + loss = n_samples * sigma + squared_loss + outlier_loss + loss += alpha * np.dot(w, w) + return loss, grad + + +class HuberRegressor(LinearModel, RegressorMixin, BaseEstimator): + """L2-regularized linear regression model that is robust to outliers. + + The Huber Regressor optimizes the squared loss for the samples where + ``|(y - Xw - c) / sigma| < epsilon`` and the absolute loss for the samples + where ``|(y - Xw - c) / sigma| > epsilon``, where the model coefficients + ``w``, the intercept ``c`` and the scale ``sigma`` are parameters + to be optimized. The parameter `sigma` makes sure that if `y` is scaled up + or down by a certain factor, one does not need to rescale `epsilon` to + achieve the same robustness. Note that this does not take into account + the fact that the different features of `X` may be of different scales. + + The Huber loss function has the advantage of not being heavily influenced + by the outliers while not completely ignoring their effect. + + Read more in the :ref:`User Guide ` + + .. versionadded:: 0.18 + + Parameters + ---------- + epsilon : float, default=1.35 + The parameter epsilon controls the number of samples that should be + classified as outliers. The smaller the epsilon, the more robust it is + to outliers. Epsilon must be in the range `[1, inf)`. + + max_iter : int, default=100 + Maximum number of iterations that + ``scipy.optimize.minimize(method="L-BFGS-B")`` should run for. + + alpha : float, default=0.0001 + Strength of the squared L2 regularization. Note that the penalty is + equal to ``alpha * ||w||^2``. + Must be in the range `[0, inf)`. + + warm_start : bool, default=False + This is useful if the stored attributes of a previously used model + has to be reused. If set to False, then the coefficients will + be rewritten for every call to fit. + See :term:`the Glossary `. + + fit_intercept : bool, default=True + Whether or not to fit the intercept. This can be set to False + if the data is already centered around the origin. + + tol : float, default=1e-05 + The iteration will stop when + ``max{|proj g_i | i = 1, ..., n}`` <= ``tol`` + where pg_i is the i-th component of the projected gradient. + + Attributes + ---------- + coef_ : array, shape (n_features,) + Features got by optimizing the L2-regularized Huber loss. + + intercept_ : float + Bias. + + scale_ : float + The value by which ``|y - Xw - c|`` is scaled down. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + Number of iterations that + ``scipy.optimize.minimize(method="L-BFGS-B")`` has run for. + + .. versionchanged:: 0.20 + + In SciPy <= 1.0.0 the number of lbfgs iterations may exceed + ``max_iter``. ``n_iter_`` will now report at most ``max_iter``. + + outliers_ : array, shape (n_samples,) + A boolean mask which is set to True where the samples are identified + as outliers. + + See Also + -------- + RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm. + TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model. + SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD. + + References + ---------- + .. [1] Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics + Concomitant scale estimates, p. 172 + .. [2] Art B. Owen (2006), `A robust hybrid of lasso and ridge regression. + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.linear_model import HuberRegressor, LinearRegression + >>> from sklearn.datasets import make_regression + >>> rng = np.random.RandomState(0) + >>> X, y, coef = make_regression( + ... n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0) + >>> X[:4] = rng.uniform(10, 20, (4, 2)) + >>> y[:4] = rng.uniform(10, 20, 4) + >>> huber = HuberRegressor().fit(X, y) + >>> huber.score(X, y) + -7.284 + >>> huber.predict(X[:1,]) + array([806.7200]) + >>> linear = LinearRegression().fit(X, y) + >>> print("True coefficients:", coef) + True coefficients: [20.4923... 34.1698...] + >>> print("Huber coefficients:", huber.coef_) + Huber coefficients: [17.7906... 31.0106...] + >>> print("Linear Regression coefficients:", linear.coef_) + Linear Regression coefficients: [-1.9221... 7.0226...] + """ + + _parameter_constraints: dict = { + "epsilon": [Interval(Real, 1.0, None, closed="left")], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "alpha": [Interval(Real, 0, None, closed="left")], + "warm_start": ["boolean"], + "fit_intercept": ["boolean"], + "tol": [Interval(Real, 0.0, None, closed="left")], + } + + def __init__( + self, + *, + epsilon=1.35, + max_iter=100, + alpha=0.0001, + warm_start=False, + fit_intercept=True, + tol=1e-05, + ): + self.epsilon = epsilon + self.max_iter = max_iter + self.alpha = alpha + self.warm_start = warm_start + self.fit_intercept = fit_intercept + self.tol = tol + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit the model according to the given training data. + + 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,) + Target vector relative to X. + + sample_weight : array-like, shape (n_samples,) + Weight given to each sample. + + Returns + ------- + self : object + Fitted `HuberRegressor` estimator. + """ + X, y = validate_data( + self, + X, + y, + copy=False, + accept_sparse=["csr"], + y_numeric=True, + dtype=[np.float64, np.float32], + ) + + sample_weight = _check_sample_weight(sample_weight, X) + + if self.warm_start and hasattr(self, "coef_"): + parameters = np.concatenate((self.coef_, [self.intercept_, self.scale_])) + else: + if self.fit_intercept: + parameters = np.zeros(X.shape[1] + 2) + else: + parameters = np.zeros(X.shape[1] + 1) + # Make sure to initialize the scale parameter to a strictly + # positive value: + parameters[-1] = 1 + + # Sigma or the scale factor should be non-negative. + # Setting it to be zero might cause undefined bounds hence we set it + # to a value close to zero. + bounds = np.tile([-np.inf, np.inf], (parameters.shape[0], 1)) + bounds[-1][0] = np.finfo(np.float64).eps * 10 + + opt_res = optimize.minimize( + _huber_loss_and_gradient, + parameters, + method="L-BFGS-B", + jac=True, + args=(X, y, self.epsilon, self.alpha, sample_weight), + options={ + "maxiter": self.max_iter, + "gtol": self.tol, + **_get_additional_lbfgs_options_dict("iprint", -1), + }, + bounds=bounds, + ) + + parameters = opt_res.x + + if opt_res.status == 2: + raise ValueError( + "HuberRegressor convergence failed: l-BFGS-b solver terminated with %s" + % opt_res.message + ) + self.n_iter_ = _check_optimize_result("lbfgs", opt_res, self.max_iter) + self.scale_ = parameters[-1] + if self.fit_intercept: + self.intercept_ = parameters[-2] + else: + self.intercept_ = 0.0 + self.coef_ = parameters[: X.shape[1]] + + residual = np.abs(y - safe_sparse_dot(X, self.coef_) - self.intercept_) + self.outliers_ = residual > self.scale_ * self.epsilon + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_least_angle.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_least_angle.py new file mode 100644 index 0000000000000000000000000000000000000000..4bffe5f6e8c0d2d6fbc05821d6553e436758c86b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_least_angle.py @@ -0,0 +1,2346 @@ +""" +Least Angle Regression algorithm. See the documentation on the +Generalized Linear Model for a complete discussion. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import sys +import warnings +from math import log +from numbers import Integral, Real + +import numpy as np +from scipy import interpolate, linalg +from scipy.linalg.lapack import get_lapack_funcs + +from ..base import MultiOutputMixin, RegressorMixin, _fit_context +from ..exceptions import ConvergenceWarning +from ..model_selection import check_cv + +# mypy error: Module 'sklearn.utils' has no attribute 'arrayfuncs' +from ..utils import ( + Bunch, + arrayfuncs, + as_float_array, + check_random_state, +) +from ..utils._metadata_requests import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils._param_validation import Hidden, Interval, StrOptions, validate_params +from ..utils.parallel import Parallel, delayed +from ..utils.validation import validate_data +from ._base import LinearModel, LinearRegression, _preprocess_data + +SOLVE_TRIANGULAR_ARGS = {"check_finite": False} + + +@validate_params( + { + "X": [np.ndarray, None], + "y": [np.ndarray, None], + "Xy": [np.ndarray, None], + "Gram": [StrOptions({"auto"}), "boolean", np.ndarray, None], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "alpha_min": [Interval(Real, 0, None, closed="left")], + "method": [StrOptions({"lar", "lasso"})], + "copy_X": ["boolean"], + "eps": [Interval(Real, 0, None, closed="neither"), None], + "copy_Gram": ["boolean"], + "verbose": ["verbose"], + "return_path": ["boolean"], + "return_n_iter": ["boolean"], + "positive": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def lars_path( + X, + y, + Xy=None, + *, + Gram=None, + max_iter=500, + alpha_min=0, + method="lar", + copy_X=True, + eps=np.finfo(float).eps, + copy_Gram=True, + verbose=0, + return_path=True, + return_n_iter=False, + positive=False, +): + """Compute Least Angle Regression or Lasso path using the LARS algorithm. + + The optimization objective for the case method='lasso' is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + in the case of method='lar', the objective function is only known in + the form of an implicit equation (see discussion in [1]_). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : None or ndarray of shape (n_samples, n_features) + Input data. If X is `None`, Gram must also be `None`. + If only the Gram matrix is available, use `lars_path_gram` instead. + + y : None or ndarray of shape (n_samples,) + Input targets. + + Xy : array-like of shape (n_features,), default=None + `Xy = X.T @ y` that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + Gram : None, 'auto', bool, ndarray of shape (n_features, n_features), \ + default=None + Precomputed Gram matrix `X.T @ X`, if `'auto'`, the Gram + matrix is precomputed from the given X, if there are more samples + than features. + + max_iter : int, default=500 + Maximum number of iterations to perform, set to infinity for no limit. + + alpha_min : float, default=0 + Minimum correlation along the path. It corresponds to the + regularization parameter `alpha` in the Lasso. + + method : {'lar', 'lasso'}, default='lar' + Specifies the returned model. Select `'lar'` for Least Angle + Regression, `'lasso'` for the Lasso. + + copy_X : bool, default=True + If `False`, `X` is overwritten. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the `tol` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_Gram : bool, default=True + If `False`, `Gram` is overwritten. + + verbose : int, default=0 + Controls output verbosity. + + return_path : bool, default=True + If `True`, returns the entire path, else returns only the + last point of the path. + + return_n_iter : bool, default=False + Whether to return the number of iterations. + + positive : bool, default=False + Restrict coefficients to be >= 0. + This option is only allowed with method 'lasso'. Note that the model + coefficients will not converge to the ordinary-least-squares solution + for small values of alpha. Only coefficients up to the smallest alpha + value (`alphas_[alphas_ > 0.].min()` when fit_path=True) reached by + the stepwise Lars-Lasso algorithm are typically in congruence with the + solution of the coordinate descent `lasso_path` function. + + Returns + ------- + alphas : ndarray of shape (n_alphas + 1,) + Maximum of covariances (in absolute value) at each iteration. + `n_alphas` is either `max_iter`, `n_features`, or the + number of nodes in the path with `alpha >= alpha_min`, whichever + is smaller. + + active : ndarray of shape (n_alphas,) + Indices of active variables at the end of the path. + + coefs : ndarray of shape (n_features, n_alphas + 1) + Coefficients along the path. + + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is set + to True. + + See Also + -------- + lars_path_gram : Compute LARS path in the sufficient stats mode. + lasso_path : Compute Lasso path with coordinate descent. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + Lars : Least Angle Regression model a.k.a. LAR. + LassoLarsCV : Cross-validated Lasso, using the LARS algorithm. + LarsCV : Cross-validated Least Angle Regression model. + sklearn.decomposition.sparse_encode : Sparse coding. + + References + ---------- + .. [1] "Least Angle Regression", Efron et al. + http://statweb.stanford.edu/~tibs/ftp/lars.pdf + + .. [2] `Wikipedia entry on the Least-angle regression + `_ + + .. [3] `Wikipedia entry on the Lasso + `_ + + Examples + -------- + >>> from sklearn.linear_model import lars_path + >>> from sklearn.datasets import make_regression + >>> X, y, true_coef = make_regression( + ... n_samples=100, n_features=5, n_informative=2, coef=True, random_state=0 + ... ) + >>> true_coef + array([ 0. , 0. , 0. , 97.9, 45.7]) + >>> alphas, _, estimated_coef = lars_path(X, y) + >>> alphas.shape + (3,) + >>> estimated_coef + array([[ 0. , 0. , 0. ], + [ 0. , 0. , 0. ], + [ 0. , 0. , 0. ], + [ 0. , 46.96, 97.99], + [ 0. , 0. , 45.70]]) + """ + if X is None and Gram is not None: + raise ValueError( + "X cannot be None if Gram is not None" + "Use lars_path_gram to avoid passing X and y." + ) + return _lars_path_solver( + X=X, + y=y, + Xy=Xy, + Gram=Gram, + n_samples=None, + max_iter=max_iter, + alpha_min=alpha_min, + method=method, + copy_X=copy_X, + eps=eps, + copy_Gram=copy_Gram, + verbose=verbose, + return_path=return_path, + return_n_iter=return_n_iter, + positive=positive, + ) + + +@validate_params( + { + "Xy": [np.ndarray], + "Gram": [np.ndarray], + "n_samples": [Interval(Integral, 0, None, closed="left")], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "alpha_min": [Interval(Real, 0, None, closed="left")], + "method": [StrOptions({"lar", "lasso"})], + "copy_X": ["boolean"], + "eps": [Interval(Real, 0, None, closed="neither"), None], + "copy_Gram": ["boolean"], + "verbose": ["verbose"], + "return_path": ["boolean"], + "return_n_iter": ["boolean"], + "positive": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def lars_path_gram( + Xy, + Gram, + *, + n_samples, + max_iter=500, + alpha_min=0, + method="lar", + copy_X=True, + eps=np.finfo(float).eps, + copy_Gram=True, + verbose=0, + return_path=True, + return_n_iter=False, + positive=False, +): + """The lars_path in the sufficient stats mode. + + The optimization objective for the case method='lasso' is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + in the case of method='lar', the objective function is only known in + the form of an implicit equation (see discussion in [1]_). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + Xy : ndarray of shape (n_features,) + `Xy = X.T @ y`. + + Gram : ndarray of shape (n_features, n_features) + `Gram = X.T @ X`. + + n_samples : int + Equivalent size of sample. + + max_iter : int, default=500 + Maximum number of iterations to perform, set to infinity for no limit. + + alpha_min : float, default=0 + Minimum correlation along the path. It corresponds to the + regularization parameter alpha parameter in the Lasso. + + method : {'lar', 'lasso'}, default='lar' + Specifies the returned model. Select `'lar'` for Least Angle + Regression, ``'lasso'`` for the Lasso. + + copy_X : bool, default=True + If `False`, `X` is overwritten. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the `tol` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_Gram : bool, default=True + If `False`, `Gram` is overwritten. + + verbose : int, default=0 + Controls output verbosity. + + return_path : bool, default=True + If `return_path==True` returns the entire path, else returns only the + last point of the path. + + return_n_iter : bool, default=False + Whether to return the number of iterations. + + positive : bool, default=False + Restrict coefficients to be >= 0. + This option is only allowed with method 'lasso'. Note that the model + coefficients will not converge to the ordinary-least-squares solution + for small values of alpha. Only coefficients up to the smallest alpha + value (`alphas_[alphas_ > 0.].min()` when `fit_path=True`) reached by + the stepwise Lars-Lasso algorithm are typically in congruence with the + solution of the coordinate descent lasso_path function. + + Returns + ------- + alphas : ndarray of shape (n_alphas + 1,) + Maximum of covariances (in absolute value) at each iteration. + `n_alphas` is either `max_iter`, `n_features` or the + number of nodes in the path with `alpha >= alpha_min`, whichever + is smaller. + + active : ndarray of shape (n_alphas,) + Indices of active variables at the end of the path. + + coefs : ndarray of shape (n_features, n_alphas + 1) + Coefficients along the path. + + n_iter : int + Number of iterations run. Returned only if `return_n_iter` is set + to True. + + See Also + -------- + lars_path_gram : Compute LARS path. + lasso_path : Compute Lasso path with coordinate descent. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + Lars : Least Angle Regression model a.k.a. LAR. + LassoLarsCV : Cross-validated Lasso, using the LARS algorithm. + LarsCV : Cross-validated Least Angle Regression model. + sklearn.decomposition.sparse_encode : Sparse coding. + + References + ---------- + .. [1] "Least Angle Regression", Efron et al. + http://statweb.stanford.edu/~tibs/ftp/lars.pdf + + .. [2] `Wikipedia entry on the Least-angle regression + `_ + + .. [3] `Wikipedia entry on the Lasso + `_ + + Examples + -------- + >>> from sklearn.linear_model import lars_path_gram + >>> from sklearn.datasets import make_regression + >>> X, y, true_coef = make_regression( + ... n_samples=100, n_features=5, n_informative=2, coef=True, random_state=0 + ... ) + >>> true_coef + array([ 0. , 0. , 0. , 97.9, 45.7]) + >>> alphas, _, estimated_coef = lars_path_gram(X.T @ y, X.T @ X, n_samples=100) + >>> alphas.shape + (3,) + >>> estimated_coef + array([[ 0. , 0. , 0. ], + [ 0. , 0. , 0. ], + [ 0. , 0. , 0. ], + [ 0. , 46.96, 97.99], + [ 0. , 0. , 45.70]]) + """ + return _lars_path_solver( + X=None, + y=None, + Xy=Xy, + Gram=Gram, + n_samples=n_samples, + max_iter=max_iter, + alpha_min=alpha_min, + method=method, + copy_X=copy_X, + eps=eps, + copy_Gram=copy_Gram, + verbose=verbose, + return_path=return_path, + return_n_iter=return_n_iter, + positive=positive, + ) + + +def _lars_path_solver( + X, + y, + Xy=None, + Gram=None, + n_samples=None, + max_iter=500, + alpha_min=0, + method="lar", + copy_X=True, + eps=np.finfo(float).eps, + copy_Gram=True, + verbose=0, + return_path=True, + return_n_iter=False, + positive=False, +): + """Compute Least Angle Regression or Lasso path using LARS algorithm [1] + + The optimization objective for the case method='lasso' is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + in the case of method='lar', the objective function is only known in + the form of an implicit equation (see discussion in [1]) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : None or ndarray of shape (n_samples, n_features) + Input data. Note that if X is None then Gram must be specified, + i.e., cannot be None or False. + + y : None or ndarray of shape (n_samples,) + Input targets. + + Xy : array-like of shape (n_features,), default=None + `Xy = np.dot(X.T, y)` that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + Gram : None, 'auto' or array-like of shape (n_features, n_features), \ + default=None + Precomputed Gram matrix `(X' * X)`, if ``'auto'``, the Gram + matrix is precomputed from the given X, if there are more samples + than features. + + n_samples : int or float, default=None + Equivalent size of sample. If `None`, it will be `n_samples`. + + max_iter : int, default=500 + Maximum number of iterations to perform, set to infinity for no limit. + + alpha_min : float, default=0 + Minimum correlation along the path. It corresponds to the + regularization parameter alpha parameter in the Lasso. + + method : {'lar', 'lasso'}, default='lar' + Specifies the returned model. Select ``'lar'`` for Least Angle + Regression, ``'lasso'`` for the Lasso. + + copy_X : bool, default=True + If ``False``, ``X`` is overwritten. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_Gram : bool, default=True + If ``False``, ``Gram`` is overwritten. + + verbose : int, default=0 + Controls output verbosity. + + return_path : bool, default=True + If ``return_path==True`` returns the entire path, else returns only the + last point of the path. + + return_n_iter : bool, default=False + Whether to return the number of iterations. + + positive : bool, default=False + Restrict coefficients to be >= 0. + This option is only allowed with method 'lasso'. Note that the model + coefficients will not converge to the ordinary-least-squares solution + for small values of alpha. Only coefficients up to the smallest alpha + value (``alphas_[alphas_ > 0.].min()`` when fit_path=True) reached by + the stepwise Lars-Lasso algorithm are typically in congruence with the + solution of the coordinate descent lasso_path function. + + Returns + ------- + alphas : array-like of shape (n_alphas + 1,) + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter``, ``n_features`` or the + number of nodes in the path with ``alpha >= alpha_min``, whichever + is smaller. + + active : array-like of shape (n_alphas,) + Indices of active variables at the end of the path. + + coefs : array-like of shape (n_features, n_alphas + 1) + Coefficients along the path + + n_iter : int + Number of iterations run. Returned only if return_n_iter is set + to True. + + See Also + -------- + lasso_path + LassoLars + Lars + LassoLarsCV + LarsCV + sklearn.decomposition.sparse_encode + + References + ---------- + .. [1] "Least Angle Regression", Efron et al. + http://statweb.stanford.edu/~tibs/ftp/lars.pdf + + .. [2] `Wikipedia entry on the Least-angle regression + `_ + + .. [3] `Wikipedia entry on the Lasso + `_ + + """ + if method == "lar" and positive: + raise ValueError("Positive constraint not supported for 'lar' coding method.") + + n_samples = n_samples if n_samples is not None else y.size + + if Xy is None: + Cov = np.dot(X.T, y) + else: + Cov = Xy.copy() + + if Gram is None or Gram is False: + Gram = None + if X is None: + raise ValueError("X and Gram cannot both be unspecified.") + elif (isinstance(Gram, str) and Gram == "auto") or Gram is True: + if Gram is True or X.shape[0] > X.shape[1]: + Gram = np.dot(X.T, X) + else: + Gram = None + elif copy_Gram: + Gram = Gram.copy() + + if Gram is None: + n_features = X.shape[1] + else: + n_features = Cov.shape[0] + if Gram.shape != (n_features, n_features): + raise ValueError("The shapes of the inputs Gram and Xy do not match.") + + if copy_X and X is not None and Gram is None: + # force copy. setting the array to be fortran-ordered + # speeds up the calculation of the (partial) Gram matrix + # and allows to easily swap columns + X = X.copy("F") + + 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), dtype=return_dtype) + alphas = np.zeros(max_features + 1, dtype=return_dtype) + else: + coef, prev_coef = ( + np.zeros(n_features, dtype=return_dtype), + np.zeros(n_features, dtype=return_dtype), + ) + alpha, prev_alpha = ( + np.array([0.0], dtype=return_dtype), + np.array([0.0], dtype=return_dtype), + ) + # above better ideas? + + n_iter, n_active = 0, 0 + active, indices = list(), np.arange(n_features) + # holds the sign of covariance + sign_active = np.empty(max_features, dtype=np.int8) + drop = False + + # will hold the cholesky factorization. Only lower part is + # referenced. + if Gram is None: + L = np.empty((max_features, max_features), dtype=X.dtype) + swap, nrm2 = linalg.get_blas_funcs(("swap", "nrm2"), (X,)) + else: + L = np.empty((max_features, max_features), dtype=Gram.dtype) + swap, nrm2 = linalg.get_blas_funcs(("swap", "nrm2"), (Cov,)) + (solve_cholesky,) = get_lapack_funcs(("potrs",), (L,)) + + if verbose: + if verbose > 1: + print("Step\t\tAdded\t\tDropped\t\tActive set size\t\tC") + else: + sys.stdout.write(".") + sys.stdout.flush() + + tiny32 = np.finfo(np.float32).tiny # to avoid division by 0 warning + cov_precision = np.finfo(Cov.dtype).precision + equality_tolerance = np.finfo(np.float32).eps + + if Gram is not None: + Gram_copy = Gram.copy() + Cov_copy = Cov.copy() + + while True: + if Cov.size: + if positive: + C_idx = np.argmax(Cov) + else: + C_idx = np.argmax(np.abs(Cov)) + + C_ = Cov[C_idx] + + if positive: + C = C_ + else: + C = np.fabs(C_) + else: + C = 0.0 + + if return_path: + alpha = alphas[n_iter, np.newaxis] + coef = coefs[n_iter] + prev_alpha = alphas[n_iter - 1, np.newaxis] + prev_coef = coefs[n_iter - 1] + + alpha[0] = C / n_samples + if alpha[0] <= alpha_min + equality_tolerance: # early stopping + if abs(alpha[0] - alpha_min) > equality_tolerance: + # interpolation factor 0 <= ss < 1 + if n_iter > 0: + # In the first iteration, all alphas are zero, the formula + # below would make ss a NaN + ss = (prev_alpha[0] - alpha_min) / (prev_alpha[0] - alpha[0]) + coef[:] = prev_coef + ss * (coef - prev_coef) + alpha[0] = alpha_min + if return_path: + coefs[n_iter] = coef + break + + if n_iter >= max_iter or n_active >= n_features: + break + if not drop: + ########################################################## + # Append x_j to the Cholesky factorization of (Xa * Xa') # + # # + # ( L 0 ) # + # L -> ( ) , where L * w = Xa' x_j # + # ( w z ) and z = ||x_j|| # + # # + ########################################################## + + if positive: + sign_active[n_active] = np.ones_like(C_) + else: + sign_active[n_active] = np.sign(C_) + m, n = n_active, C_idx + n_active + + Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0]) + indices[n], indices[m] = indices[m], indices[n] + Cov_not_shortened = Cov + Cov = Cov[1:] # remove Cov[0] + + if Gram is None: + X.T[n], X.T[m] = swap(X.T[n], X.T[m]) + c = nrm2(X.T[n_active]) ** 2 + L[n_active, :n_active] = np.dot(X.T[n_active], X.T[:n_active].T) + else: + # swap does only work inplace if matrix is fortran + # contiguous ... + Gram[m], Gram[n] = swap(Gram[m], Gram[n]) + Gram[:, m], Gram[:, n] = swap(Gram[:, m], Gram[:, n]) + c = Gram[n_active, n_active] + L[n_active, :n_active] = Gram[n_active, :n_active] + + # Update the cholesky decomposition for the Gram matrix + if n_active: + linalg.solve_triangular( + L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, + lower=1, + overwrite_b=True, + **SOLVE_TRIANGULAR_ARGS, + ) + + v = np.dot(L[n_active, :n_active], L[n_active, :n_active]) + diag = max(np.sqrt(np.abs(c - v)), eps) + L[n_active, n_active] = diag + + if diag < 1e-7: + # The system is becoming too ill-conditioned. + # We have degenerate vectors in our active set. + # We'll 'drop for good' the last regressor added. + warnings.warn( + "Regressors in active set degenerate. " + "Dropping a regressor, after %i iterations, " + "i.e. alpha=%.3e, " + "with an active set of %i regressors, and " + "the smallest cholesky pivot element being %.3e." + " Reduce max_iter or increase eps parameters." + % (n_iter, alpha.item(), n_active, diag), + ConvergenceWarning, + ) + + # XXX: need to figure a 'drop for good' way + Cov = Cov_not_shortened + Cov[0] = 0 + Cov[C_idx], Cov[0] = swap(Cov[C_idx], Cov[0]) + continue + + active.append(indices[n_active]) + n_active += 1 + + if verbose > 1: + print( + "%s\t\t%s\t\t%s\t\t%s\t\t%s" % (n_iter, active[-1], "", n_active, C) + ) + + if method == "lasso" and n_iter > 0 and prev_alpha[0] < alpha[0]: + # alpha is increasing. This is because the updates of Cov are + # bringing in too much numerical error that is greater than + # than the remaining correlation with the + # regressors. Time to bail out + warnings.warn( + "Early stopping the lars path, as the residues " + "are small and the current value of alpha is no " + "longer well controlled. %i iterations, alpha=%.3e, " + "previous alpha=%.3e, with an active set of %i " + "regressors." % (n_iter, alpha.item(), prev_alpha.item(), n_active), + ConvergenceWarning, + ) + break + + # least squares solution + least_squares, _ = solve_cholesky( + L[:n_active, :n_active], sign_active[:n_active], lower=True + ) + + if least_squares.size == 1 and least_squares == 0: + # This happens because sign_active[:n_active] = 0 + least_squares[...] = 1 + AA = 1.0 + else: + # is this really needed ? + AA = 1.0 / np.sqrt(np.sum(least_squares * sign_active[:n_active])) + + if not np.isfinite(AA): + # L is too ill-conditioned + i = 0 + L_ = L[:n_active, :n_active].copy() + while not np.isfinite(AA): + L_.flat[:: n_active + 1] += (2**i) * eps + least_squares, _ = solve_cholesky( + L_, sign_active[:n_active], lower=True + ) + tmp = max(np.sum(least_squares * sign_active[:n_active]), eps) + AA = 1.0 / np.sqrt(tmp) + i += 1 + least_squares *= AA + + if Gram is None: + # equiangular direction of variables in the active set + eq_dir = np.dot(X.T[:n_active].T, least_squares) + # correlation between each unactive variables and + # eqiangular vector + corr_eq_dir = np.dot(X.T[n_active:], eq_dir) + else: + # if huge number of features, this takes 50% of time, I + # think could be avoided if we just update it using an + # orthogonal (QR) decomposition of X + corr_eq_dir = np.dot(Gram[:n_active, n_active:].T, least_squares) + + # Explicit rounding can be necessary to avoid `np.argmax(Cov)` yielding + # unstable results because of rounding errors. + np.around(corr_eq_dir, decimals=cov_precision, out=corr_eq_dir) + + g1 = arrayfuncs.min_pos((C - Cov) / (AA - corr_eq_dir + tiny32)) + if positive: + gamma_ = min(g1, C / AA) + else: + g2 = arrayfuncs.min_pos((C + Cov) / (AA + corr_eq_dir + tiny32)) + gamma_ = min(g1, g2, C / AA) + + # TODO: better names for these variables: z + drop = False + z = -coef[active] / (least_squares + tiny32) + z_pos = arrayfuncs.min_pos(z) + if z_pos < gamma_: + # some coefficients have changed sign + idx = np.where(z == z_pos)[0][::-1] + + # update the sign, important for LAR + sign_active[idx] = -sign_active[idx] + + if method == "lasso": + gamma_ = z_pos + drop = True + + n_iter += 1 + + if return_path: + if n_iter >= coefs.shape[0]: + del coef, alpha, prev_alpha, prev_coef + # resize the coefs and alphas array + add_features = 2 * max(1, (max_features - n_active)) + coefs = np.resize(coefs, (n_iter + add_features, n_features)) + coefs[-add_features:] = 0 + alphas = np.resize(alphas, n_iter + add_features) + alphas[-add_features:] = 0 + coef = coefs[n_iter] + prev_coef = coefs[n_iter - 1] + else: + # mimic the effect of incrementing n_iter on the array references + prev_coef = coef + prev_alpha[0] = alpha[0] + coef = np.zeros_like(coef) + + coef[active] = prev_coef[active] + gamma_ * least_squares + + # update correlations + Cov -= gamma_ * corr_eq_dir + + # See if any coefficient has changed sign + if drop and method == "lasso": + # handle the case when idx is not length of 1 + for ii in idx: + arrayfuncs.cholesky_delete(L[:n_active, :n_active], ii) + + n_active -= 1 + # handle the case when idx is not length of 1 + drop_idx = [active.pop(ii) for ii in idx] + + if Gram is None: + # propagate dropped variable + for ii in idx: + for i in range(ii, n_active): + X.T[i], X.T[i + 1] = swap(X.T[i], X.T[i + 1]) + # yeah this is stupid + indices[i], indices[i + 1] = indices[i + 1], indices[i] + + # TODO: this could be updated + residual = y - np.dot(X[:, :n_active], coef[active]) + temp = np.dot(X.T[n_active], residual) + + Cov = np.r_[temp, Cov] + else: + for ii in idx: + for i in range(ii, n_active): + indices[i], indices[i + 1] = indices[i + 1], indices[i] + Gram[i], Gram[i + 1] = swap(Gram[i], Gram[i + 1]) + Gram[:, i], Gram[:, i + 1] = swap(Gram[:, i], Gram[:, i + 1]) + + # Cov_n = Cov_j + x_j * X + increment(betas) TODO: + # will this still work with multiple drops ? + + # recompute covariance. Probably could be done better + # wrong as Xy is not swapped with the rest of variables + + # TODO: this could be updated + temp = Cov_copy[drop_idx] - np.dot(Gram_copy[drop_idx], coef) + Cov = np.r_[temp, Cov] + + sign_active = np.delete(sign_active, idx) + sign_active = np.append(sign_active, 0.0) # just to maintain size + if verbose > 1: + print( + "%s\t\t%s\t\t%s\t\t%s\t\t%s" + % (n_iter, "", drop_idx, n_active, abs(temp)) + ) + + if return_path: + # resize coefs in case of early stop + alphas = alphas[: n_iter + 1] + coefs = coefs[: n_iter + 1] + + if return_n_iter: + return alphas, active, coefs.T, n_iter + else: + return alphas, active, coefs.T + else: + if return_n_iter: + return alpha, active, coef, n_iter + else: + return alpha, active, coef + + +############################################################################### +# Estimator classes + + +class Lars(MultiOutputMixin, RegressorMixin, LinearModel): + """Least Angle Regression model a.k.a. LAR. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + verbose : bool or int, default=False + Sets the verbosity amount. + + precompute : bool, 'auto' or array-like , default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + n_nonzero_coefs : int, default=500 + Target number of non-zero coefficients. Use ``np.inf`` for no limit. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + fit_path : bool, default=True + If True the full path is stored in the ``coef_path_`` attribute. + If you compute the solution for a large problem or many targets, + setting ``fit_path`` to ``False`` will lead to a speedup, especially + with a small alpha. + + jitter : float, default=None + Upper bound on a uniform noise parameter to be added to the + `y` values, to satisfy the model's assumption of + one-at-a-time computations. Might help with stability. + + .. versionadded:: 0.23 + + random_state : int, RandomState instance or None, default=None + Determines random number generation for jittering. Pass an int + for reproducible output across multiple function calls. + See :term:`Glossary `. Ignored if `jitter` is None. + + .. versionadded:: 0.23 + + Attributes + ---------- + alphas_ : array-like of shape (n_alphas + 1,) or list of such arrays + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter``, ``n_features`` or the + number of nodes in the path with ``alpha >= alpha_min``, whichever + is smaller. If this is a list of array-like, the length of the outer + list is `n_targets`. + + active_ : list of shape (n_alphas,) or list of such lists + Indices of active variables at the end of the path. + If this is a list of list, the length of the outer list is `n_targets`. + + coef_path_ : array-like of shape (n_features, n_alphas + 1) or list \ + of such arrays + The varying values of the coefficients along the path. It is not + present if the ``fit_path`` parameter is ``False``. If this is a list + of array-like, the length of the outer list is `n_targets`. + + coef_ : array-like of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the formulation formula). + + intercept_ : float or array-like of shape (n_targets,) + Independent term in decision function. + + n_iter_ : array-like or int + The number of iterations taken by lars_path to find the + grid of alphas for each target. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path: Compute Least Angle Regression or Lasso + path using LARS algorithm. + LarsCV : Cross-validated Least Angle Regression model. + sklearn.decomposition.sparse_encode : Sparse coding. + + Examples + -------- + >>> from sklearn import linear_model + >>> reg = linear_model.Lars(n_nonzero_coefs=1) + >>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1.1111, 0, -1.1111]) + Lars(n_nonzero_coefs=1) + >>> print(reg.coef_) + [ 0. -1.11] + """ + + _parameter_constraints: dict = { + "fit_intercept": ["boolean"], + "verbose": ["verbose"], + "precompute": ["boolean", StrOptions({"auto"}), np.ndarray, Hidden(None)], + "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left")], + "eps": [Interval(Real, 0, None, closed="left")], + "copy_X": ["boolean"], + "fit_path": ["boolean"], + "jitter": [Interval(Real, 0, None, closed="left"), None], + "random_state": ["random_state"], + } + + method = "lar" + positive = False + + def __init__( + self, + *, + fit_intercept=True, + verbose=False, + precompute="auto", + n_nonzero_coefs=500, + eps=np.finfo(float).eps, + copy_X=True, + fit_path=True, + jitter=None, + random_state=None, + ): + self.fit_intercept = fit_intercept + self.verbose = verbose + self.precompute = precompute + self.n_nonzero_coefs = n_nonzero_coefs + self.eps = eps + self.copy_X = copy_X + self.fit_path = fit_path + self.jitter = jitter + self.random_state = random_state + + @staticmethod + def _get_gram(precompute, X, y): + if (not hasattr(precompute, "__array__")) and ( + (precompute is True) + or (precompute == "auto" and X.shape[0] > X.shape[1]) + or (precompute == "auto" and y.shape[1] > 1) + ): + precompute = np.dot(X.T, X) + + return precompute + + def _fit(self, X, y, max_iter, alpha, fit_path, Xy=None): + """Auxiliary method to fit the model using X, y as training data""" + n_features = X.shape[1] + + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, y, fit_intercept=self.fit_intercept, copy=self.copy_X + ) + + if y.ndim == 1: + y = y[:, np.newaxis] + + n_targets = y.shape[1] + + Gram = self._get_gram(self.precompute, X, y) + + self.alphas_ = [] + self.n_iter_ = [] + self.coef_ = np.empty((n_targets, n_features), dtype=X.dtype) + + if fit_path: + self.active_ = [] + self.coef_path_ = [] + for k in range(n_targets): + this_Xy = None if Xy is None else Xy[:, k] + alphas, active, coef_path, n_iter_ = lars_path( + X, + y[:, k], + Gram=Gram, + Xy=this_Xy, + copy_X=self.copy_X, + copy_Gram=True, + alpha_min=alpha, + method=self.method, + verbose=max(0, self.verbose - 1), + max_iter=max_iter, + eps=self.eps, + return_path=True, + return_n_iter=True, + positive=self.positive, + ) + self.alphas_.append(alphas) + self.active_.append(active) + self.n_iter_.append(n_iter_) + self.coef_path_.append(coef_path) + self.coef_[k] = coef_path[:, -1] + + if n_targets == 1: + self.alphas_, self.active_, self.coef_path_, self.coef_ = [ + a[0] + for a in (self.alphas_, self.active_, self.coef_path_, self.coef_) + ] + self.n_iter_ = self.n_iter_[0] + else: + for k in range(n_targets): + this_Xy = None if Xy is None else Xy[:, k] + alphas, _, self.coef_[k], n_iter_ = lars_path( + X, + y[:, k], + Gram=Gram, + Xy=this_Xy, + copy_X=self.copy_X, + copy_Gram=True, + alpha_min=alpha, + method=self.method, + verbose=max(0, self.verbose - 1), + max_iter=max_iter, + eps=self.eps, + return_path=False, + return_n_iter=True, + positive=self.positive, + ) + self.alphas_.append(alphas) + self.n_iter_.append(n_iter_) + if n_targets == 1: + self.alphas_ = self.alphas_[0] + self.n_iter_ = self.n_iter_[0] + + self._set_intercept(X_offset, y_offset, X_scale) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, Xy=None): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + Xy : array-like of shape (n_features,) or (n_features, n_targets), \ + default=None + Xy = np.dot(X.T, y) that can be precomputed. It is useful + only when the Gram matrix is precomputed. + + Returns + ------- + self : object + Returns an instance of self. + """ + X, y = validate_data( + self, X, y, force_writeable=True, y_numeric=True, multi_output=True + ) + + alpha = getattr(self, "alpha", 0.0) + if hasattr(self, "n_nonzero_coefs"): + alpha = 0.0 # n_nonzero_coefs parametrization takes priority + max_iter = self.n_nonzero_coefs + else: + max_iter = self.max_iter + + if self.jitter is not None: + rng = check_random_state(self.random_state) + + noise = rng.uniform(high=self.jitter, size=len(y)) + y = y + noise + + self._fit( + X, + y, + max_iter=max_iter, + alpha=alpha, + fit_path=self.fit_path, + Xy=Xy, + ) + + return self + + +class LassoLars(Lars): + """Lasso model fit with Least Angle Regression a.k.a. Lars. + + It is a Linear Model trained with an L1 prior as regularizer. + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Constant that multiplies the penalty term. Defaults to 1.0. + ``alpha = 0`` is equivalent to an ordinary least square, solved + by :class:`LinearRegression`. For numerical reasons, using + ``alpha = 0`` with the LassoLars object is not advised and you + should prefer the LinearRegression object. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + verbose : bool or int, default=False + Sets the verbosity amount. + + precompute : bool, 'auto' or array-like, default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + max_iter : int, default=500 + Maximum number of iterations to perform. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + fit_path : bool, default=True + If ``True`` the full path is stored in the ``coef_path_`` attribute. + If you compute the solution for a large problem or many targets, + setting ``fit_path`` to ``False`` will lead to a speedup, especially + with a small alpha. + + positive : bool, default=False + Restrict coefficients to be >= 0. Be aware that you might want to + remove fit_intercept which is set True by default. + Under the positive restriction the model coefficients will not converge + to the ordinary-least-squares solution for small values of alpha. + Only coefficients up to the smallest alpha value (``alphas_[alphas_ > + 0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso + algorithm are typically in congruence with the solution of the + coordinate descent Lasso estimator. + + jitter : float, default=None + Upper bound on a uniform noise parameter to be added to the + `y` values, to satisfy the model's assumption of + one-at-a-time computations. Might help with stability. + + .. versionadded:: 0.23 + + random_state : int, RandomState instance or None, default=None + Determines random number generation for jittering. Pass an int + for reproducible output across multiple function calls. + See :term:`Glossary `. Ignored if `jitter` is None. + + .. versionadded:: 0.23 + + Attributes + ---------- + alphas_ : array-like of shape (n_alphas + 1,) or list of such arrays + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter``, ``n_features`` or the + number of nodes in the path with ``alpha >= alpha_min``, whichever + is smaller. If this is a list of array-like, the length of the outer + list is `n_targets`. + + active_ : list of length n_alphas or list of such lists + Indices of active variables at the end of the path. + If this is a list of list, the length of the outer list is `n_targets`. + + coef_path_ : array-like of shape (n_features, n_alphas + 1) or list \ + of such arrays + If a list is passed it's expected to be one of n_targets such arrays. + The varying values of the coefficients along the path. It is not + present if the ``fit_path`` parameter is ``False``. If this is a list + of array-like, the length of the outer list is `n_targets`. + + coef_ : array-like of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the formulation formula). + + intercept_ : float or array-like of shape (n_targets,) + Independent term in decision function. + + n_iter_ : array-like or int + The number of iterations taken by lars_path to find the + grid of alphas for each target. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso + path using LARS algorithm. + lasso_path : Compute Lasso path with coordinate descent. + Lasso : Linear Model trained with L1 prior as + regularizer (aka the Lasso). + LassoCV : Lasso linear model with iterative fitting + along a regularization path. + LassoLarsCV: Cross-validated Lasso, using the LARS algorithm. + LassoLarsIC : Lasso model fit with Lars using BIC + or AIC for model selection. + sklearn.decomposition.sparse_encode : Sparse coding. + + Examples + -------- + >>> from sklearn import linear_model + >>> reg = linear_model.LassoLars(alpha=0.01) + >>> reg.fit([[-1, 1], [0, 0], [1, 1]], [-1, 0, -1]) + LassoLars(alpha=0.01) + >>> print(reg.coef_) + [ 0. -0.955] + """ + + _parameter_constraints: dict = { + **Lars._parameter_constraints, + "alpha": [Interval(Real, 0, None, closed="left")], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "positive": ["boolean"], + } + _parameter_constraints.pop("n_nonzero_coefs") + + method = "lasso" + + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + verbose=False, + precompute="auto", + max_iter=500, + eps=np.finfo(float).eps, + copy_X=True, + fit_path=True, + positive=False, + jitter=None, + random_state=None, + ): + self.alpha = alpha + self.fit_intercept = fit_intercept + self.max_iter = max_iter + self.verbose = verbose + self.positive = positive + self.precompute = precompute + self.copy_X = copy_X + self.eps = eps + self.fit_path = fit_path + self.jitter = jitter + self.random_state = random_state + + +############################################################################### +# Cross-validated estimator classes + + +def _check_copy_and_writeable(array, copy=False): + if copy or not array.flags.writeable: + return array.copy() + return array + + +def _lars_path_residues( + X_train, + y_train, + X_test, + y_test, + Gram=None, + copy=True, + method="lar", + verbose=False, + fit_intercept=True, + max_iter=500, + eps=np.finfo(float).eps, + positive=False, +): + """Compute the residues on left-out data for a full LARS path + + Parameters + ----------- + X_train : array-like of shape (n_samples, n_features) + The data to fit the LARS on + + y_train : array-like of shape (n_samples,) + The target variable to fit LARS on + + X_test : array-like of shape (n_samples, n_features) + The data to compute the residues on + + y_test : array-like of shape (n_samples,) + The target variable to compute the residues on + + Gram : None, 'auto' or array-like of shape (n_features, n_features), \ + default=None + Precomputed Gram matrix (X' * X), if ``'auto'``, the Gram + matrix is precomputed from the given X, if there are more samples + than features + + copy : bool, default=True + Whether X_train, X_test, y_train and y_test should be copied; + if False, they may be overwritten. + + method : {'lar' , 'lasso'}, default='lar' + Specifies the returned model. Select ``'lar'`` for Least Angle + Regression, ``'lasso'`` for the Lasso. + + verbose : bool or int, default=False + Sets the amount of verbosity + + fit_intercept : bool, default=True + whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + positive : bool, default=False + Restrict coefficients to be >= 0. Be aware that you might want to + remove fit_intercept which is set True by default. + See reservations for using this option in combination with method + 'lasso' for expected small values of alpha in the doc of LassoLarsCV + and LassoLarsIC. + + max_iter : int, default=500 + Maximum number of iterations to perform. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + Returns + -------- + alphas : array-like of shape (n_alphas,) + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter`` or ``n_features``, whichever + is smaller. + + active : list + Indices of active variables at the end of the path. + + coefs : array-like of shape (n_features, n_alphas) + Coefficients along the path + + residues : array-like of shape (n_alphas, n_samples) + Residues of the prediction on the test data + """ + X_train = _check_copy_and_writeable(X_train, copy) + y_train = _check_copy_and_writeable(y_train, copy) + X_test = _check_copy_and_writeable(X_test, copy) + y_test = _check_copy_and_writeable(y_test, copy) + + if fit_intercept: + X_mean = X_train.mean(axis=0) + X_train -= X_mean + X_test -= X_mean + y_mean = y_train.mean(axis=0) + y_train = as_float_array(y_train, copy=False) + y_train -= y_mean + y_test = as_float_array(y_test, copy=False) + y_test -= y_mean + + alphas, active, coefs = lars_path( + X_train, + y_train, + Gram=Gram, + copy_X=False, + copy_Gram=False, + method=method, + verbose=max(0, verbose - 1), + max_iter=max_iter, + eps=eps, + positive=positive, + ) + residues = np.dot(X_test, coefs) - y_test[:, np.newaxis] + return alphas, active, coefs, residues.T + + +class LarsCV(Lars): + """Cross-validated Least Angle Regression model. + + See glossary entry for :term:`cross-validation estimator`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + verbose : bool or int, default=False + Sets the verbosity amount. + + max_iter : int, default=500 + Maximum number of iterations to perform. + + precompute : bool, 'auto' or array-like , default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram matrix + cannot be passed as argument since we will use only subsets of X. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + max_n_alphas : int, default=1000 + The maximum number of points on the path used to compute the + residuals in the cross-validation. + + n_jobs : int or None, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_X : bool, default=True + If ``True``, X will be copied; else, it may be overwritten. + + Attributes + ---------- + active_ : list of length n_alphas or list of such lists + Indices of active variables at the end of the path. + If this is a list of lists, the outer list length is `n_targets`. + + coef_ : array-like of shape (n_features,) + parameter vector (w in the formulation formula) + + intercept_ : float + independent term in decision function + + coef_path_ : array-like of shape (n_features, n_alphas) + the varying values of the coefficients along the path + + alpha_ : float + the estimated regularization parameter alpha + + alphas_ : array-like of shape (n_alphas,) + the different values of alpha along the path + + cv_alphas_ : array-like of shape (n_cv_alphas,) + all the values of alpha along the path for the different folds + + mse_path_ : array-like of shape (n_folds, n_cv_alphas) + the mean square error on left-out for each fold along the path + (alpha values given by ``cv_alphas``) + + n_iter_ : array-like or int + the number of iterations run by Lars with the optimal alpha. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso + path using LARS algorithm. + lasso_path : Compute Lasso path with coordinate descent. + Lasso : Linear Model trained with L1 prior as + regularizer (aka the Lasso). + LassoCV : Lasso linear model with iterative fitting + along a regularization path. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + LassoLarsIC : Lasso model fit with Lars using BIC + or AIC for model selection. + sklearn.decomposition.sparse_encode : Sparse coding. + + Notes + ----- + In `fit`, once the best parameter `alpha` is found through + cross-validation, the model is fit again using the entire training set. + + Examples + -------- + >>> from sklearn.linear_model import LarsCV + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression(n_samples=200, noise=4.0, random_state=0) + >>> reg = LarsCV(cv=5).fit(X, y) + >>> reg.score(X, y) + 0.9996 + >>> reg.alpha_ + np.float64(0.2961) + >>> reg.predict(X[:1,]) + array([154.3996]) + """ + + _parameter_constraints: dict = { + **Lars._parameter_constraints, + "max_iter": [Interval(Integral, 0, None, closed="left")], + "cv": ["cv_object"], + "max_n_alphas": [Interval(Integral, 1, None, closed="left")], + "n_jobs": [Integral, None], + } + + for parameter in ["n_nonzero_coefs", "jitter", "fit_path", "random_state"]: + _parameter_constraints.pop(parameter) + + method = "lar" + + def __init__( + self, + *, + fit_intercept=True, + verbose=False, + max_iter=500, + precompute="auto", + cv=None, + max_n_alphas=1000, + n_jobs=None, + eps=np.finfo(float).eps, + copy_X=True, + ): + self.max_iter = max_iter + self.cv = cv + self.max_n_alphas = max_n_alphas + self.n_jobs = n_jobs + super().__init__( + fit_intercept=fit_intercept, + verbose=verbose, + precompute=precompute, + n_nonzero_coefs=500, + eps=eps, + copy_X=copy_X, + fit_path=True, + ) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.multi_output = False + return tags + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, **params): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict, default=None + Parameters to be passed to the CV splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of self. + """ + _raise_for_params(params, self, "fit") + + X, y = validate_data(self, X, y, force_writeable=True, y_numeric=True) + X = as_float_array(X, copy=self.copy_X) + y = as_float_array(y, copy=self.copy_X) + + # init cross-validation generator + cv = check_cv(self.cv, classifier=False) + + if _routing_enabled(): + routed_params = process_routing(self, "fit", **params) + else: + routed_params = Bunch(splitter=Bunch(split={})) + + # As we use cross-validation, the Gram matrix is not precomputed here + Gram = self.precompute + if hasattr(Gram, "__array__"): + warnings.warn( + 'Parameter "precompute" cannot be an array in ' + '%s. Automatically switch to "auto" instead.' % self.__class__.__name__ + ) + Gram = "auto" + + cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( + delayed(_lars_path_residues)( + X[train], + y[train], + X[test], + y[test], + Gram=Gram, + copy=False, + method=self.method, + verbose=max(0, self.verbose - 1), + fit_intercept=self.fit_intercept, + max_iter=self.max_iter, + eps=self.eps, + positive=self.positive, + ) + for train, test in cv.split(X, y, **routed_params.splitter.split) + ) + all_alphas = np.concatenate(next(zip(*cv_paths))) + # Unique also sorts + all_alphas = np.unique(all_alphas) + # Take at most max_n_alphas values + stride = int(max(1, int(len(all_alphas) / float(self.max_n_alphas)))) + all_alphas = all_alphas[::stride] + + mse_path = np.empty((len(all_alphas), len(cv_paths))) + for index, (alphas, _, _, residues) in enumerate(cv_paths): + alphas = alphas[::-1] + residues = residues[::-1] + if alphas[0] != 0: + alphas = np.r_[0, alphas] + residues = np.r_[residues[0, np.newaxis], residues] + if alphas[-1] != all_alphas[-1]: + alphas = np.r_[alphas, all_alphas[-1]] + residues = np.r_[residues, residues[-1, np.newaxis]] + this_residues = interpolate.interp1d(alphas, residues, axis=0)(all_alphas) + this_residues **= 2 + mse_path[:, index] = np.mean(this_residues, axis=-1) + + mask = np.all(np.isfinite(mse_path), axis=-1) + all_alphas = all_alphas[mask] + mse_path = mse_path[mask] + # Select the alpha that minimizes left-out error + i_best_alpha = np.argmin(mse_path.mean(axis=-1)) + best_alpha = all_alphas[i_best_alpha] + + # Store our parameters + self.alpha_ = best_alpha + self.cv_alphas_ = all_alphas + self.mse_path_ = mse_path + + # Now compute the full model using best_alpha + # it will call a lasso internally when self if LassoLarsCV + # as self.method == 'lasso' + self._fit( + X, + y, + max_iter=self.max_iter, + alpha=best_alpha, + Xy=None, + fit_path=True, + ) + return self + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.4 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + splitter=check_cv(self.cv), + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + return router + + +class LassoLarsCV(LarsCV): + """Cross-validated Lasso, using the LARS algorithm. + + See glossary entry for :term:`cross-validation estimator`. + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + verbose : bool or int, default=False + Sets the verbosity amount. + + max_iter : int, default=500 + Maximum number of iterations to perform. + + precompute : bool or 'auto' , default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram matrix + cannot be passed as argument since we will use only subsets of X. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + max_n_alphas : int, default=1000 + The maximum number of points on the path used to compute the + residuals in the cross-validation. + + n_jobs : int or None, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + positive : bool, default=False + Restrict coefficients to be >= 0. Be aware that you might want to + remove fit_intercept which is set True by default. + Under the positive restriction the model coefficients do not converge + to the ordinary-least-squares solution for small values of alpha. + Only coefficients up to the smallest alpha value (``alphas_[alphas_ > + 0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso + algorithm are typically in congruence with the solution of the + coordinate descent Lasso estimator. + As a consequence using LassoLarsCV only makes sense for problems where + a sparse solution is expected and/or reached. + + Attributes + ---------- + coef_ : array-like of shape (n_features,) + parameter vector (w in the formulation formula) + + intercept_ : float + independent term in decision function. + + coef_path_ : array-like of shape (n_features, n_alphas) + the varying values of the coefficients along the path + + alpha_ : float + the estimated regularization parameter alpha + + alphas_ : array-like of shape (n_alphas,) + the different values of alpha along the path + + cv_alphas_ : array-like of shape (n_cv_alphas,) + all the values of alpha along the path for the different folds + + mse_path_ : array-like of shape (n_folds, n_cv_alphas) + the mean square error on left-out for each fold along the path + (alpha values given by ``cv_alphas``) + + n_iter_ : array-like or int + the number of iterations run by Lars with the optimal alpha. + + active_ : list of int + Indices of active variables at the end of the path. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso + path using LARS algorithm. + lasso_path : Compute Lasso path with coordinate descent. + Lasso : Linear Model trained with L1 prior as + regularizer (aka the Lasso). + LassoCV : Lasso linear model with iterative fitting + along a regularization path. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + LassoLarsIC : Lasso model fit with Lars using BIC + or AIC for model selection. + sklearn.decomposition.sparse_encode : Sparse coding. + + Notes + ----- + The object solves the same problem as the + :class:`~sklearn.linear_model.LassoCV` object. However, unlike the + :class:`~sklearn.linear_model.LassoCV`, it find the relevant alphas values + by itself. In general, because of this property, it will be more stable. + However, it is more fragile to heavily multicollinear datasets. + + It is more efficient than the :class:`~sklearn.linear_model.LassoCV` if + only a small number of features are selected compared to the total number, + for instance if there are very few samples compared to the number of + features. + + In `fit`, once the best parameter `alpha` is found through + cross-validation, the model is fit again using the entire training set. + + Examples + -------- + >>> from sklearn.linear_model import LassoLarsCV + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression(noise=4.0, random_state=0) + >>> reg = LassoLarsCV(cv=5).fit(X, y) + >>> reg.score(X, y) + 0.9993 + >>> reg.alpha_ + np.float64(0.3972) + >>> reg.predict(X[:1,]) + array([-78.4831]) + """ + + _parameter_constraints = { + **LarsCV._parameter_constraints, + "positive": ["boolean"], + } + + method = "lasso" + + def __init__( + self, + *, + fit_intercept=True, + verbose=False, + max_iter=500, + precompute="auto", + cv=None, + max_n_alphas=1000, + n_jobs=None, + eps=np.finfo(float).eps, + copy_X=True, + positive=False, + ): + self.fit_intercept = fit_intercept + self.verbose = verbose + self.max_iter = max_iter + self.precompute = precompute + self.cv = cv + self.max_n_alphas = max_n_alphas + self.n_jobs = n_jobs + self.eps = eps + self.copy_X = copy_X + self.positive = positive + # XXX : we don't use super().__init__ + # to avoid setting n_nonzero_coefs + + +class LassoLarsIC(LassoLars): + """Lasso model fit with Lars using BIC or AIC for model selection. + + The optimization objective for Lasso is:: + + (1 / (2 * n_samples)) * ||y - Xw||^2_2 + alpha * ||w||_1 + + AIC is the Akaike information criterion [2]_ and BIC is the Bayes + Information criterion [3]_. Such criteria are useful to select the value + of the regularization parameter by making a trade-off between the + goodness of fit and the complexity of the model. A good model should + explain well the data while being simple. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + criterion : {'aic', 'bic'}, default='aic' + The type of criterion to use. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + verbose : bool or int, default=False + Sets the verbosity amount. + + precompute : bool, 'auto' or array-like, default='auto' + Whether to use a precomputed Gram matrix to speed up + calculations. If set to ``'auto'`` let us decide. The Gram + matrix can also be passed as argument. + + max_iter : int, default=500 + Maximum number of iterations to perform. Can be used for + early stopping. + + eps : float, default=np.finfo(float).eps + The machine-precision regularization in the computation of the + Cholesky diagonal factors. Increase this for very ill-conditioned + systems. Unlike the ``tol`` parameter in some iterative + optimization-based algorithms, this parameter does not control + the tolerance of the optimization. + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + positive : bool, default=False + Restrict coefficients to be >= 0. Be aware that you might want to + remove fit_intercept which is set True by default. + Under the positive restriction the model coefficients do not converge + to the ordinary-least-squares solution for small values of alpha. + Only coefficients up to the smallest alpha value (``alphas_[alphas_ > + 0.].min()`` when fit_path=True) reached by the stepwise Lars-Lasso + algorithm are typically in congruence with the solution of the + coordinate descent Lasso estimator. + As a consequence using LassoLarsIC only makes sense for problems where + a sparse solution is expected and/or reached. + + noise_variance : float, default=None + The estimated noise variance of the data. If `None`, an unbiased + estimate is computed by an OLS model. However, it is only possible + in the case where `n_samples > n_features + fit_intercept`. + + .. versionadded:: 1.1 + + Attributes + ---------- + coef_ : array-like of shape (n_features,) + parameter vector (w in the formulation formula) + + intercept_ : float + independent term in decision function. + + alpha_ : float + the alpha parameter chosen by the information criterion + + alphas_ : array-like of shape (n_alphas + 1,) or list of such arrays + Maximum of covariances (in absolute value) at each iteration. + ``n_alphas`` is either ``max_iter``, ``n_features`` or the + number of nodes in the path with ``alpha >= alpha_min``, whichever + is smaller. If a list, it will be of length `n_targets`. + + n_iter_ : int + number of iterations run by lars_path to find the grid of + alphas. + + criterion_ : array-like of shape (n_alphas,) + The value of the information criteria ('aic', 'bic') across all + alphas. The alpha which has the smallest information criterion is + chosen, as specified in [1]_. + + noise_variance_ : float + The estimated noise variance from the data used to compute the + criterion. + + .. versionadded:: 1.1 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + lars_path : Compute Least Angle Regression or Lasso + path using LARS algorithm. + lasso_path : Compute Lasso path with coordinate descent. + Lasso : Linear Model trained with L1 prior as + regularizer (aka the Lasso). + LassoCV : Lasso linear model with iterative fitting + along a regularization path. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + LassoLarsCV: Cross-validated Lasso, using the LARS algorithm. + sklearn.decomposition.sparse_encode : Sparse coding. + + Notes + ----- + The number of degrees of freedom is computed as in [1]_. + + To have more details regarding the mathematical formulation of the + AIC and BIC criteria, please refer to :ref:`User Guide `. + + References + ---------- + .. [1] :arxiv:`Zou, Hui, Trevor Hastie, and Robert Tibshirani. + "On the degrees of freedom of the lasso." + The Annals of Statistics 35.5 (2007): 2173-2192. + <0712.0881>` + + .. [2] `Wikipedia entry on the Akaike information criterion + `_ + + .. [3] `Wikipedia entry on the Bayesian information criterion + `_ + + Examples + -------- + >>> from sklearn import linear_model + >>> reg = linear_model.LassoLarsIC(criterion='bic') + >>> X = [[-2, 2], [-1, 1], [0, 0], [1, 1], [2, 2]] + >>> y = [-2.2222, -1.1111, 0, -1.1111, -2.2222] + >>> reg.fit(X, y) + LassoLarsIC(criterion='bic') + >>> print(reg.coef_) + [ 0. -1.11] + """ + + _parameter_constraints: dict = { + **LassoLars._parameter_constraints, + "criterion": [StrOptions({"aic", "bic"})], + "noise_variance": [Interval(Real, 0, None, closed="left"), None], + } + + for parameter in ["jitter", "fit_path", "alpha", "random_state"]: + _parameter_constraints.pop(parameter) + + def __init__( + self, + criterion="aic", + *, + fit_intercept=True, + verbose=False, + precompute="auto", + max_iter=500, + eps=np.finfo(float).eps, + copy_X=True, + positive=False, + noise_variance=None, + ): + self.criterion = criterion + self.fit_intercept = fit_intercept + self.positive = positive + self.max_iter = max_iter + self.verbose = verbose + self.copy_X = copy_X + self.precompute = precompute + self.eps = eps + self.fit_path = True + self.noise_variance = noise_variance + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.multi_output = False + return tags + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, copy_X=None): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. Will be cast to X's dtype if necessary. + + copy_X : bool, default=None + If provided, this parameter will override the choice + of copy_X made at instance creation. + If ``True``, X will be copied; else, it may be overwritten. + + Returns + ------- + self : object + Returns an instance of self. + """ + if copy_X is None: + copy_X = self.copy_X + X, y = validate_data(self, X, y, force_writeable=True, y_numeric=True) + + X, y, Xmean, ymean, Xstd = _preprocess_data( + X, y, fit_intercept=self.fit_intercept, copy=copy_X + ) + + Gram = self.precompute + + alphas_, _, coef_path_, self.n_iter_ = lars_path( + X, + y, + Gram=Gram, + copy_X=copy_X, + copy_Gram=True, + alpha_min=0.0, + method="lasso", + verbose=self.verbose, + max_iter=self.max_iter, + eps=self.eps, + return_n_iter=True, + positive=self.positive, + ) + + n_samples = X.shape[0] + + if self.criterion == "aic": + criterion_factor = 2 + elif self.criterion == "bic": + criterion_factor = log(n_samples) + else: + raise ValueError( + f"criterion should be either bic or aic, got {self.criterion!r}" + ) + + residuals = y[:, np.newaxis] - np.dot(X, coef_path_) + residuals_sum_squares = np.sum(residuals**2, axis=0) + degrees_of_freedom = np.zeros(coef_path_.shape[1], dtype=int) + for k, coef in enumerate(coef_path_.T): + mask = np.abs(coef) > np.finfo(coef.dtype).eps + if not np.any(mask): + continue + # get the number of degrees of freedom equal to: + # Xc = X[:, mask] + # Trace(Xc * inv(Xc.T, Xc) * Xc.T) ie the number of non-zero coefs + degrees_of_freedom[k] = np.sum(mask) + + self.alphas_ = alphas_ + + if self.noise_variance is None: + self.noise_variance_ = self._estimate_noise_variance( + X, y, positive=self.positive + ) + else: + self.noise_variance_ = self.noise_variance + + self.criterion_ = ( + n_samples * np.log(2 * np.pi * self.noise_variance_) + + residuals_sum_squares / self.noise_variance_ + + criterion_factor * degrees_of_freedom + ) + n_best = np.argmin(self.criterion_) + + self.alpha_ = alphas_[n_best] + self.coef_ = coef_path_[:, n_best] + self._set_intercept(Xmean, ymean, Xstd) + return self + + def _estimate_noise_variance(self, X, y, positive): + """Compute an estimate of the variance with an OLS model. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Data to be fitted by the OLS model. We expect the data to be + centered. + + y : ndarray of shape (n_samples,) + Associated target. + + positive : bool, default=False + Restrict coefficients to be >= 0. This should be inline with + the `positive` parameter from `LassoLarsIC`. + + Returns + ------- + noise_variance : float + An estimator of the noise variance of an OLS model. + """ + if X.shape[0] <= X.shape[1] + self.fit_intercept: + raise ValueError( + f"You are using {self.__class__.__name__} in the case where the number " + "of samples is smaller than the number of features. In this setting, " + "getting a good estimate for the variance of the noise is not " + "possible. Provide an estimate of the noise variance in the " + "constructor." + ) + # X and y are already centered and we don't need to fit with an intercept + ols_model = LinearRegression(positive=positive, fit_intercept=False) + y_pred = ols_model.fit(X, y).predict(X) + return np.sum((y - y_pred) ** 2) / ( + X.shape[0] - X.shape[1] - self.fit_intercept + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_linear_loss.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_linear_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..9213008a19841f1707b57e3e47b7887ea29da4da --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_linear_loss.py @@ -0,0 +1,825 @@ +""" +Loss functions for linear models with raw_prediction = X @ coef +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +from scipy import sparse + +from ..utils.extmath import squared_norm + + +def sandwich_dot(X, W): + """Compute the sandwich product X.T @ diag(W) @ X.""" + # TODO: This "sandwich product" is the main computational bottleneck for solvers + # that use the full hessian matrix. Here, thread parallelism would pay-off the + # most. + # While a dedicated Cython routine could exploit the symmetry, it is very hard to + # beat BLAS GEMM, even thought the latter cannot exploit the symmetry, unless one + # pays the price of taking square roots and implements + # sqrtWX = sqrt(W)[: None] * X + # return sqrtWX.T @ sqrtWX + # which (might) detect the symmetry and use BLAS SYRK under the hood. + n_samples = X.shape[0] + if sparse.issparse(X): + return ( + X.T @ sparse.dia_matrix((W, 0), shape=(n_samples, n_samples)) @ X + ).toarray() + else: + # np.einsum may use less memory but the following, using BLAS matrix + # multiplication (gemm), is by far faster. + WX = W[:, None] * X + return X.T @ WX + + +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 average of per sample losses and includes a term for L2 + regularization:: + + loss = 1 / s_sum * 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 and s_sum=sum_i s_i. + + Gradient and hessian, for simplicity without intercept, are:: + + gradient = 1 / s_sum * X.T @ loss.gradient + l2_reg_strength * coef + hessian = 1 / s_sum * 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] + + Shape of gradient follows shape of coef. + gradient.shape = coef.shape + + But hessian (to make our lives simpler) are always 2-d: + if base_loss.is_multiclass: + hessian.shape = (n_classes * n_dof, n_classes * n_dof) + else: + hessian.shape = (n_dof, n_dof) + + 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 init_zero_coef(self, X, dtype=None): + """Allocate coef of correct shape with zeros. + + Parameters: + ----------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + dtype : data-type, default=None + Overrides the data type of coef. With dtype=None, coef will have the same + dtype as X. + + Returns + ------- + coef : ndarray of shape (n_dof,) or (n_classes, n_dof) + Coefficients of a linear model. + """ + n_features = X.shape[1] + n_classes = self.base_loss.n_classes + if self.fit_intercept: + n_dof = n_features + 1 + else: + n_dof = n_features + if self.base_loss.is_multiclass: + coef = np.zeros_like(X, shape=(n_classes, n_dof), dtype=dtype, order="F") + else: + coef = np.zeros_like(X, shape=n_dof, dtype=dtype) + return coef + + def weight_intercept(self, coef): + """Helper function to get coefficients and intercept. + + 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"). + + 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. + """ + if not self.base_loss.is_multiclass: + if self.fit_intercept: + intercept = coef[-1] + weights = coef[:-1] + else: + intercept = 0.0 + weights = coef + 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 + + return weights, intercept + + def weight_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) + """ + weights, intercept = self.weight_intercept(coef) + + if not self.base_loss.is_multiclass: + raw_prediction = X @ weights + intercept + else: + # weights has shape (n_classes, n_dof) + raw_prediction = X @ weights.T + intercept # ndarray, likely C-contiguous + + return weights, intercept, raw_prediction + + def l2_penalty(self, weights, l2_reg_strength): + """Compute L2 penalty term l2_reg_strength/2 *||w||_2^2.""" + norm2_w = weights @ weights if weights.ndim == 1 else squared_norm(weights) + return 0.5 * l2_reg_strength * norm2_w + + def loss( + self, + coef, + X, + y, + sample_weight=None, + l2_reg_strength=0.0, + n_threads=1, + raw_prediction=None, + ): + """Compute the loss as weighted average 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. + raw_prediction : C-contiguous array of shape (n_samples,) or array of \ + shape (n_samples, n_classes) + Raw prediction values (in link space). If provided, these are used. If + None, then raw_prediction = X @ coef + intercept is calculated. + + Returns + ------- + loss : float + Weighted average of losses per sample, plus penalty. + """ + if raw_prediction is None: + weights, intercept, raw_prediction = self.weight_intercept_raw(coef, X) + else: + weights, intercept = self.weight_intercept(coef) + + loss = self.base_loss.loss( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=None, + n_threads=n_threads, + ) + loss = np.average(loss, weights=sample_weight) + + return loss + self.l2_penalty(weights, l2_reg_strength) + + def loss_gradient( + self, + coef, + X, + y, + sample_weight=None, + l2_reg_strength=0.0, + n_threads=1, + raw_prediction=None, + ): + """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. + raw_prediction : C-contiguous array of shape (n_samples,) or array of \ + shape (n_samples, n_classes) + Raw prediction values (in link space). If provided, these are used. If + None, then raw_prediction = X @ coef + intercept is calculated. + + Returns + ------- + loss : float + Weighted average of losses per sample, plus penalty. + + gradient : ndarray of shape coef.shape + The gradient of the loss. + """ + (n_samples, n_features), n_classes = X.shape, self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + + if raw_prediction is None: + weights, intercept, raw_prediction = self.weight_intercept_raw(coef, X) + else: + weights, intercept = self.weight_intercept(coef) + + loss, grad_pointwise = self.base_loss.loss_gradient( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) + loss = loss.sum() / sw_sum + loss += self.l2_penalty(weights, l2_reg_strength) + + grad_pointwise /= sw_sum + + if not self.base_loss.is_multiclass: + grad = np.empty_like(coef, dtype=weights.dtype) + grad[:n_features] = X.T @ grad_pointwise + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_pointwise.sum() + else: + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") + # grad_pointwise.shape = (n_samples, n_classes) + grad[:, :n_features] = grad_pointwise.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_pointwise.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, + raw_prediction=None, + ): + """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. + raw_prediction : C-contiguous array of shape (n_samples,) or array of \ + shape (n_samples, n_classes) + Raw prediction values (in link space). If provided, these are used. If + None, then raw_prediction = X @ coef + intercept is calculated. + + Returns + ------- + gradient : ndarray of shape coef.shape + The gradient of the loss. + """ + (n_samples, n_features), n_classes = X.shape, self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + + if raw_prediction is None: + weights, intercept, raw_prediction = self.weight_intercept_raw(coef, X) + else: + weights, intercept = self.weight_intercept(coef) + + grad_pointwise = self.base_loss.gradient( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) + grad_pointwise /= sw_sum + + if not self.base_loss.is_multiclass: + grad = np.empty_like(coef, dtype=weights.dtype) + grad[:n_features] = X.T @ grad_pointwise + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_pointwise.sum() + return grad + else: + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") + # gradient.shape = (n_samples, n_classes) + grad[:, :n_features] = grad_pointwise.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_pointwise.sum(axis=0) + if coef.ndim == 1: + return grad.ravel(order="F") + else: + return grad + + def gradient_hessian( + self, + coef, + X, + y, + sample_weight=None, + l2_reg_strength=0.0, + n_threads=1, + gradient_out=None, + hessian_out=None, + raw_prediction=None, + ): + """Computes gradient and hessian 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. + gradient_out : None or ndarray of shape coef.shape + A location into which the gradient is stored. If None, a new array + might be created. + hessian_out : None or ndarray of shape (n_dof, n_dof) or \ + (n_classes * n_dof, n_classes * n_dof) + A location into which the hessian is stored. If None, a new array + might be created. + raw_prediction : C-contiguous array of shape (n_samples,) or array of \ + shape (n_samples, n_classes) + Raw prediction values (in link space). If provided, these are used. If + None, then raw_prediction = X @ coef + intercept is calculated. + + Returns + ------- + gradient : ndarray of shape coef.shape + The gradient of the loss. + + hessian : ndarray of shape (n_dof, n_dof) or \ + (n_classes, n_dof, n_dof, n_classes) + Hessian matrix. + + hessian_warning : bool + True if pointwise hessian has more than 25% of its elements non-positive. + """ + (n_samples, n_features), n_classes = X.shape, self.base_loss.n_classes + n_dof = n_features + int(self.fit_intercept) + if raw_prediction is None: + weights, intercept, raw_prediction = self.weight_intercept_raw(coef, X) + else: + weights, intercept = self.weight_intercept(coef) + sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) + + # Allocate gradient. + if gradient_out is None: + grad = np.empty_like(coef, dtype=weights.dtype, order="F") + elif gradient_out.shape != coef.shape: + raise ValueError( + f"gradient_out is required to have shape coef.shape = {coef.shape}; " + f"got {gradient_out.shape}." + ) + elif self.base_loss.is_multiclass and not gradient_out.flags.f_contiguous: + raise ValueError("gradient_out must be F-contiguous.") + else: + grad = gradient_out + # Allocate hessian. + n = coef.size # for multinomial this equals n_dof * n_classes + if hessian_out is None: + hess = np.empty((n, n), dtype=weights.dtype) + elif hessian_out.shape != (n, n): + raise ValueError( + f"hessian_out is required to have shape ({n, n}); got " + f"{hessian_out.shape=}." + ) + elif self.base_loss.is_multiclass and ( + not hessian_out.flags.c_contiguous and not hessian_out.flags.f_contiguous + ): + raise ValueError("hessian_out must be contiguous.") + else: + hess = hessian_out + + if not self.base_loss.is_multiclass: + grad_pointwise, hess_pointwise = self.base_loss.gradient_hessian( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad_pointwise /= sw_sum + hess_pointwise /= sw_sum + + # For non-canonical link functions and far away from the optimum, the + # pointwise hessian can be negative. We take care that 75% of the hessian + # entries are positive. + hessian_warning = ( + np.average(hess_pointwise <= 0, weights=sample_weight) > 0.25 + ) + hess_pointwise = np.abs(hess_pointwise) + + grad[:n_features] = X.T @ grad_pointwise + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_pointwise.sum() + + if hessian_warning: + # Exit early without computing the hessian. + return grad, hess, hessian_warning + + hess[:n_features, :n_features] = sandwich_dot(X, hess_pointwise) + + if l2_reg_strength > 0: + # The L2 penalty enters the Hessian on the diagonal only. To add those + # terms, we use a flattened view of the array. + order = "C" if hess.flags.c_contiguous else "F" + hess.reshape(-1, order=order)[: (n_features * n_dof) : (n_dof + 1)] += ( + l2_reg_strength + ) + + if self.fit_intercept: + # With intercept included as added column to X, the hessian becomes + # hess = (X, 1)' @ diag(h) @ (X, 1) + # = (X' @ diag(h) @ X, X' @ h) + # ( h @ X, sum(h)) + # The left upper part has already been filled, it remains to compute + # the last row and the last column. + Xh = X.T @ hess_pointwise + hess[:-1, -1] = Xh + hess[-1, :-1] = Xh + hess[-1, -1] = hess_pointwise.sum() + 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 full hessian. Therefore, we + # call gradient_proba. + grad_pointwise, proba = self.base_loss.gradient_proba( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad_pointwise /= sw_sum + grad = grad.reshape((n_classes, n_dof), order="F") + grad[:, :n_features] = grad_pointwise.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_pointwise.sum(axis=0) + if coef.ndim == 1: + grad = grad.ravel(order="F") + + # The full hessian matrix, i.e. not only the diagonal part, dropping most + # indices, is given by: + # + # hess = X' @ h @ X + # + # Here, h is a priori a 4-dimensional matrix of shape + # (n_samples, n_samples, n_classes, n_classes). It is diagonal its first + # two dimensions (the ones with n_samples), i.e. it is + # effectively a 3-dimensional matrix (n_samples, n_classes, n_classes). + # + # h = diag(p) - p' p + # + # or with indices k and l for classes + # + # h_kl = p_k * delta_kl - p_k * p_l + # + # with p_k the (predicted) probability for class k. Only the dimension in + # n_samples multiplies with X. + # For 3 classes and n_samples = 1, this looks like ("@" is a bit misused + # here): + # + # hess = X' @ (h00 h10 h20) @ X + # (h10 h11 h12) + # (h20 h12 h22) + # = (X' @ diag(h00) @ X, X' @ diag(h10), X' @ diag(h20)) + # (X' @ diag(h10) @ X, X' @ diag(h11), X' @ diag(h12)) + # (X' @ diag(h20) @ X, X' @ diag(h12), X' @ diag(h22)) + # + # Now coef of shape (n_classes * n_dof) is contiguous in n_classes. + # Therefore, we want the hessian to follow this convention, too, i.e. + # hess[:n_classes, :n_classes] = (x0' @ h00 @ x0, x0' @ h10 @ x0, ..) + # (x0' @ h10 @ x0, x0' @ h11 @ x0, ..) + # (x0' @ h20 @ x0, x0' @ h12 @ x0, ..) + # is the first feature, x0, for all classes. In our implementation, we + # still want to take advantage of BLAS "X.T @ X". Therefore, we have some + # index/slicing battle to fight. + if sample_weight is not None: + sw = sample_weight / sw_sum + else: + sw = 1.0 / sw_sum + + for k in range(n_classes): + # Diagonal terms (in classes) hess_kk. + # Note that this also writes to some of the lower triangular part. + h = proba[:, k] * (1 - proba[:, k]) * sw + hess[ + k : n_classes * n_features : n_classes, + k : n_classes * n_features : n_classes, + ] = sandwich_dot(X, h) + if self.fit_intercept: + # See above in the non multiclass case. + Xh = X.T @ h + hess[ + k : n_classes * n_features : n_classes, + n_classes * n_features + k, + ] = Xh + hess[ + n_classes * n_features + k, + k : n_classes * n_features : n_classes, + ] = Xh + hess[n_classes * n_features + k, n_classes * n_features + k] = ( + h.sum() + ) + # Off diagonal terms (in classes) hess_kl. + for l in range(k + 1, n_classes): + # Upper triangle (in classes). + h = -proba[:, k] * proba[:, l] * sw + hess[ + k : n_classes * n_features : n_classes, + l : n_classes * n_features : n_classes, + ] = sandwich_dot(X, h) + if self.fit_intercept: + Xh = X.T @ h + hess[ + k : n_classes * n_features : n_classes, + n_classes * n_features + l, + ] = Xh + hess[ + n_classes * n_features + k, + l : n_classes * n_features : n_classes, + ] = Xh + hess[n_classes * n_features + k, n_classes * n_features + l] = ( + h.sum() + ) + # Fill lower triangle (in classes). + hess[l::n_classes, k::n_classes] = hess[k::n_classes, l::n_classes] + + if l2_reg_strength > 0: + # See above in the non multiclass case. + order = "C" if hess.flags.c_contiguous else "F" + hess.reshape(-1, order=order)[ + : (n_classes**2 * n_features * n_dof) : (n_classes * n_dof + 1) + ] += l2_reg_strength + + # The pointwise hessian is always non-negative for the multinomial loss. + hessian_warning = False + + return grad, hess, hessian_warning + + 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.weight_intercept_raw(coef, X) + sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) + + if not self.base_loss.is_multiclass: + grad_pointwise, hess_pointwise = self.base_loss.gradient_hessian( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad_pointwise /= sw_sum + hess_pointwise /= sw_sum + grad = np.empty_like(coef, dtype=weights.dtype) + grad[:n_features] = X.T @ grad_pointwise + l2_reg_strength * weights + if self.fit_intercept: + grad[-1] = grad_pointwise.sum() + + # Precompute as much as possible: hX, hX_sum and hessian_sum + hessian_sum = hess_pointwise.sum() + if sparse.issparse(X): + hX = ( + sparse.dia_matrix((hess_pointwise, 0), shape=(n_samples, n_samples)) + @ X + ) + else: + hX = hess_pointwise[:, 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))) + # prevent squeezing to zero-dim array if n_features == 1 + hX_sum = np.atleast_1d(hX_sum) + + # 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. + grad_pointwise, proba = self.base_loss.gradient_proba( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + n_threads=n_threads, + ) + grad_pointwise /= sw_sum + grad = np.empty((n_classes, n_dof), dtype=weights.dtype, order="F") + grad[:, :n_features] = grad_pointwise.T @ X + l2_reg_strength * weights + if self.fit_intercept: + grad[:, -1] = grad_pointwise.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 + 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=weights.dtype, order="F") + hess_prod[:, :n_features] = (tmp.T @ X) / sw_sum + l2_reg_strength * s + if self.fit_intercept: + hess_prod[:, -1] = tmp.sum(axis=0) / sw_sum + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_logistic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_logistic.py new file mode 100644 index 0000000000000000000000000000000000000000..35cfcee7ce7d16e4dcd57ada0d51db87bfa8c69f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_logistic.py @@ -0,0 +1,2327 @@ +""" +Logistic Regression +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import warnings +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs +from scipy import optimize + +from sklearn.metrics import get_scorer_names + +from .._loss.loss import HalfBinomialLoss, HalfMultinomialLoss +from ..base import _fit_context +from ..metrics import get_scorer +from ..model_selection import check_cv +from ..preprocessing import LabelBinarizer, LabelEncoder +from ..svm._base import _fit_liblinear +from ..utils import ( + Bunch, + check_array, + check_consistent_length, + check_random_state, + compute_class_weight, +) +from ..utils._param_validation import Hidden, Interval, StrOptions +from ..utils.extmath import row_norms, softmax +from ..utils.fixes import _get_additional_lbfgs_options_dict +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils.multiclass import check_classification_targets +from ..utils.optimize import _check_optimize_result, _newton_cg +from ..utils.parallel import Parallel, delayed +from ..utils.validation import ( + _check_method_params, + _check_sample_weight, + check_is_fitted, + validate_data, +) +from ._base import BaseEstimator, LinearClassifierMixin, SparseCoefMixin +from ._glm.glm import NewtonCholeskySolver +from ._linear_loss import LinearModelLoss +from ._sag import sag_solver + +_LOGISTIC_SOLVER_CONVERGENCE_MSG = ( + "Please also refer to the documentation for alternative solver options:\n" + " https://scikit-learn.org/stable/modules/linear_model.html" + "#logistic-regression" +) + + +def _check_solver(solver, penalty, dual): + if solver not in ["liblinear", "saga"] and penalty not in ("l2", None): + raise ValueError( + f"Solver {solver} supports only 'l2' or None penalties, got {penalty} " + "penalty." + ) + if solver != "liblinear" and dual: + raise ValueError(f"Solver {solver} supports only dual=False, got dual={dual}") + + if penalty == "elasticnet" and solver != "saga": + raise ValueError( + f"Only 'saga' solver supports elasticnet penalty, got solver={solver}." + ) + + if solver == "liblinear" and penalty is None: + raise ValueError("penalty=None is not supported for the liblinear solver") + + return solver + + +def _check_multi_class(multi_class, solver, n_classes): + """Computes the multi class type, either "multinomial" or "ovr". + + For `n_classes` > 2 and a solver that supports it, returns "multinomial". + For all other cases, in particular binary classification, return "ovr". + """ + if multi_class == "auto": + if solver in ("liblinear",): + multi_class = "ovr" + elif n_classes > 2: + multi_class = "multinomial" + else: + multi_class = "ovr" + if multi_class == "multinomial" and solver in ("liblinear",): + raise ValueError("Solver %s does not support a multinomial backend." % solver) + return multi_class + + +def _logistic_regression_path( + X, + y, + pos_class=None, + Cs=10, + fit_intercept=True, + max_iter=100, + tol=1e-4, + verbose=0, + solver="lbfgs", + coef=None, + class_weight=None, + dual=False, + penalty="l2", + intercept_scaling=1.0, + multi_class="auto", + random_state=None, + check_input=True, + max_squared_sum=None, + sample_weight=None, + l1_ratio=None, + n_threads=1, +): + """Compute a Logistic Regression model for a list of regularization + parameters. + + This is an implementation that uses the result of the previous model + to speed up computations along the set of solutions, making it faster + than sequentially calling LogisticRegression for the different parameters. + Note that there will be no speedup with liblinear solver, since it does + not handle warm-starting. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Input data, target values. + + pos_class : int, default=None + The class with respect to which we perform a one-vs-all fit. + If None, then it is assumed that the given problem is binary. + + Cs : int or array-like of shape (n_cs,), default=10 + List of values for the regularization parameter or integer specifying + the number of regularization parameters that should be used. In this + case, the parameters will be chosen in a logarithmic scale between + 1e-4 and 1e4. + + fit_intercept : bool, default=True + Whether to fit an intercept for the model. In this case the shape of + the returned array is (n_cs, n_features + 1). + + max_iter : int, default=100 + Maximum number of iterations for the solver. + + tol : float, default=1e-4 + Stopping criterion. For the newton-cg and lbfgs solvers, the iteration + will stop when ``max{|g_i | i = 1, ..., n} <= tol`` + where ``g_i`` is the i-th component of the gradient. + + verbose : int, default=0 + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'}, \ + default='lbfgs' + Numerical solver to use. + + coef : array-like of shape (n_features,), default=None + Initialization value for coefficients of logistic regression. + Useless for liblinear solver. + + class_weight : dict or 'balanced', default=None + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + dual : bool, default=False + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + penalty : {'l1', 'l2', 'elasticnet'}, default='l2' + Used to specify the norm used in the penalization. The 'newton-cg', + 'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is + only supported by the 'saga' solver. + + intercept_scaling : float, default=1. + Useful only when the solver `liblinear` is used + and `self.fit_intercept` is set to `True`. In this case, `x` becomes + `[x, self.intercept_scaling]`, + i.e. a "synthetic" feature with constant value equal to + `intercept_scaling` is appended to the instance vector. + The intercept becomes + ``intercept_scaling * synthetic_feature_weight``. + + .. note:: + The synthetic feature weight is subject to L1 or L2 + regularization as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) `intercept_scaling` has to be increased. + + multi_class : {'ovr', 'multinomial', 'auto'}, default='auto' + If the option chosen is 'ovr', then a binary problem is fit for each + label. For 'multinomial' the loss minimised is the multinomial loss fit + across the entire probability distribution, *even when the data is + binary*. 'multinomial' is unavailable when solver='liblinear'. + 'auto' selects 'ovr' if the data is binary, or if solver='liblinear', + and otherwise selects 'multinomial'. + + .. versionadded:: 0.18 + Stochastic Average Gradient descent solver for 'multinomial' case. + .. versionchanged:: 0.22 + Default changed from 'ovr' to 'auto' in 0.22. + + random_state : int, RandomState instance, default=None + Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the + data. See :term:`Glossary ` for details. + + check_input : bool, default=True + If False, the input arrays X and y will not be checked. + + max_squared_sum : float, default=None + Maximum squared sum of X over samples. Used only in SAG solver. + If None, it will be computed, going through all the samples. + The value should be precomputed to speed up cross validation. + + 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. + + l1_ratio : float, default=None + The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only + used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent + to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent + 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) + List of coefficients for the Logistic Regression model. If + fit_intercept is set to True then the second dimension will be + n_features + 1, where the last item represents the intercept. For + ``multiclass='multinomial'``, the shape is (n_classes, n_cs, + n_features) or (n_classes, n_cs, n_features + 1). + + Cs : ndarray + Grid of Cs used for cross-validation. + + n_iter : array of shape (n_cs,) + Actual number of iteration for each Cs. + + Notes + ----- + You might get slightly different results with the solver liblinear than + with the others since this uses LIBLINEAR which penalizes the intercept. + + .. versionchanged:: 0.19 + The "copy" parameter was removed. + """ + if isinstance(Cs, numbers.Integral): + Cs = np.logspace(-4, 4, Cs) + + solver = _check_solver(solver, penalty, dual) + + # Preprocessing. + if check_input: + X = check_array( + X, + accept_sparse="csr", + dtype=np.float64, + accept_large_sparse=solver not in ["liblinear", "sag", "saga"], + ) + y = check_array(y, ensure_2d=False, dtype=None) + check_consistent_length(X, y) + n_samples, n_features = X.shape + + classes = np.unique(y) + random_state = check_random_state(random_state) + + multi_class = _check_multi_class(multi_class, solver, len(classes)) + if pos_class is None and multi_class != "multinomial": + if classes.size > 2: + raise ValueError("To fit OvR, use the pos_class argument") + # np.unique(y) gives labels in sorted order. + pos_class = classes[1] + + if sample_weight is not None or class_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype, copy=True) + + # If class_weights is a dict (provided by the user), the weights + # are assigned to the original labels. If it is "balanced", then + # the class_weights are assigned after masking the labels with a OvR. + le = LabelEncoder() + if isinstance(class_weight, dict) or ( + multi_class == "multinomial" and class_weight is not None + ): + class_weight_ = compute_class_weight( + class_weight, classes=classes, y=y, sample_weight=sample_weight + ) + sample_weight *= class_weight_[le.fit_transform(y)] + + # For doing a ovr, we need to mask the labels first. For the + # multinomial case this is not necessary. + if multi_class == "ovr": + w0 = np.zeros(n_features + int(fit_intercept), dtype=X.dtype) + mask = y == pos_class + y_bin = np.ones(y.shape, dtype=X.dtype) + if solver == "liblinear": + mask_classes = np.array([-1, 1]) + y_bin[~mask] = -1.0 + else: + # 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 + + # for compute_class_weight + if class_weight == "balanced": + class_weight_ = compute_class_weight( + class_weight, + classes=mask_classes, + y=y_bin, + sample_weight=sample_weight, + ) + sample_weight *= class_weight_[le.fit_transform(y_bin)] + + else: + if solver in ["sag", "saga", "lbfgs", "newton-cg", "newton-cholesky"]: + # SAG, lbfgs, newton-cg and newton-cholesky 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]) + + w0 = np.zeros( + (classes.size, n_features + int(fit_intercept)), order="F", dtype=X.dtype + ) + + # IMPORTANT NOTE: + # All solvers relying on LinearModelLoss need to scale the penalty with n_samples + # or the sum of sample weights because the implemented logistic regression + # objective here is (unfortunately) + # C * sum(pointwise_loss) + penalty + # instead of (as LinearModelLoss does) + # mean(pointwise_loss) + 1/C * penalty + if solver in ["lbfgs", "newton-cg", "newton-cholesky"]: + # This needs to be calculated after sample_weight is multiplied by + # class_weight. It is even tested that passing class_weight is equivalent to + # passing sample_weights according to class_weight. + sw_sum = n_samples if sample_weight is None else np.sum(sample_weight) + + if coef is not None: + # it must work both giving the bias term and not + if multi_class == "ovr": + if coef.size not in (n_features, w0.size): + raise ValueError( + "Initialization coef is of shape %d, expected shape %d or %d" + % (coef.size, n_features, w0.size) + ) + w0[: coef.size] = coef + else: + # For binary problems coef.shape[0] should be 1, otherwise it + # should be classes.size. + n_classes = classes.size + if n_classes == 2: + n_classes = 1 + + if coef.shape[0] != n_classes or coef.shape[1] not in ( + n_features, + n_features + 1, + ): + raise ValueError( + "Initialization coef is of shape (%d, %d), expected " + "shape (%d, %d) or (%d, %d)" + % ( + coef.shape[0], + coef.shape[1], + classes.size, + n_features, + classes.size, + n_features + 1, + ) + ) + + if n_classes == 1: + w0[0, : coef.shape[1]] = -coef + w0[1, : coef.shape[1]] = coef + else: + w0[:, : coef.shape[1]] = coef + + if multi_class == "multinomial": + if solver in ["lbfgs", "newton-cg", "newton-cholesky"]: + # 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": + func = loss.loss_gradient + elif solver == "newton-cg": + 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": + loss = LinearModelLoss( + base_loss=HalfBinomialLoss(), fit_intercept=fit_intercept + ) + func = loss.loss_gradient + elif solver == "newton-cg": + loss = LinearModelLoss( + base_loss=HalfBinomialLoss(), fit_intercept=fit_intercept + ) + func = loss.loss + grad = loss.gradient + hess = loss.gradient_hessian_product # hess = [gradient, hessp] + elif solver == "newton-cholesky": + loss = LinearModelLoss( + base_loss=HalfBinomialLoss(), fit_intercept=fit_intercept + ) + 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 * sw_sum) + iprint = [-1, 50, 1, 100, 101][ + np.searchsorted(np.array([0, 1, 2, 3]), verbose) + ] + opt_res = optimize.minimize( + func, + w0, + method="L-BFGS-B", + jac=True, + args=(X, target, sample_weight, l2_reg_strength, n_threads), + options={ + "maxiter": max_iter, + "maxls": 50, # default is 20 + "gtol": tol, + "ftol": 64 * np.finfo(float).eps, + **_get_additional_lbfgs_options_dict("iprint", iprint), + }, + ) + n_iter_i = _check_optimize_result( + solver, + opt_res, + max_iter, + extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG, + ) + w0, loss = opt_res.x, opt_res.fun + elif solver == "newton-cg": + l2_reg_strength = 1.0 / (C * sw_sum) + args = (X, target, sample_weight, l2_reg_strength, n_threads) + w0, n_iter_i = _newton_cg( + grad_hess=hess, + func=func, + grad=grad, + x0=w0, + args=args, + maxiter=max_iter, + tol=tol, + verbose=verbose, + ) + elif solver == "newton-cholesky": + l2_reg_strength = 1.0 / (C * sw_sum) + sol = NewtonCholeskySolver( + coef=w0, + linear_loss=loss, + l2_reg_strength=l2_reg_strength, + tol=tol, + max_iter=max_iter, + n_threads=n_threads, + verbose=verbose, + ) + w0 = sol.solve(X=X, y=target, sample_weight=sample_weight) + n_iter_i = sol.iteration + elif solver == "liblinear": + if len(classes) > 2: + warnings.warn( + "Using the 'liblinear' solver for multiclass classification is " + "deprecated. An error will be raised in 1.8. Either use another " + "solver which supports the multinomial loss or wrap the estimator " + "in a OneVsRestClassifier to keep applying a one-versus-rest " + "scheme.", + FutureWarning, + ) + ( + coef_, + intercept_, + n_iter_i, + ) = _fit_liblinear( + X, + target, + C, + fit_intercept, + intercept_scaling, + None, + penalty, + dual, + verbose, + max_iter, + tol, + random_state, + sample_weight=sample_weight, + ) + if fit_intercept: + w0 = np.concatenate([coef_.ravel(), intercept_]) + else: + w0 = coef_.ravel() + # n_iter_i is an array for each class. However, `target` is always encoded + # in {-1, 1}, so we only take the first element of n_iter_i. + n_iter_i = n_iter_i.item() + + elif solver in ["sag", "saga"]: + if multi_class == "multinomial": + target = target.astype(X.dtype, copy=False) + loss = "multinomial" + else: + loss = "log" + # alpha is for L2-norm, beta is for L1-norm + if penalty == "l1": + alpha = 0.0 + beta = 1.0 / C + elif penalty == "l2": + alpha = 1.0 / C + beta = 0.0 + else: # Elastic-Net penalty + alpha = (1.0 / C) * (1 - l1_ratio) + beta = (1.0 / C) * l1_ratio + + w0, n_iter_i, warm_start_sag = sag_solver( + X, + target, + sample_weight, + loss, + alpha, + beta, + max_iter, + tol, + verbose, + random_state, + False, + max_squared_sum, + warm_start_sag, + is_saga=(solver == "saga"), + ) + + else: + raise ValueError( + "solver must be one of {'liblinear', 'lbfgs', " + "'newton-cg', 'sag'}, got '%s' instead" % solver + ) + + if multi_class == "multinomial": + n_classes = max(2, classes.size) + if solver in ["lbfgs", "newton-cg", "newton-cholesky"]: + 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()) + else: + coefs.append(w0.copy()) + + n_iter[i] = n_iter_i + + return np.array(coefs), np.array(Cs), n_iter + + +# helper function for LogisticCV +def _log_reg_scoring_path( + X, + y, + train, + test, + *, + pos_class, + Cs, + scoring, + fit_intercept, + max_iter, + tol, + class_weight, + verbose, + solver, + penalty, + dual, + intercept_scaling, + multi_class, + random_state, + max_squared_sum, + sample_weight, + l1_ratio, + score_params, +): + """Computes scores across logistic_regression_path + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target labels. + + train : list of indices + The indices of the train set. + + test : list of indices + The indices of the test set. + + pos_class : int + The class with respect to which we perform a one-vs-all fit. + If None, then it is assumed that the given problem is binary. + + Cs : int or list of floats + Each of the values in Cs describes the inverse of + regularization strength. If Cs is as an int, then a grid of Cs + values are chosen in a logarithmic scale between 1e-4 and 1e4. + + scoring : str, callable or None + The scoring method to use for cross-validation. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: :ref:`accuracy ` is used. + + fit_intercept : bool + If False, then the bias term is set to zero. Else the last + term of each coef_ gives us the intercept. + + max_iter : int + Maximum number of iterations for the solver. + + tol : float + Tolerance for stopping criteria. + + class_weight : dict or 'balanced' + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))`` + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + verbose : int + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'} + Decides which solver to use. + + penalty : {'l1', 'l2', 'elasticnet'} + Used to specify the norm used in the penalization. The 'newton-cg', + 'sag' and 'lbfgs' solvers support only l2 penalties. 'elasticnet' is + only supported by the 'saga' solver. + + dual : bool + Dual or primal formulation. Dual formulation is only implemented for + l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + intercept_scaling : float + Useful only when the solver `liblinear` is used + and `self.fit_intercept` is set to `True`. In this case, `x` becomes + `[x, self.intercept_scaling]`, + i.e. a "synthetic" feature with constant value equal to + `intercept_scaling` is appended to the instance vector. + The intercept becomes + ``intercept_scaling * synthetic_feature_weight``. + + .. note:: + The synthetic feature weight is subject to L1 or L2 + regularization as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) `intercept_scaling` has to be increased. + + multi_class : {'auto', 'ovr', 'multinomial'} + If the option chosen is 'ovr', then a binary problem is fit for each + label. For 'multinomial' the loss minimised is the multinomial loss fit + across the entire probability distribution, *even when the data is + binary*. 'multinomial' is unavailable when solver='liblinear'. + + random_state : int, RandomState instance + Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the + data. See :term:`Glossary ` for details. + + max_squared_sum : float + Maximum squared sum of X over samples. Used only in SAG solver. + If None, it will be computed, going through all the samples. + The value should be precomputed to speed up cross validation. + + sample_weight : array-like of shape(n_samples,) + Array of weights that are assigned to individual samples. + If not provided, then each sample is given unit weight. + + l1_ratio : float + The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only + used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent + to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent + to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a + combination of L1 and L2. + + score_params : dict + Parameters to pass to the `score` method of the underlying scorer. + + Returns + ------- + coefs : ndarray of shape (n_cs, n_features) or (n_cs, n_features + 1) + List of coefficients for the Logistic Regression model. If + fit_intercept is set to True then the second dimension will be + n_features + 1, where the last item represents the intercept. + + Cs : ndarray + Grid of Cs used for cross-validation. + + scores : ndarray of shape (n_cs,) + Scores obtained for each Cs. + + n_iter : ndarray of shape(n_cs,) + Actual number of iteration for each Cs. + """ + X_train = X[train] + X_test = X[test] + y_train = y[train] + y_test = y[test] + + sw_train, sw_test = None, None + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + sw_train = sample_weight[train] + sw_test = sample_weight[test] + + coefs, Cs, n_iter = _logistic_regression_path( + X_train, + y_train, + Cs=Cs, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + solver=solver, + max_iter=max_iter, + class_weight=class_weight, + pos_class=pos_class, + multi_class=multi_class, + tol=tol, + verbose=verbose, + dual=dual, + penalty=penalty, + intercept_scaling=intercept_scaling, + random_state=random_state, + check_input=False, + max_squared_sum=max_squared_sum, + sample_weight=sw_train, + ) + + log_reg = LogisticRegression(solver=solver, multi_class=multi_class) + + # The score method of Logistic Regression has a classes_ attribute. + if multi_class == "ovr": + log_reg.classes_ = np.array([-1, 1]) + elif multi_class == "multinomial": + log_reg.classes_ = np.unique(y_train) + else: + raise ValueError( + "multi_class should be either multinomial or ovr, got %d" % multi_class + ) + + if pos_class is not None: + mask = y_test == pos_class + y_test = np.ones(y_test.shape, dtype=np.float64) + y_test[~mask] = -1.0 + + scores = list() + + scoring = get_scorer(scoring) + for w in coefs: + if multi_class == "ovr": + w = w[np.newaxis, :] + if fit_intercept: + log_reg.coef_ = w[:, :-1] + log_reg.intercept_ = w[:, -1] + else: + log_reg.coef_ = w + log_reg.intercept_ = 0.0 + + if scoring is None: + scores.append(log_reg.score(X_test, y_test, sample_weight=sw_test)) + else: + score_params = score_params or {} + score_params = _check_method_params(X=X, params=score_params, indices=test) + scores.append(scoring(log_reg, X_test, y_test, **score_params)) + return coefs, Cs, np.array(scores), n_iter + + +class LogisticRegression(LinearClassifierMixin, SparseCoefMixin, BaseEstimator): + """ + Logistic Regression (aka logit, MaxEnt) classifier. + + This class implements regularized logistic regression using the + 'liblinear' library, 'newton-cg', 'sag', 'saga' and 'lbfgs' solvers. **Note + that regularization is applied by default**. It can handle both dense + and sparse input. Use C-ordered arrays or CSR matrices containing 64-bit + floats for optimal performance; any other input format will be converted + (and copied). + + The 'newton-cg', 'sag', and 'lbfgs' solvers support only L2 regularization + with primal formulation, or no regularization. The 'liblinear' solver + supports both L1 and L2 regularization, with a dual formulation only for + the L2 penalty. The Elastic-Net regularization is only supported by the + 'saga' solver. + + For :term:`multiclass` problems, all solvers but 'liblinear' optimize the + (penalized) multinomial loss. 'liblinear' only handle binary classification but can + be extended to handle multiclass by using + :class:`~sklearn.multiclass.OneVsRestClassifier`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + penalty : {'l1', 'l2', 'elasticnet', None}, default='l2' + Specify the norm of the penalty: + + - `None`: no penalty is added; + - `'l2'`: add a L2 penalty term and it is the default choice; + - `'l1'`: add a L1 penalty term; + - `'elasticnet'`: both L1 and L2 penalty terms are added. + + .. warning:: + Some penalties may not work with some solvers. See the parameter + `solver` below, to know the compatibility between the penalty and + solver. + + .. versionadded:: 0.19 + l1 penalty with SAGA solver (allowing 'multinomial' + L1) + + dual : bool, default=False + Dual (constrained) or primal (regularized, see also + :ref:`this equation `) formulation. Dual formulation + is only implemented for l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + tol : float, default=1e-4 + Tolerance for stopping criteria. + + C : float, default=1.0 + Inverse of regularization strength; must be a positive float. + Like in support vector machines, smaller values specify stronger + regularization. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the decision function. + + intercept_scaling : float, default=1 + Useful only when the solver `liblinear` is used + and `self.fit_intercept` is set to `True`. In this case, `x` becomes + `[x, self.intercept_scaling]`, + i.e. a "synthetic" feature with constant value equal to + `intercept_scaling` is appended to the instance vector. + The intercept becomes + ``intercept_scaling * synthetic_feature_weight``. + + .. note:: + The synthetic feature weight is subject to L1 or L2 + regularization as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) `intercept_scaling` has to be increased. + + class_weight : dict or 'balanced', default=None + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + .. versionadded:: 0.17 + *class_weight='balanced'* + + random_state : int, RandomState instance, default=None + Used when ``solver`` == 'sag', 'saga' or 'liblinear' to shuffle the + data. See :term:`Glossary ` for details. + + solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'}, \ + default='lbfgs' + + Algorithm to use in the optimization problem. Default is 'lbfgs'. + To choose a solver, you might want to consider the following aspects: + + - For small datasets, 'liblinear' is a good choice, whereas 'sag' + and 'saga' are faster for large ones; + - For :term:`multiclass` problems, all solvers except 'liblinear' minimize the + full multinomial loss; + - 'liblinear' can only handle binary classification by default. To apply a + one-versus-rest scheme for the multiclass setting one can wrap it with the + :class:`~sklearn.multiclass.OneVsRestClassifier`. + - 'newton-cholesky' is a good choice for + `n_samples` >> `n_features * n_classes`, especially with one-hot encoded + categorical features with rare categories. Be aware that the memory usage + of this solver has a quadratic dependency on `n_features * n_classes` + because it explicitly computes the full Hessian matrix. + + .. warning:: + The choice of the algorithm depends on the penalty chosen and on + (multinomial) multiclass support: + + ================= ============================== ====================== + solver penalty multinomial multiclass + ================= ============================== ====================== + 'lbfgs' 'l2', None yes + 'liblinear' 'l1', 'l2' no + 'newton-cg' 'l2', None yes + 'newton-cholesky' 'l2', None yes + 'sag' 'l2', None yes + 'saga' 'elasticnet', 'l1', 'l2', None yes + ================= ============================== ====================== + + .. note:: + 'sag' and 'saga' fast convergence is only guaranteed on features + with approximately the same scale. You can preprocess the data with + a scaler from :mod:`sklearn.preprocessing`. + + .. seealso:: + Refer to the :ref:`User Guide ` for more + information regarding :class:`LogisticRegression` and more specifically the + :ref:`Table ` + summarizing solver/penalty supports. + + .. versionadded:: 0.17 + Stochastic Average Gradient (SAG) descent solver. Multinomial support in + version 0.18. + .. versionadded:: 0.19 + SAGA solver. + .. versionchanged:: 0.22 + The default solver changed from 'liblinear' to 'lbfgs' in 0.22. + .. versionadded:: 1.2 + newton-cholesky solver. Multinomial support in version 1.6. + + max_iter : int, default=100 + Maximum number of iterations taken for the solvers to converge. + + multi_class : {'auto', 'ovr', 'multinomial'}, default='auto' + If the option chosen is 'ovr', then a binary problem is fit for each + label. For 'multinomial' the loss minimised is the multinomial loss fit + across the entire probability distribution, *even when the data is + binary*. 'multinomial' is unavailable when solver='liblinear'. + 'auto' selects 'ovr' if the data is binary, or if solver='liblinear', + and otherwise selects 'multinomial'. + + .. versionadded:: 0.18 + Stochastic Average Gradient descent solver for 'multinomial' case. + .. versionchanged:: 0.22 + Default changed from 'ovr' to 'auto' in 0.22. + .. deprecated:: 1.5 + ``multi_class`` was deprecated in version 1.5 and will be removed in 1.8. + From then on, the recommended 'multinomial' will always be used for + `n_classes >= 3`. + Solvers that do not support 'multinomial' will raise an error. + Use `sklearn.multiclass.OneVsRestClassifier(LogisticRegression())` if you + still want to use OvR. + + verbose : int, default=0 + For the liblinear and lbfgs solvers set verbose to any positive + number for verbosity. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous call to fit as + initialization, otherwise, just erase the previous solution. + Useless for liblinear solver. See :term:`the Glossary `. + + .. versionadded:: 0.17 + *warm_start* to support *lbfgs*, *newton-cg*, *sag*, *saga* solvers. + + n_jobs : int, default=None + Number of CPU cores used when parallelizing over classes if + multi_class='ovr'". This parameter is ignored when the ``solver`` is + set to 'liblinear' regardless of whether 'multi_class' is specified or + not. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` + context. ``-1`` means using all processors. + See :term:`Glossary ` for more details. + + l1_ratio : float, default=None + The Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. Only + used if ``penalty='elasticnet'``. Setting ``l1_ratio=0`` is equivalent + to using ``penalty='l2'``, while setting ``l1_ratio=1`` is equivalent + to using ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a + combination of L1 and L2. + + Attributes + ---------- + + classes_ : ndarray of shape (n_classes, ) + A list of class labels known to the classifier. + + coef_ : ndarray of shape (1, n_features) or (n_classes, n_features) + Coefficient of the features in the decision function. + + `coef_` is of shape (1, n_features) when the given problem is binary. + In particular, when `multi_class='multinomial'`, `coef_` corresponds + to outcome 1 (True) and `-coef_` corresponds to outcome 0 (False). + + intercept_ : ndarray of shape (1,) or (n_classes,) + Intercept (a.k.a. bias) added to the decision function. + + If `fit_intercept` is set to False, the intercept is set to zero. + `intercept_` is of shape (1,) when the given problem is binary. + In particular, when `multi_class='multinomial'`, `intercept_` + corresponds to outcome 1 (True) and `-intercept_` corresponds to + outcome 0 (False). + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : ndarray of shape (n_classes,) or (1, ) + Actual number of iterations for all classes. If binary or multinomial, + it returns only 1 element. For liblinear solver, only the maximum + number of iteration across all classes is given. + + .. versionchanged:: 0.20 + + In SciPy <= 1.0.0 the number of lbfgs iterations may exceed + ``max_iter``. ``n_iter_`` will now report at most ``max_iter``. + + See Also + -------- + SGDClassifier : Incrementally trained logistic regression (when given + the parameter ``loss="log_loss"``). + LogisticRegressionCV : Logistic regression with built-in cross validation. + + Notes + ----- + The underlying C implementation uses a random number generator to + select features when fitting the model. It is thus not uncommon, + to have slightly different results for the same input data. If + that happens, try with a smaller tol parameter. + + Predict output may not match that of standalone liblinear in certain + cases. See :ref:`differences from liblinear ` + in the narrative documentation. + + References + ---------- + + L-BFGS-B -- Software for Large-scale Bound-constrained Optimization + Ciyou Zhu, Richard Byrd, Jorge Nocedal and Jose Luis Morales. + http://users.iems.northwestern.edu/~nocedal/lbfgsb.html + + LIBLINEAR -- A Library for Large Linear Classification + https://www.csie.ntu.edu.tw/~cjlin/liblinear/ + + SAG -- Mark Schmidt, Nicolas Le Roux, and Francis Bach + Minimizing Finite Sums with the Stochastic Average Gradient + https://hal.inria.fr/hal-00860051/document + + SAGA -- Defazio, A., Bach F. & Lacoste-Julien S. (2014). + :arxiv:`"SAGA: A Fast Incremental Gradient Method With Support + for Non-Strongly Convex Composite Objectives" <1407.0202>` + + Hsiang-Fu Yu, Fang-Lan Huang, Chih-Jen Lin (2011). Dual coordinate descent + methods for logistic regression and maximum entropy models. + Machine Learning 85(1-2):41-75. + https://www.csie.ntu.edu.tw/~cjlin/papers/maxent_dual.pdf + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = load_iris(return_X_y=True) + >>> clf = LogisticRegression(random_state=0).fit(X, y) + >>> clf.predict(X[:2, :]) + array([0, 0]) + >>> clf.predict_proba(X[:2, :]) + array([[9.82e-01, 1.82e-02, 1.44e-08], + [9.72e-01, 2.82e-02, 3.02e-08]]) + >>> clf.score(X, y) + 0.97 + + For a comparison of the LogisticRegression with other classifiers see: + :ref:`sphx_glr_auto_examples_classification_plot_classification_probability.py`. + """ + + _parameter_constraints: dict = { + "penalty": [StrOptions({"l1", "l2", "elasticnet"}), None], + "dual": ["boolean"], + "tol": [Interval(Real, 0, None, closed="left")], + "C": [Interval(Real, 0, None, closed="right")], + "fit_intercept": ["boolean"], + "intercept_scaling": [Interval(Real, 0, None, closed="neither")], + "class_weight": [dict, StrOptions({"balanced"}), None], + "random_state": ["random_state"], + "solver": [ + StrOptions( + {"lbfgs", "liblinear", "newton-cg", "newton-cholesky", "sag", "saga"} + ) + ], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "verbose": ["verbose"], + "warm_start": ["boolean"], + "n_jobs": [None, Integral], + "l1_ratio": [Interval(Real, 0, 1, closed="both"), None], + "multi_class": [ + StrOptions({"auto", "ovr", "multinomial"}), + Hidden(StrOptions({"deprecated"})), + ], + } + + def __init__( + self, + penalty="l2", + *, + dual=False, + tol=1e-4, + C=1.0, + fit_intercept=True, + intercept_scaling=1, + class_weight=None, + random_state=None, + solver="lbfgs", + max_iter=100, + multi_class="deprecated", + verbose=0, + warm_start=False, + n_jobs=None, + l1_ratio=None, + ): + self.penalty = penalty + self.dual = dual + self.tol = tol + self.C = C + self.fit_intercept = fit_intercept + self.intercept_scaling = intercept_scaling + self.class_weight = class_weight + self.random_state = random_state + self.solver = solver + self.max_iter = max_iter + self.multi_class = multi_class + self.verbose = verbose + self.warm_start = warm_start + self.n_jobs = n_jobs + self.l1_ratio = l1_ratio + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """ + Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) + Target vector relative to X. + + 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. + + .. versionadded:: 0.17 + *sample_weight* support to LogisticRegression. + + Returns + ------- + self + Fitted estimator. + + Notes + ----- + The SAGA solver supports both float64 and float32 bit arrays. + """ + solver = _check_solver(self.solver, self.penalty, self.dual) + + if self.penalty != "elasticnet" and self.l1_ratio is not None: + warnings.warn( + "l1_ratio parameter is only used when penalty is " + "'elasticnet'. Got " + "(penalty={})".format(self.penalty) + ) + + if self.penalty == "elasticnet" and self.l1_ratio is None: + raise ValueError("l1_ratio must be specified when penalty is elasticnet.") + + if self.penalty is None: + if self.C != 1.0: # default values + warnings.warn( + "Setting penalty=None will ignore the C and l1_ratio parameters" + ) + # Note that check for l1_ratio is done right above + C_ = np.inf + penalty = "l2" + else: + C_ = self.C + penalty = self.penalty + + if solver == "lbfgs": + _dtype = np.float64 + else: + _dtype = [np.float64, np.float32] + + X, y = validate_data( + self, + X, + y, + accept_sparse="csr", + dtype=_dtype, + order="C", + accept_large_sparse=solver not in ["liblinear", "sag", "saga"], + ) + check_classification_targets(y) + self.classes_ = np.unique(y) + + # TODO(1.8) remove multi_class + multi_class = self.multi_class + if self.multi_class == "multinomial" and len(self.classes_) == 2: + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. From then on, binary problems will be fit as proper binary " + " logistic regression models (as if multi_class='ovr' were set)." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + elif self.multi_class in ("multinomial", "auto"): + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. From then on, it will always use 'multinomial'." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + elif self.multi_class == "ovr": + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. Use OneVsRestClassifier(LogisticRegression(..)) instead." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + else: + # Set to old default value. + multi_class = "auto" + multi_class = _check_multi_class(multi_class, solver, len(self.classes_)) + + if solver == "liblinear": + if len(self.classes_) > 2: + warnings.warn( + "Using the 'liblinear' solver for multiclass classification is " + "deprecated. An error will be raised in 1.8. Either use another " + "solver which supports the multinomial loss or wrap the estimator " + "in a OneVsRestClassifier to keep applying a one-versus-rest " + "scheme.", + FutureWarning, + ) + if effective_n_jobs(self.n_jobs) != 1: + warnings.warn( + "'n_jobs' > 1 does not have any effect when" + " 'solver' is set to 'liblinear'. Got 'n_jobs'" + " = {}.".format(effective_n_jobs(self.n_jobs)) + ) + self.coef_, self.intercept_, self.n_iter_ = _fit_liblinear( + X, + y, + self.C, + self.fit_intercept, + self.intercept_scaling, + self.class_weight, + self.penalty, + self.dual, + self.verbose, + self.max_iter, + self.tol, + self.random_state, + sample_weight=sample_weight, + ) + return self + + if solver in ["sag", "saga"]: + max_squared_sum = row_norms(X, squared=True).max() + else: + max_squared_sum = None + + n_classes = len(self.classes_) + classes_ = self.classes_ + if n_classes < 2: + raise ValueError( + "This solver needs samples of at least 2 classes" + " in the data, but the data contains only one" + " class: %r" % classes_[0] + ) + + if len(self.classes_) == 2: + n_classes = 1 + classes_ = classes_[1:] + + if self.warm_start: + warm_start_coef = getattr(self, "coef_", None) + else: + warm_start_coef = None + if warm_start_coef is not None and self.fit_intercept: + warm_start_coef = np.append( + warm_start_coef, self.intercept_[:, np.newaxis], axis=1 + ) + + # Hack so that we iterate only once for the multinomial case. + if multi_class == "multinomial": + classes_ = [None] + warm_start_coef = [warm_start_coef] + if warm_start_coef is None: + warm_start_coef = [None] * n_classes + + path_func = delayed(_logistic_regression_path) + + # The SAG solver releases the GIL so it's more efficient to use + # threads for this solver. + if solver in ["sag", "saga"]: + 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", "newton-cholesky"] + 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, + y, + pos_class=class_, + Cs=[C_], + l1_ratio=self.l1_ratio, + fit_intercept=self.fit_intercept, + tol=self.tol, + verbose=self.verbose, + solver=solver, + multi_class=multi_class, + max_iter=self.max_iter, + class_weight=self.class_weight, + check_input=False, + random_state=self.random_state, + coef=warm_start_coef_, + 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) + ) + + fold_coefs_, _, n_iter_ = zip(*fold_coefs_) + self.n_iter_ = np.asarray(n_iter_, dtype=np.int32)[:, 0] + + n_features = X.shape[1] + if multi_class == "multinomial": + self.coef_ = fold_coefs_[0][0] + else: + self.coef_ = np.asarray(fold_coefs_) + self.coef_ = self.coef_.reshape( + n_classes, n_features + int(self.fit_intercept) + ) + + if self.fit_intercept: + self.intercept_ = self.coef_[:, -1] + self.coef_ = self.coef_[:, :-1] + else: + self.intercept_ = np.zeros(n_classes) + + return self + + def predict_proba(self, X): + """ + Probability estimates. + + The returned estimates for all classes are ordered by the + label of classes. + + For a multi_class problem, if multi_class is set to be "multinomial" + the softmax function is used to find the predicted probability of + each class. + Else use a one-vs-rest approach, i.e. calculate the probability + of each class assuming it to be positive using the logistic function + and normalize these values across all the classes. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Vector to be scored, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + T : array-like of shape (n_samples, n_classes) + Returns the probability of the sample for each class in the model, + where classes are ordered as they are in ``self.classes_``. + """ + check_is_fitted(self) + + ovr = self.multi_class in ["ovr", "warn"] or ( + self.multi_class in ["auto", "deprecated"] + and (self.classes_.size <= 2 or self.solver == "liblinear") + ) + if ovr: + return super()._predict_proba_lr(X) + else: + decision = self.decision_function(X) + if decision.ndim == 1: + # Workaround for multi_class="multinomial" and binary outcomes + # which requires softmax prediction with only a 1D decision. + decision_2d = np.c_[-decision, decision] + else: + decision_2d = decision + return softmax(decision_2d, copy=False) + + def predict_log_proba(self, X): + """ + Predict logarithm of probability estimates. + + The returned estimates for all classes are ordered by the + label of classes. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Vector to be scored, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + T : array-like of shape (n_samples, n_classes) + Returns the log-probability of the sample for each class in the + model, where classes are ordered as they are in ``self.classes_``. + """ + return np.log(self.predict_proba(X)) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class LogisticRegressionCV(LogisticRegression, LinearClassifierMixin, BaseEstimator): + """Logistic Regression CV (aka logit, MaxEnt) classifier. + + See glossary entry for :term:`cross-validation estimator`. + + This class implements logistic regression using liblinear, newton-cg, sag + or lbfgs optimizer. The newton-cg, sag and lbfgs solvers support only L2 + regularization with primal formulation. The liblinear solver supports both + L1 and L2 regularization, with a dual formulation only for the L2 penalty. + Elastic-Net penalty is only supported by the saga solver. + + For the grid of `Cs` values and `l1_ratios` values, the best hyperparameter + is selected by the cross-validator + :class:`~sklearn.model_selection.StratifiedKFold`, but it can be changed + using the :term:`cv` parameter. The 'newton-cg', 'sag', 'saga' and 'lbfgs' + solvers can warm-start the coefficients (see :term:`Glossary`). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + Cs : int or list of floats, default=10 + Each of the values in Cs describes the inverse of regularization + strength. If Cs is as an int, then a grid of Cs values are chosen + in a logarithmic scale between 1e-4 and 1e4. + Like in support vector machines, smaller values specify stronger + regularization. + + fit_intercept : bool, default=True + Specifies if a constant (a.k.a. bias or intercept) should be + added to the decision function. + + cv : int or cross-validation generator, default=None + The default cross-validation generator used is Stratified K-Folds. + If an integer is provided, then it is the number of folds used. + See the module :mod:`sklearn.model_selection` module for the + list of possible cross-validation objects. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + dual : bool, default=False + Dual (constrained) or primal (regularized, see also + :ref:`this equation `) formulation. Dual formulation + is only implemented for l2 penalty with liblinear solver. Prefer dual=False when + n_samples > n_features. + + penalty : {'l1', 'l2', 'elasticnet'}, default='l2' + Specify the norm of the penalty: + + - `'l2'`: add a L2 penalty term (used by default); + - `'l1'`: add a L1 penalty term; + - `'elasticnet'`: both L1 and L2 penalty terms are added. + + .. warning:: + Some penalties may not work with some solvers. See the parameter + `solver` below, to know the compatibility between the penalty and + solver. + + scoring : str or callable, default=None + The scoring method to use for cross-validation. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: :ref:`accuracy ` is used. + + solver : {'lbfgs', 'liblinear', 'newton-cg', 'newton-cholesky', 'sag', 'saga'}, \ + default='lbfgs' + + Algorithm to use in the optimization problem. Default is 'lbfgs'. + To choose a solver, you might want to consider the following aspects: + + - For small datasets, 'liblinear' is a good choice, whereas 'sag' + and 'saga' are faster for large ones; + - For multiclass problems, all solvers except 'liblinear' minimize the full + multinomial loss; + - 'liblinear' might be slower in :class:`LogisticRegressionCV` + because it does not handle warm-starting. + - 'liblinear' can only handle binary classification by default. To apply a + one-versus-rest scheme for the multiclass setting one can wrap it with the + :class:`~sklearn.multiclass.OneVsRestClassifier`. + - 'newton-cholesky' is a good choice for + `n_samples` >> `n_features * n_classes`, especially with one-hot encoded + categorical features with rare categories. Be aware that the memory usage + of this solver has a quadratic dependency on `n_features * n_classes` + because it explicitly computes the full Hessian matrix. + + .. warning:: + The choice of the algorithm depends on the penalty chosen and on + (multinomial) multiclass support: + + ================= ============================== ====================== + solver penalty multinomial multiclass + ================= ============================== ====================== + 'lbfgs' 'l2' yes + 'liblinear' 'l1', 'l2' no + 'newton-cg' 'l2' yes + 'newton-cholesky' 'l2', yes + 'sag' 'l2', yes + 'saga' 'elasticnet', 'l1', 'l2' yes + ================= ============================== ====================== + + .. note:: + 'sag' and 'saga' fast convergence is only guaranteed on features + with approximately the same scale. You can preprocess the data with + a scaler from :mod:`sklearn.preprocessing`. + + .. versionadded:: 0.17 + Stochastic Average Gradient (SAG) descent solver. Multinomial support in + version 0.18. + .. versionadded:: 0.19 + SAGA solver. + .. versionadded:: 1.2 + newton-cholesky solver. Multinomial support in version 1.6. + + tol : float, default=1e-4 + Tolerance for stopping criteria. + + max_iter : int, default=100 + Maximum number of iterations of the optimization algorithm. + + class_weight : dict or 'balanced', default=None + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + Note that these weights will be multiplied with sample_weight (passed + through the fit method) if sample_weight is specified. + + .. versionadded:: 0.17 + class_weight == 'balanced' + + n_jobs : int, default=None + Number of CPU cores used during the cross-validation loop. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : int, default=0 + For the 'liblinear', 'sag' and 'lbfgs' solvers set verbose to any + positive number for verbosity. + + refit : bool, default=True + If set to True, the scores are averaged across all folds, and the + coefs and the C that corresponds to the best score is taken, and a + final refit is done using these parameters. + Otherwise the coefs, intercepts and C that correspond to the + best scores across folds are averaged. + + intercept_scaling : float, default=1 + Useful only when the solver `liblinear` is used + and `self.fit_intercept` is set to `True`. In this case, `x` becomes + `[x, self.intercept_scaling]`, + i.e. a "synthetic" feature with constant value equal to + `intercept_scaling` is appended to the instance vector. + The intercept becomes + ``intercept_scaling * synthetic_feature_weight``. + + .. note:: + The synthetic feature weight is subject to L1 or L2 + regularization as all other features. + To lessen the effect of regularization on synthetic feature weight + (and therefore on the intercept) `intercept_scaling` has to be increased. + + multi_class : {'auto, 'ovr', 'multinomial'}, default='auto' + If the option chosen is 'ovr', then a binary problem is fit for each + label. For 'multinomial' the loss minimised is the multinomial loss fit + across the entire probability distribution, *even when the data is + binary*. 'multinomial' is unavailable when solver='liblinear'. + 'auto' selects 'ovr' if the data is binary, or if solver='liblinear', + and otherwise selects 'multinomial'. + + .. versionadded:: 0.18 + Stochastic Average Gradient descent solver for 'multinomial' case. + .. versionchanged:: 0.22 + Default changed from 'ovr' to 'auto' in 0.22. + .. deprecated:: 1.5 + ``multi_class`` was deprecated in version 1.5 and will be removed in 1.8. + From then on, the recommended 'multinomial' will always be used for + `n_classes >= 3`. + Solvers that do not support 'multinomial' will raise an error. + Use `sklearn.multiclass.OneVsRestClassifier(LogisticRegressionCV())` if you + still want to use OvR. + + random_state : int, RandomState instance, default=None + Used when `solver='sag'`, 'saga' or 'liblinear' to shuffle the data. + Note that this only applies to the solver and not the cross-validation + generator. See :term:`Glossary ` for details. + + l1_ratios : list of float, default=None + The list of Elastic-Net mixing parameter, with ``0 <= l1_ratio <= 1``. + Only used if ``penalty='elasticnet'``. A value of 0 is equivalent to + using ``penalty='l2'``, while 1 is equivalent to using + ``penalty='l1'``. For ``0 < l1_ratio <1``, the penalty is a combination + of L1 and L2. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes, ) + A list of class labels known to the classifier. + + coef_ : ndarray of shape (1, n_features) or (n_classes, n_features) + Coefficient of the features in the decision function. + + `coef_` is of shape (1, n_features) when the given problem + is binary. + + intercept_ : ndarray of shape (1,) or (n_classes,) + Intercept (a.k.a. bias) added to the decision function. + + If `fit_intercept` is set to False, the intercept is set to zero. + `intercept_` is of shape(1,) when the problem is binary. + + Cs_ : ndarray of shape (n_cs) + Array of C i.e. inverse of regularization parameter values used + for cross-validation. + + l1_ratios_ : ndarray of shape (n_l1_ratios) + Array of l1_ratios used for cross-validation. If no l1_ratio is used + (i.e. penalty is not 'elasticnet'), this is set to ``[None]`` + + coefs_paths_ : ndarray of shape (n_folds, n_cs, n_features) or \ + (n_folds, n_cs, n_features + 1) + dict with classes as the keys, and the path of coefficients obtained + during cross-validating across each fold and then across each Cs + after doing an OvR for the corresponding class as values. + If the 'multi_class' option is set to 'multinomial', then + the coefs_paths are the coefficients corresponding to each class. + Each dict value has shape ``(n_folds, n_cs, n_features)`` or + ``(n_folds, n_cs, n_features + 1)`` depending on whether the + intercept is fit or not. If ``penalty='elasticnet'``, the shape is + ``(n_folds, n_cs, n_l1_ratios_, n_features)`` or + ``(n_folds, n_cs, n_l1_ratios_, n_features + 1)``. + + scores_ : dict + dict with classes as the keys, and the values as the + grid of scores obtained during cross-validating each fold, after doing + an OvR for the corresponding class. If the 'multi_class' option + given is 'multinomial' then the same scores are repeated across + all classes, since this is the multinomial class. Each dict value + has shape ``(n_folds, n_cs)`` or ``(n_folds, n_cs, n_l1_ratios)`` if + ``penalty='elasticnet'``. + + C_ : ndarray of shape (n_classes,) or (n_classes - 1,) + Array of C that maps to the best scores across every class. If refit is + set to False, then for each class, the best C is the average of the + C's that correspond to the best scores for each fold. + `C_` is of shape(n_classes,) when the problem is binary. + + l1_ratio_ : ndarray of shape (n_classes,) or (n_classes - 1,) + Array of l1_ratio that maps to the best scores across every class. If + refit is set to False, then for each class, the best l1_ratio is the + average of the l1_ratio's that correspond to the best scores for each + fold. `l1_ratio_` is of shape(n_classes,) when the problem is binary. + + n_iter_ : ndarray of shape (n_classes, n_folds, n_cs) or (1, n_folds, n_cs) + Actual number of iterations for all classes, folds and Cs. + In the binary or multinomial cases, the first dimension is equal to 1. + If ``penalty='elasticnet'``, the shape is ``(n_classes, n_folds, + n_cs, n_l1_ratios)`` or ``(1, n_folds, n_cs, n_l1_ratios)``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + LogisticRegression : Logistic regression without tuning the + hyperparameter `C`. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.linear_model import LogisticRegressionCV + >>> X, y = load_iris(return_X_y=True) + >>> clf = LogisticRegressionCV(cv=5, random_state=0).fit(X, y) + >>> clf.predict(X[:2, :]) + array([0, 0]) + >>> clf.predict_proba(X[:2, :]).shape + (2, 3) + >>> clf.score(X, y) + 0.98... + """ + + _parameter_constraints: dict = {**LogisticRegression._parameter_constraints} + + for param in ["C", "warm_start", "l1_ratio"]: + _parameter_constraints.pop(param) + + _parameter_constraints.update( + { + "Cs": [Interval(Integral, 1, None, closed="left"), "array-like"], + "cv": ["cv_object"], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "l1_ratios": ["array-like", None], + "refit": ["boolean"], + "penalty": [StrOptions({"l1", "l2", "elasticnet"})], + } + ) + + def __init__( + self, + *, + Cs=10, + fit_intercept=True, + cv=None, + dual=False, + penalty="l2", + scoring=None, + solver="lbfgs", + tol=1e-4, + max_iter=100, + class_weight=None, + n_jobs=None, + verbose=0, + refit=True, + intercept_scaling=1.0, + multi_class="deprecated", + random_state=None, + l1_ratios=None, + ): + self.Cs = Cs + self.fit_intercept = fit_intercept + self.cv = cv + self.dual = dual + self.penalty = penalty + self.scoring = scoring + self.tol = tol + self.max_iter = max_iter + self.class_weight = class_weight + self.n_jobs = n_jobs + self.verbose = verbose + self.solver = solver + self.refit = refit + self.intercept_scaling = intercept_scaling + self.multi_class = multi_class + self.random_state = random_state + self.l1_ratios = l1_ratios + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None, **params): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) + Target vector relative to X. + + 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. + + **params : dict + Parameters to pass to the underlying splitter and scorer. + + .. versionadded:: 1.4 + + Returns + ------- + self : object + Fitted LogisticRegressionCV estimator. + """ + _raise_for_params(params, self, "fit") + + solver = _check_solver(self.solver, self.penalty, self.dual) + + if self.penalty == "elasticnet": + if ( + self.l1_ratios is None + or len(self.l1_ratios) == 0 + or any( + ( + not isinstance(l1_ratio, numbers.Number) + or l1_ratio < 0 + or l1_ratio > 1 + ) + for l1_ratio in self.l1_ratios + ) + ): + raise ValueError( + "l1_ratios must be a list of numbers between " + "0 and 1; got (l1_ratios=%r)" % self.l1_ratios + ) + l1_ratios_ = self.l1_ratios + else: + if self.l1_ratios is not None: + warnings.warn( + "l1_ratios parameter is only used when penalty " + "is 'elasticnet'. Got (penalty={})".format(self.penalty) + ) + + l1_ratios_ = [None] + + X, y = validate_data( + self, + X, + y, + accept_sparse="csr", + dtype=np.float64, + order="C", + accept_large_sparse=solver not in ["liblinear", "sag", "saga"], + ) + check_classification_targets(y) + + class_weight = self.class_weight + + # Encode for string labels + label_encoder = LabelEncoder().fit(y) + y = label_encoder.transform(y) + if isinstance(class_weight, dict): + class_weight = { + label_encoder.transform([cls])[0]: v for cls, v in class_weight.items() + } + + # The original class labels + classes = self.classes_ = label_encoder.classes_ + encoded_labels = label_encoder.transform(label_encoder.classes_) + + # TODO(1.8) remove multi_class + multi_class = self.multi_class + if self.multi_class == "multinomial" and len(self.classes_) == 2: + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. From then on, binary problems will be fit as proper binary " + " logistic regression models (as if multi_class='ovr' were set)." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + elif self.multi_class in ("multinomial", "auto"): + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. From then on, it will always use 'multinomial'." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + elif self.multi_class == "ovr": + warnings.warn( + ( + "'multi_class' was deprecated in version 1.5 and will be removed in" + " 1.8. Use OneVsRestClassifier(LogisticRegressionCV(..)) instead." + " Leave it to its default value to avoid this warning." + ), + FutureWarning, + ) + else: + # Set to old default value. + multi_class = "auto" + multi_class = _check_multi_class(multi_class, solver, len(classes)) + + if solver in ["sag", "saga"]: + max_squared_sum = row_norms(X, squared=True).max() + else: + max_squared_sum = None + + if _routing_enabled(): + routed_params = process_routing( + self, + "fit", + sample_weight=sample_weight, + **params, + ) + else: + routed_params = Bunch() + routed_params.splitter = Bunch(split={}) + routed_params.scorer = Bunch(score=params) + if sample_weight is not None: + routed_params.scorer.score["sample_weight"] = sample_weight + + # init cross-validation generator + cv = check_cv(self.cv, y, classifier=True) + folds = list(cv.split(X, y, **routed_params.splitter.split)) + + # Use the label encoded classes + n_classes = len(encoded_labels) + + if n_classes < 2: + raise ValueError( + "This solver needs samples of at least 2 classes" + " in the data, but the data contains only one" + " class: %r" % classes[0] + ) + + if n_classes == 2: + # OvR in case of binary problems is as good as fitting + # the higher label + n_classes = 1 + encoded_labels = encoded_labels[1:] + classes = classes[1:] + + # We need this hack to iterate only once over labels, in the case of + # multi_class = multinomial, without changing the value of the labels. + if multi_class == "multinomial": + iter_encoded_labels = iter_classes = [None] + else: + iter_encoded_labels = encoded_labels + iter_classes = classes + + # compute the class weights for the entire dataset y + if class_weight == "balanced": + class_weight = compute_class_weight( + class_weight, + classes=np.arange(len(self.classes_)), + y=y, + sample_weight=sample_weight, + ) + class_weight = dict(enumerate(class_weight)) + + path_func = delayed(_log_reg_scoring_path) + + # The SAG solver releases the GIL so it's more efficient to use + # threads for this solver. + if self.solver in ["sag", "saga"]: + prefer = "threads" + else: + prefer = "processes" + + fold_coefs_ = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, prefer=prefer)( + path_func( + X, + y, + train, + test, + pos_class=label, + Cs=self.Cs, + fit_intercept=self.fit_intercept, + penalty=self.penalty, + dual=self.dual, + solver=solver, + tol=self.tol, + max_iter=self.max_iter, + verbose=self.verbose, + class_weight=class_weight, + scoring=self.scoring, + multi_class=multi_class, + intercept_scaling=self.intercept_scaling, + random_state=self.random_state, + max_squared_sum=max_squared_sum, + sample_weight=sample_weight, + l1_ratio=l1_ratio, + score_params=routed_params.scorer.score, + ) + for label in iter_encoded_labels + for train, test in folds + for l1_ratio in l1_ratios_ + ) + + # _log_reg_scoring_path will output different shapes depending on the + # multi_class param, so we need to reshape the outputs accordingly. + # Cs is of shape (n_classes . n_folds . n_l1_ratios, n_Cs) and all the + # rows are equal, so we just take the first one. + # After reshaping, + # - scores is of shape (n_classes, n_folds, n_Cs . n_l1_ratios) + # - coefs_paths is of shape + # (n_classes, n_folds, n_Cs . n_l1_ratios, n_features) + # - n_iter is of shape + # (n_classes, n_folds, n_Cs . n_l1_ratios) or + # (1, n_folds, n_Cs . n_l1_ratios) + coefs_paths, Cs, scores, n_iter_ = zip(*fold_coefs_) + self.Cs_ = Cs[0] + if multi_class == "multinomial": + coefs_paths = np.reshape( + coefs_paths, + (len(folds), len(l1_ratios_) * len(self.Cs_), n_classes, -1), + ) + # equiv to coefs_paths = np.moveaxis(coefs_paths, (0, 1, 2, 3), + # (1, 2, 0, 3)) + coefs_paths = np.swapaxes(coefs_paths, 0, 1) + coefs_paths = np.swapaxes(coefs_paths, 0, 2) + self.n_iter_ = np.reshape( + n_iter_, (1, len(folds), len(self.Cs_) * len(l1_ratios_)) + ) + # repeat same scores across all classes + scores = np.tile(scores, (n_classes, 1, 1)) + else: + coefs_paths = np.reshape( + coefs_paths, + (n_classes, len(folds), len(self.Cs_) * len(l1_ratios_), -1), + ) + self.n_iter_ = np.reshape( + n_iter_, (n_classes, len(folds), len(self.Cs_) * len(l1_ratios_)) + ) + scores = np.reshape(scores, (n_classes, len(folds), -1)) + self.scores_ = dict(zip(classes, scores)) + self.coefs_paths_ = dict(zip(classes, coefs_paths)) + + self.C_ = list() + self.l1_ratio_ = list() + self.coef_ = np.empty((n_classes, X.shape[1])) + self.intercept_ = np.zeros(n_classes) + for index, (cls, encoded_label) in enumerate( + zip(iter_classes, iter_encoded_labels) + ): + if multi_class == "ovr": + scores = self.scores_[cls] + coefs_paths = self.coefs_paths_[cls] + else: + # For multinomial, all scores are the same across classes + scores = scores[0] + # coefs_paths will keep its original shape because + # logistic_regression_path expects it this way + + if self.refit: + # best_index is between 0 and (n_Cs . n_l1_ratios - 1) + # for example, with n_cs=2 and n_l1_ratios=3 + # the layout of scores is + # [c1, c2, c1, c2, c1, c2] + # l1_1 , l1_2 , l1_3 + best_index = scores.sum(axis=0).argmax() + + best_index_C = best_index % len(self.Cs_) + C_ = self.Cs_[best_index_C] + self.C_.append(C_) + + best_index_l1 = best_index // len(self.Cs_) + l1_ratio_ = l1_ratios_[best_index_l1] + self.l1_ratio_.append(l1_ratio_) + + if multi_class == "multinomial": + coef_init = np.mean(coefs_paths[:, :, best_index, :], axis=1) + else: + coef_init = np.mean(coefs_paths[:, best_index, :], axis=0) + + # Note that y is label encoded and hence pos_class must be + # the encoded label / None (for 'multinomial') + w, _, _ = _logistic_regression_path( + X, + y, + pos_class=encoded_label, + Cs=[C_], + solver=solver, + fit_intercept=self.fit_intercept, + coef=coef_init, + max_iter=self.max_iter, + tol=self.tol, + penalty=self.penalty, + class_weight=class_weight, + multi_class=multi_class, + verbose=max(0, self.verbose - 1), + random_state=self.random_state, + check_input=False, + max_squared_sum=max_squared_sum, + sample_weight=sample_weight, + l1_ratio=l1_ratio_, + ) + w = w[0] + + else: + # Take the best scores across every fold and the average of + # all coefficients corresponding to the best scores. + best_indices = np.argmax(scores, axis=1) + if multi_class == "ovr": + w = np.mean( + [coefs_paths[i, best_indices[i], :] for i in range(len(folds))], + axis=0, + ) + else: + w = np.mean( + [ + coefs_paths[:, i, best_indices[i], :] + for i in range(len(folds)) + ], + axis=0, + ) + + best_indices_C = best_indices % len(self.Cs_) + self.C_.append(np.mean(self.Cs_[best_indices_C])) + + if self.penalty == "elasticnet": + best_indices_l1 = best_indices // len(self.Cs_) + self.l1_ratio_.append(np.mean(l1_ratios_[best_indices_l1])) + else: + self.l1_ratio_.append(None) + + if multi_class == "multinomial": + self.C_ = np.tile(self.C_, n_classes) + self.l1_ratio_ = np.tile(self.l1_ratio_, n_classes) + self.coef_ = w[:, : X.shape[1]] + if self.fit_intercept: + self.intercept_ = w[:, -1] + else: + self.coef_[index] = w[: X.shape[1]] + if self.fit_intercept: + self.intercept_[index] = w[-1] + + self.C_ = np.asarray(self.C_) + self.l1_ratio_ = np.asarray(self.l1_ratio_) + self.l1_ratios_ = np.asarray(l1_ratios_) + # if elasticnet was used, add the l1_ratios dimension to some + # attributes + if self.l1_ratios is not None: + # with n_cs=2 and n_l1_ratios=3 + # the layout of scores is + # [c1, c2, c1, c2, c1, c2] + # l1_1 , l1_2 , l1_3 + # To get a 2d array with the following layout + # l1_1, l1_2, l1_3 + # c1 [[ . , . , . ], + # c2 [ . , . , . ]] + # We need to first reshape and then transpose. + # The same goes for the other arrays + for cls, coefs_path in self.coefs_paths_.items(): + self.coefs_paths_[cls] = coefs_path.reshape( + (len(folds), self.l1_ratios_.size, self.Cs_.size, -1) + ) + self.coefs_paths_[cls] = np.transpose( + self.coefs_paths_[cls], (0, 2, 1, 3) + ) + for cls, score in self.scores_.items(): + self.scores_[cls] = score.reshape( + (len(folds), self.l1_ratios_.size, self.Cs_.size) + ) + self.scores_[cls] = np.transpose(self.scores_[cls], (0, 2, 1)) + + self.n_iter_ = self.n_iter_.reshape( + (-1, len(folds), self.l1_ratios_.size, self.Cs_.size) + ) + self.n_iter_ = np.transpose(self.n_iter_, (0, 1, 3, 2)) + + return self + + def score(self, X, y, sample_weight=None, **score_params): + """Score using the `scoring` option on the given test data and labels. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Test samples. + + y : array-like of shape (n_samples,) + True labels for X. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + **score_params : dict + Parameters to pass to the `score` method of the underlying scorer. + + .. versionadded:: 1.4 + + Returns + ------- + score : float + Score of self.predict(X) w.r.t. y. + """ + _raise_for_params(score_params, self, "score") + + scoring = self._get_scorer() + if _routing_enabled(): + routed_params = process_routing( + self, + "score", + sample_weight=sample_weight, + **score_params, + ) + else: + routed_params = Bunch() + routed_params.scorer = Bunch(score={}) + if sample_weight is not None: + routed_params.scorer.score["sample_weight"] = sample_weight + + return scoring( + self, + X, + y, + **routed_params.scorer.score, + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.4 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + + router = ( + MetadataRouter(owner=self.__class__.__name__) + .add_self_request(self) + .add( + splitter=self.cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + scorer=self._get_scorer(), + method_mapping=MethodMapping() + .add(caller="score", callee="score") + .add(caller="fit", callee="score"), + ) + ) + return router + + def _get_scorer(self): + """Get the scorer based on the scoring method specified. + The default scoring method is `accuracy`. + """ + scoring = self.scoring or "accuracy" + return get_scorer(scoring) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_omp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_omp.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4dbac2d7634b0fe4e6a02771e64f80adcf490b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_omp.py @@ -0,0 +1,1121 @@ +"""Orthogonal matching pursuit algorithms""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from math import sqrt +from numbers import Integral, Real + +import numpy as np +from scipy import linalg +from scipy.linalg.lapack import get_lapack_funcs + +from ..base import MultiOutputMixin, RegressorMixin, _fit_context +from ..model_selection import check_cv +from ..utils import Bunch, as_float_array, check_array +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils.parallel import Parallel, delayed +from ..utils.validation import validate_data +from ._base import LinearModel, _pre_fit + +premature = ( + "Orthogonal matching pursuit ended prematurely due to linear" + " dependence in the dictionary. The requested precision might" + " not have been met." +) + + +def _cholesky_omp(X, y, n_nonzero_coefs, tol=None, copy_X=True, return_path=False): + """Orthogonal Matching Pursuit step using the Cholesky decomposition. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Input dictionary. Columns are assumed to have unit norm. + + y : ndarray of shape (n_samples,) + Input targets. + + n_nonzero_coefs : int + Targeted number of non-zero elements. + + tol : float, default=None + Targeted squared error, if not None overrides n_nonzero_coefs. + + copy_X : bool, default=True + Whether the design matrix X must be copied by the algorithm. A false + value is only helpful if X is already Fortran-ordered, otherwise a + copy is made anyway. + + return_path : bool, default=False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + Returns + ------- + gamma : ndarray of shape (n_nonzero_coefs,) + Non-zero elements of the solution. + + idx : ndarray of shape (n_nonzero_coefs,) + Indices of the positions of the elements in gamma within the solution + vector. + + coef : ndarray of shape (n_features, n_nonzero_coefs) + The first k values of column k correspond to the coefficient value + for the active features at that step. The lower left triangle contains + garbage. Only returned if ``return_path=True``. + + n_active : int + Number of active features at convergence. + """ + if copy_X: + X = X.copy("F") + else: # even if we are allowed to overwrite, still copy it if bad order + X = np.asfortranarray(X) + + min_float = np.finfo(X.dtype).eps + nrm2, swap = linalg.get_blas_funcs(("nrm2", "swap"), (X,)) + (potrs,) = get_lapack_funcs(("potrs",), (X,)) + + alpha = np.dot(X.T, y) + residual = y + gamma = np.empty(0) + n_active = 0 + indices = np.arange(X.shape[1]) # keeping track of swapping + + max_features = X.shape[1] if tol is not None else n_nonzero_coefs + + L = np.empty((max_features, max_features), dtype=X.dtype) + + if return_path: + coefs = np.empty_like(L) + + while True: + lam = np.argmax(np.abs(np.dot(X.T, residual))) + if lam < n_active or alpha[lam] ** 2 < min_float: + # atom already selected or inner product too small + warnings.warn(premature, RuntimeWarning, stacklevel=2) + break + + if n_active > 0: + # Updates the Cholesky decomposition of X' X + L[n_active, :n_active] = np.dot(X[:, :n_active].T, X[:, lam]) + linalg.solve_triangular( + L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, + lower=1, + overwrite_b=True, + check_finite=False, + ) + v = nrm2(L[n_active, :n_active]) ** 2 + Lkk = linalg.norm(X[:, lam]) ** 2 - v + if Lkk <= min_float: # selected atoms are dependent + warnings.warn(premature, RuntimeWarning, stacklevel=2) + break + L[n_active, n_active] = sqrt(Lkk) + else: + L[0, 0] = linalg.norm(X[:, lam]) + + X.T[n_active], X.T[lam] = swap(X.T[n_active], X.T[lam]) + alpha[n_active], alpha[lam] = alpha[lam], alpha[n_active] + indices[n_active], indices[lam] = indices[lam], indices[n_active] + n_active += 1 + + # solves LL'x = X'y as a composition of two triangular systems + gamma, _ = potrs( + L[:n_active, :n_active], alpha[:n_active], lower=True, overwrite_b=False + ) + + if return_path: + coefs[:n_active, n_active - 1] = gamma + residual = y - np.dot(X[:, :n_active], gamma) + if tol is not None and nrm2(residual) ** 2 <= tol: + break + elif n_active == max_features: + break + + if return_path: + return gamma, indices[:n_active], coefs[:, :n_active], n_active + else: + return gamma, indices[:n_active], n_active + + +def _gram_omp( + Gram, + Xy, + n_nonzero_coefs, + tol_0=None, + tol=None, + copy_Gram=True, + copy_Xy=True, + return_path=False, +): + """Orthogonal Matching Pursuit step on a precomputed Gram matrix. + + This function uses the Cholesky decomposition method. + + Parameters + ---------- + Gram : ndarray of shape (n_features, n_features) + Gram matrix of the input data matrix. + + Xy : ndarray of shape (n_features,) + Input targets. + + n_nonzero_coefs : int + Targeted number of non-zero elements. + + tol_0 : float, default=None + Squared norm of y, required if tol is not None. + + tol : float, default=None + Targeted squared error, if not None overrides n_nonzero_coefs. + + copy_Gram : bool, default=True + Whether the gram matrix must be copied by the algorithm. A false + value is only helpful if it is already Fortran-ordered, otherwise a + copy is made anyway. + + copy_Xy : bool, default=True + Whether the covariance vector Xy must be copied by the algorithm. + If False, it may be overwritten. + + return_path : bool, default=False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + Returns + ------- + gamma : ndarray of shape (n_nonzero_coefs,) + Non-zero elements of the solution. + + idx : ndarray of shape (n_nonzero_coefs,) + Indices of the positions of the elements in gamma within the solution + vector. + + coefs : ndarray of shape (n_features, n_nonzero_coefs) + The first k values of column k correspond to the coefficient value + for the active features at that step. The lower left triangle contains + garbage. Only returned if ``return_path=True``. + + n_active : int + Number of active features at convergence. + """ + Gram = Gram.copy("F") if copy_Gram else np.asfortranarray(Gram) + + if copy_Xy or not Xy.flags.writeable: + Xy = Xy.copy() + + min_float = np.finfo(Gram.dtype).eps + nrm2, swap = linalg.get_blas_funcs(("nrm2", "swap"), (Gram,)) + (potrs,) = get_lapack_funcs(("potrs",), (Gram,)) + + indices = np.arange(len(Gram)) # keeping track of swapping + alpha = Xy + tol_curr = tol_0 + delta = 0 + gamma = np.empty(0) + n_active = 0 + + max_features = len(Gram) if tol is not None else n_nonzero_coefs + + L = np.empty((max_features, max_features), dtype=Gram.dtype) + + L[0, 0] = 1.0 + if return_path: + coefs = np.empty_like(L) + + while True: + lam = np.argmax(np.abs(alpha)) + if lam < n_active or alpha[lam] ** 2 < min_float: + # selected same atom twice, or inner product too small + warnings.warn(premature, RuntimeWarning, stacklevel=3) + break + if n_active > 0: + L[n_active, :n_active] = Gram[lam, :n_active] + linalg.solve_triangular( + L[:n_active, :n_active], + L[n_active, :n_active], + trans=0, + lower=1, + overwrite_b=True, + check_finite=False, + ) + v = nrm2(L[n_active, :n_active]) ** 2 + Lkk = Gram[lam, lam] - v + if Lkk <= min_float: # selected atoms are dependent + warnings.warn(premature, RuntimeWarning, stacklevel=3) + break + L[n_active, n_active] = sqrt(Lkk) + else: + L[0, 0] = sqrt(Gram[lam, lam]) + + Gram[n_active], Gram[lam] = swap(Gram[n_active], Gram[lam]) + Gram.T[n_active], Gram.T[lam] = swap(Gram.T[n_active], Gram.T[lam]) + indices[n_active], indices[lam] = indices[lam], indices[n_active] + Xy[n_active], Xy[lam] = Xy[lam], Xy[n_active] + n_active += 1 + # solves LL'x = X'y as a composition of two triangular systems + gamma, _ = potrs( + L[:n_active, :n_active], Xy[:n_active], lower=True, overwrite_b=False + ) + if return_path: + coefs[:n_active, n_active - 1] = gamma + beta = np.dot(Gram[:, :n_active], gamma) + alpha = Xy - beta + if tol is not None: + tol_curr += delta + delta = np.inner(gamma, beta[:n_active]) + tol_curr -= delta + if abs(tol_curr) <= tol: + break + elif n_active == max_features: + break + + if return_path: + return gamma, indices[:n_active], coefs[:, :n_active], n_active + else: + return gamma, indices[:n_active], n_active + + +@validate_params( + { + "X": ["array-like"], + "y": [np.ndarray], + "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None], + "tol": [Interval(Real, 0, None, closed="left"), None], + "precompute": ["boolean", StrOptions({"auto"})], + "copy_X": ["boolean"], + "return_path": ["boolean"], + "return_n_iter": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def orthogonal_mp( + X, + y, + *, + n_nonzero_coefs=None, + tol=None, + precompute=False, + copy_X=True, + return_path=False, + return_n_iter=False, +): + r"""Orthogonal Matching Pursuit (OMP). + + Solves n_targets Orthogonal Matching Pursuit problems. + An instance of the problem has the form: + + When parametrized by the number of non-zero coefficients using + `n_nonzero_coefs`: + argmin ||y - X\gamma||^2 subject to ||\gamma||_0 <= n_{nonzero coefs} + + When parametrized by error using the parameter `tol`: + argmin ||\gamma||_0 subject to ||y - X\gamma||^2 <= tol + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data. Columns are assumed to have unit norm. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Input targets. + + n_nonzero_coefs : int, default=None + Desired number of non-zero entries in the solution. If None (by + default) this value is set to 10% of n_features. + + tol : float, default=None + Maximum squared norm of the residual. If not None, overrides n_nonzero_coefs. + + precompute : 'auto' or bool, default=False + Whether to perform precomputations. Improves performance when n_targets + or n_samples is very large. + + copy_X : bool, default=True + Whether the design matrix X must be copied by the algorithm. A false + value is only helpful if X is already Fortran-ordered, otherwise a + copy is made anyway. + + return_path : bool, default=False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + Returns + ------- + coef : ndarray of shape (n_features,) or (n_features, n_targets) + Coefficients of the OMP solution. If `return_path=True`, this contains + the whole coefficient path. In this case its shape is + (n_features, n_features) or (n_features, n_targets, n_features) and + iterating over the last axis generates coefficients in increasing order + of active features. + + n_iters : array-like or int + Number of active features across every target. Returned only if + `return_n_iter` is set to True. + + See Also + -------- + OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model. + orthogonal_mp_gram : Solve OMP problems using Gram matrix and the product X.T * y. + lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm. + sklearn.decomposition.sparse_encode : Sparse coding. + + Notes + ----- + Orthogonal matching pursuit was introduced in S. Mallat, Z. Zhang, + Matching pursuits with time-frequency dictionaries, IEEE Transactions on + Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. + (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf) + + This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, + M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal + Matching Pursuit Technical Report - CS Technion, April 2008. + https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.linear_model import orthogonal_mp + >>> X, y = make_regression(noise=4, random_state=0) + >>> coef = orthogonal_mp(X, y) + >>> coef.shape + (100,) + >>> X[:1,] @ coef + array([-78.68]) + """ + X = check_array(X, order="F", copy=copy_X) + copy_X = False + if y.ndim == 1: + y = y.reshape(-1, 1) + y = check_array(y) + if y.shape[1] > 1: # subsequent targets will be affected + copy_X = True + if n_nonzero_coefs is None and tol is None: + # default for n_nonzero_coefs is 0.1 * n_features + # but at least one. + n_nonzero_coefs = max(int(0.1 * X.shape[1]), 1) + if tol is None and n_nonzero_coefs > X.shape[1]: + raise ValueError( + "The number of atoms cannot be more than the number of features" + ) + if precompute == "auto": + precompute = X.shape[0] > X.shape[1] + if precompute: + G = np.dot(X.T, X) + G = np.asfortranarray(G) + Xy = np.dot(X.T, y) + if tol is not None: + norms_squared = np.sum((y**2), axis=0) + else: + norms_squared = None + return orthogonal_mp_gram( + G, + Xy, + n_nonzero_coefs=n_nonzero_coefs, + tol=tol, + norms_squared=norms_squared, + copy_Gram=copy_X, + copy_Xy=False, + return_path=return_path, + ) + + if return_path: + coef = np.zeros((X.shape[1], y.shape[1], X.shape[1])) + else: + coef = np.zeros((X.shape[1], y.shape[1])) + n_iters = [] + + for k in range(y.shape[1]): + out = _cholesky_omp( + X, y[:, k], n_nonzero_coefs, tol, copy_X=copy_X, return_path=return_path + ) + if return_path: + _, idx, coefs, n_iter = out + coef = coef[:, :, : len(idx)] + for n_active, x in enumerate(coefs.T): + coef[idx[: n_active + 1], k, n_active] = x[: n_active + 1] + else: + x, idx, n_iter = out + coef[idx, k] = x + n_iters.append(n_iter) + + if y.shape[1] == 1: + n_iters = n_iters[0] + + if return_n_iter: + return np.squeeze(coef), n_iters + else: + return np.squeeze(coef) + + +@validate_params( + { + "Gram": ["array-like"], + "Xy": ["array-like"], + "n_nonzero_coefs": [Interval(Integral, 0, None, closed="neither"), None], + "tol": [Interval(Real, 0, None, closed="left"), None], + "norms_squared": ["array-like", None], + "copy_Gram": ["boolean"], + "copy_Xy": ["boolean"], + "return_path": ["boolean"], + "return_n_iter": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def orthogonal_mp_gram( + Gram, + Xy, + *, + n_nonzero_coefs=None, + tol=None, + norms_squared=None, + copy_Gram=True, + copy_Xy=True, + return_path=False, + return_n_iter=False, +): + """Gram Orthogonal Matching Pursuit (OMP). + + Solves n_targets Orthogonal Matching Pursuit problems using only + the Gram matrix X.T * X and the product X.T * y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + Gram : array-like of shape (n_features, n_features) + Gram matrix of the input data: `X.T * X`. + + Xy : array-like of shape (n_features,) or (n_features, n_targets) + Input targets multiplied by `X`: `X.T * y`. + + n_nonzero_coefs : int, default=None + Desired number of non-zero entries in the solution. If `None` (by + default) this value is set to 10% of n_features. + + tol : float, default=None + Maximum squared norm of the residual. If not `None`, + overrides `n_nonzero_coefs`. + + norms_squared : array-like of shape (n_targets,), default=None + Squared L2 norms of the lines of `y`. Required if `tol` is not None. + + copy_Gram : bool, default=True + Whether the gram matrix must be copied by the algorithm. A `False` + value is only helpful if it is already Fortran-ordered, otherwise a + copy is made anyway. + + copy_Xy : bool, default=True + Whether the covariance vector `Xy` must be copied by the algorithm. + If `False`, it may be overwritten. + + return_path : bool, default=False + Whether to return every value of the nonzero coefficients along the + forward path. Useful for cross-validation. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + Returns + ------- + coef : ndarray of shape (n_features,) or (n_features, n_targets) + Coefficients of the OMP solution. If `return_path=True`, this contains + the whole coefficient path. In this case its shape is + `(n_features, n_features)` or `(n_features, n_targets, n_features)` and + iterating over the last axis yields coefficients in increasing order + of active features. + + n_iters : list or int + Number of active features across every target. Returned only if + `return_n_iter` is set to True. + + See Also + -------- + OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model (OMP). + orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems. + lars_path : Compute Least Angle Regression or Lasso path using + LARS algorithm. + sklearn.decomposition.sparse_encode : Generic sparse coding. + Each column of the result is the solution to a Lasso problem. + + Notes + ----- + Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang, + Matching pursuits with time-frequency dictionaries, IEEE Transactions on + Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. + (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf) + + This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, + M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal + Matching Pursuit Technical Report - CS Technion, April 2008. + https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf + + Examples + -------- + >>> from sklearn.datasets import make_regression + >>> from sklearn.linear_model import orthogonal_mp_gram + >>> X, y = make_regression(noise=4, random_state=0) + >>> coef = orthogonal_mp_gram(X.T @ X, X.T @ y) + >>> coef.shape + (100,) + >>> X[:1,] @ coef + array([-78.68]) + """ + Gram = check_array(Gram, order="F", copy=copy_Gram) + Xy = np.asarray(Xy) + if Xy.ndim > 1 and Xy.shape[1] > 1: + # or subsequent target will be affected + copy_Gram = True + if Xy.ndim == 1: + Xy = Xy[:, np.newaxis] + if tol is not None: + norms_squared = [norms_squared] + if copy_Xy or not Xy.flags.writeable: + # Make the copy once instead of many times in _gram_omp itself. + Xy = Xy.copy() + + if n_nonzero_coefs is None and tol is None: + n_nonzero_coefs = int(0.1 * len(Gram)) + if tol is not None and norms_squared is None: + raise ValueError( + "Gram OMP needs the precomputed norms in order " + "to evaluate the error sum of squares." + ) + if tol is not None and tol < 0: + raise ValueError("Epsilon cannot be negative") + if tol is None and n_nonzero_coefs <= 0: + raise ValueError("The number of atoms must be positive") + if tol is None and n_nonzero_coefs > len(Gram): + raise ValueError( + "The number of atoms cannot be more than the number of features" + ) + + if return_path: + coef = np.zeros((len(Gram), Xy.shape[1], len(Gram)), dtype=Gram.dtype) + else: + coef = np.zeros((len(Gram), Xy.shape[1]), dtype=Gram.dtype) + + n_iters = [] + for k in range(Xy.shape[1]): + out = _gram_omp( + Gram, + Xy[:, k], + n_nonzero_coefs, + norms_squared[k] if tol is not None else None, + tol, + copy_Gram=copy_Gram, + copy_Xy=False, + return_path=return_path, + ) + if return_path: + _, idx, coefs, n_iter = out + coef = coef[:, :, : len(idx)] + for n_active, x in enumerate(coefs.T): + coef[idx[: n_active + 1], k, n_active] = x[: n_active + 1] + else: + x, idx, n_iter = out + coef[idx, k] = x + n_iters.append(n_iter) + + if Xy.shape[1] == 1: + n_iters = n_iters[0] + + if return_n_iter: + return np.squeeze(coef), n_iters + else: + return np.squeeze(coef) + + +class OrthogonalMatchingPursuit(MultiOutputMixin, RegressorMixin, LinearModel): + """Orthogonal Matching Pursuit model (OMP). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_nonzero_coefs : int, default=None + Desired number of non-zero entries in the solution. Ignored if `tol` is set. + When `None` and `tol` is also `None`, this value is either set to 10% of + `n_features` or 1, whichever is greater. + + tol : float, default=None + Maximum squared norm of the residual. If not None, overrides n_nonzero_coefs. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + precompute : 'auto' or bool, default='auto' + Whether to use a precomputed Gram and Xy matrix to speed up + calculations. Improves performance when :term:`n_targets` or + :term:`n_samples` is very large. Note that if you already have such + matrices, you can pass them directly to the fit method. + + Attributes + ---------- + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the formula). + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. + + n_iter_ : int or array-like + Number of active features across every target. + + n_nonzero_coefs_ : int or None + The number of non-zero coefficients in the solution or `None` when `tol` is + set. If `n_nonzero_coefs` is None and `tol` is None this value is either set + to 10% of `n_features` or 1, whichever is greater. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems. + orthogonal_mp_gram : Solves n_targets Orthogonal Matching Pursuit + problems using only the Gram matrix X.T * X and the product X.T * y. + lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm. + Lars : Least Angle Regression model a.k.a. LAR. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + sklearn.decomposition.sparse_encode : Generic sparse coding. + Each column of the result is the solution to a Lasso problem. + OrthogonalMatchingPursuitCV : Cross-validated + Orthogonal Matching Pursuit model (OMP). + + Notes + ----- + Orthogonal matching pursuit was introduced in G. Mallat, Z. Zhang, + Matching pursuits with time-frequency dictionaries, IEEE Transactions on + Signal Processing, Vol. 41, No. 12. (December 1993), pp. 3397-3415. + (https://www.di.ens.fr/~mallat/papiers/MallatPursuit93.pdf) + + This implementation is based on Rubinstein, R., Zibulevsky, M. and Elad, + M., Efficient Implementation of the K-SVD Algorithm using Batch Orthogonal + Matching Pursuit Technical Report - CS Technion, April 2008. + https://www.cs.technion.ac.il/~ronrubin/Publications/KSVD-OMP-v2.pdf + + Examples + -------- + >>> from sklearn.linear_model import OrthogonalMatchingPursuit + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression(noise=4, random_state=0) + >>> reg = OrthogonalMatchingPursuit().fit(X, y) + >>> reg.score(X, y) + 0.9991 + >>> reg.predict(X[:1,]) + array([-78.3854]) + """ + + _parameter_constraints: dict = { + "n_nonzero_coefs": [Interval(Integral, 1, None, closed="left"), None], + "tol": [Interval(Real, 0, None, closed="left"), None], + "fit_intercept": ["boolean"], + "precompute": [StrOptions({"auto"}), "boolean"], + } + + def __init__( + self, + *, + n_nonzero_coefs=None, + tol=None, + fit_intercept=True, + precompute="auto", + ): + self.n_nonzero_coefs = n_nonzero_coefs + self.tol = tol + self.fit_intercept = fit_intercept + self.precompute = precompute + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. Will be cast to X's dtype if necessary. + + Returns + ------- + self : object + Returns an instance of self. + """ + X, y = validate_data(self, X, y, multi_output=True, y_numeric=True) + n_features = X.shape[1] + + X, y, X_offset, y_offset, X_scale, Gram, Xy = _pre_fit( + X, y, None, self.precompute, self.fit_intercept, copy=True + ) + + if y.ndim == 1: + y = y[:, np.newaxis] + + if self.n_nonzero_coefs is None and self.tol is None: + # default for n_nonzero_coefs is 0.1 * n_features + # but at least one. + self.n_nonzero_coefs_ = max(int(0.1 * n_features), 1) + elif self.tol is not None: + self.n_nonzero_coefs_ = None + else: + self.n_nonzero_coefs_ = self.n_nonzero_coefs + + if Gram is False: + coef_, self.n_iter_ = orthogonal_mp( + X, + y, + n_nonzero_coefs=self.n_nonzero_coefs_, + tol=self.tol, + precompute=False, + copy_X=True, + return_n_iter=True, + ) + else: + norms_sq = np.sum(y**2, axis=0) if self.tol is not None else None + + coef_, self.n_iter_ = orthogonal_mp_gram( + Gram, + Xy=Xy, + n_nonzero_coefs=self.n_nonzero_coefs_, + tol=self.tol, + norms_squared=norms_sq, + copy_Gram=True, + copy_Xy=True, + return_n_iter=True, + ) + self.coef_ = coef_.T + self._set_intercept(X_offset, y_offset, X_scale) + return self + + +def _omp_path_residues( + X_train, + y_train, + X_test, + y_test, + copy=True, + fit_intercept=True, + max_iter=100, +): + """Compute the residues on left-out data for a full LARS path. + + Parameters + ---------- + X_train : ndarray of shape (n_samples, n_features) + The data to fit the LARS on. + + y_train : ndarray of shape (n_samples) + The target variable to fit LARS on. + + X_test : ndarray of shape (n_samples, n_features) + The data to compute the residues on. + + y_test : ndarray of shape (n_samples) + The target variable to compute the residues on. + + copy : bool, default=True + Whether X_train, X_test, y_train and y_test should be copied. If + False, they may be overwritten. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + max_iter : int, default=100 + Maximum numbers of iterations to perform, therefore maximum features + to include. 100 by default. + + Returns + ------- + residues : ndarray of shape (n_samples, max_features) + Residues of the prediction on the test data. + """ + + if copy: + X_train = X_train.copy() + y_train = y_train.copy() + X_test = X_test.copy() + y_test = y_test.copy() + + if fit_intercept: + X_mean = X_train.mean(axis=0) + X_train -= X_mean + X_test -= X_mean + y_mean = y_train.mean(axis=0) + y_train = as_float_array(y_train, copy=False) + y_train -= y_mean + y_test = as_float_array(y_test, copy=False) + y_test -= y_mean + + coefs = orthogonal_mp( + X_train, + y_train, + n_nonzero_coefs=max_iter, + tol=None, + precompute=False, + copy_X=False, + return_path=True, + ) + if coefs.ndim == 1: + coefs = coefs[:, np.newaxis] + + return np.dot(coefs.T, X_test.T) - y_test + + +class OrthogonalMatchingPursuitCV(RegressorMixin, LinearModel): + """Cross-validated Orthogonal Matching Pursuit model (OMP). + + See glossary entry for :term:`cross-validation estimator`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + copy : bool, default=True + Whether the design matrix X must be copied by the algorithm. A false + value is only helpful if X is already Fortran-ordered, otherwise a + copy is made anyway. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + max_iter : int, default=None + Maximum numbers of iterations to perform, therefore maximum features + to include. 10% of ``n_features`` but at least 5 if available. + + cv : int, cross-validation generator or iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross-validation, + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : bool or int, default=False + Sets the verbosity amount. + + Attributes + ---------- + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. + + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Parameter vector (w in the problem formulation). + + n_nonzero_coefs_ : int + Estimated number of non-zero coefficients giving the best mean squared + error over the cross-validation folds. + + n_iter_ : int or array-like + Number of active features across every target for the model refit with + the best hyperparameters got by cross-validating across all folds. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + orthogonal_mp : Solves n_targets Orthogonal Matching Pursuit problems. + orthogonal_mp_gram : Solves n_targets Orthogonal Matching Pursuit + problems using only the Gram matrix X.T * X and the product X.T * y. + lars_path : Compute Least Angle Regression or Lasso path using LARS algorithm. + Lars : Least Angle Regression model a.k.a. LAR. + LassoLars : Lasso model fit with Least Angle Regression a.k.a. Lars. + OrthogonalMatchingPursuit : Orthogonal Matching Pursuit model (OMP). + LarsCV : Cross-validated Least Angle Regression model. + LassoLarsCV : Cross-validated Lasso model fit with Least Angle Regression. + sklearn.decomposition.sparse_encode : Generic sparse coding. + Each column of the result is the solution to a Lasso problem. + + Notes + ----- + In `fit`, once the optimal number of non-zero coefficients is found through + cross-validation, the model is fit again using the entire training set. + + Examples + -------- + >>> from sklearn.linear_model import OrthogonalMatchingPursuitCV + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression(n_features=100, n_informative=10, + ... noise=4, random_state=0) + >>> reg = OrthogonalMatchingPursuitCV(cv=5).fit(X, y) + >>> reg.score(X, y) + 0.9991 + >>> reg.n_nonzero_coefs_ + np.int64(10) + >>> reg.predict(X[:1,]) + array([-78.3854]) + """ + + _parameter_constraints: dict = { + "copy": ["boolean"], + "fit_intercept": ["boolean"], + "max_iter": [Interval(Integral, 0, None, closed="left"), None], + "cv": ["cv_object"], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + } + + def __init__( + self, + *, + copy=True, + fit_intercept=True, + max_iter=None, + cv=None, + n_jobs=None, + verbose=False, + ): + self.copy = copy + self.fit_intercept = fit_intercept + self.max_iter = max_iter + self.cv = cv + self.n_jobs = n_jobs + self.verbose = verbose + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, **fit_params): + """Fit the model using X, y as training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. Will be cast to X's dtype if necessary. + + **fit_params : dict + Parameters to pass to the underlying splitter. + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Returns an instance of self. + """ + _raise_for_params(fit_params, self, "fit") + + X, y = validate_data(self, X, y, y_numeric=True, ensure_min_features=2) + X = as_float_array(X, copy=False, ensure_all_finite=False) + cv = check_cv(self.cv, classifier=False) + if _routing_enabled(): + routed_params = process_routing(self, "fit", **fit_params) + else: + # TODO(SLEP6): remove when metadata routing cannot be disabled. + routed_params = Bunch() + routed_params.splitter = Bunch(split={}) + max_iter = ( + min(max(int(0.1 * X.shape[1]), 5), X.shape[1]) + if not self.max_iter + else self.max_iter + ) + cv_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose)( + delayed(_omp_path_residues)( + X[train], + y[train], + X[test], + y[test], + self.copy, + self.fit_intercept, + max_iter, + ) + for train, test in cv.split(X, **routed_params.splitter.split) + ) + + min_early_stop = min(fold.shape[0] for fold in cv_paths) + mse_folds = np.array( + [(fold[:min_early_stop] ** 2).mean(axis=1) for fold in cv_paths] + ) + best_n_nonzero_coefs = np.argmin(mse_folds.mean(axis=0)) + 1 + self.n_nonzero_coefs_ = best_n_nonzero_coefs + omp = OrthogonalMatchingPursuit( + n_nonzero_coefs=best_n_nonzero_coefs, + fit_intercept=self.fit_intercept, + ).fit(X, y) + + self.coef_ = omp.coef_ + self.intercept_ = omp.intercept_ + self.n_iter_ = omp.n_iter_ + return self + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.4 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + + router = MetadataRouter(owner=self.__class__.__name__).add( + splitter=self.cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + return router diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_passive_aggressive.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_passive_aggressive.py new file mode 100644 index 0000000000000000000000000000000000000000..61eb06edae85f9c6d04a94c070cd71c1bbbcaa3b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_passive_aggressive.py @@ -0,0 +1,573 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Real + +from ..base import _fit_context +from ..utils._param_validation import Interval, StrOptions +from ._stochastic_gradient import DEFAULT_EPSILON, BaseSGDClassifier, BaseSGDRegressor + + +class PassiveAggressiveClassifier(BaseSGDClassifier): + """Passive Aggressive Classifier. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + C : float, default=1.0 + Maximum step size (regularization). Defaults to 1.0. + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`~sklearn.linear_model.PassiveAggressiveClassifier.partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set aside + a stratified fraction of training data as validation and terminate + training when validation score is not improving by at least `tol` for + `n_iter_no_change` consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + loss : str, default="hinge" + The loss function to be used: + hinge: equivalent to PA-I in the reference paper. + squared_hinge: equivalent to PA-II in the reference paper. + + n_jobs : int or None, default=None + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + 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 `. + + 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. + + class_weight : dict, {class_label: weight} or "balanced" or None, \ + default=None + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + .. versionadded:: 0.17 + parameter *class_weight* to automatically weight samples. + + average : bool or int, default=False + 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. + + .. versionadded:: 0.19 + parameter *average* to use weights averaging in SGD. + + Attributes + ---------- + coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \ + (n_classes, n_features) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + For multiclass fits, it is the maximum over every binary fit. + + classes_ : ndarray of shape (n_classes,) + The unique classes labels. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + See Also + -------- + SGDClassifier : Incrementally trained logistic regression. + Perceptron : Linear perceptron classifier. + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006) + + Examples + -------- + >>> from sklearn.linear_model import PassiveAggressiveClassifier + >>> from sklearn.datasets import make_classification + >>> X, y = make_classification(n_features=4, random_state=0) + >>> clf = PassiveAggressiveClassifier(max_iter=1000, random_state=0, + ... tol=1e-3) + >>> clf.fit(X, y) + PassiveAggressiveClassifier(random_state=0) + >>> print(clf.coef_) + [[0.26642044 0.45070924 0.67251877 0.64185414]] + >>> print(clf.intercept_) + [1.84127814] + >>> print(clf.predict([[0, 0, 0, 0]])) + [1] + """ + + _parameter_constraints: dict = { + **BaseSGDClassifier._parameter_constraints, + "loss": [StrOptions({"hinge", "squared_hinge"})], + "C": [Interval(Real, 0, None, closed="right")], + } + + def __init__( + self, + *, + C=1.0, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + shuffle=True, + verbose=0, + loss="hinge", + n_jobs=None, + random_state=None, + warm_start=False, + class_weight=None, + average=False, + ): + super().__init__( + penalty=None, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + eta0=1.0, + warm_start=warm_start, + class_weight=class_weight, + average=average, + n_jobs=n_jobs, + ) + + self.C = C + self.loss = loss + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, classes=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Subset of the training data. + + y : array-like of shape (n_samples,) + Subset of the target values. + + classes : ndarray of shape (n_classes,) + Classes across all calls to partial_fit. + Can be obtained by via `np.unique(y_all)`, where y_all is the + target vector of the entire dataset. + This argument is required for the first call to partial_fit + and can be omitted in the subsequent calls. + Note that y doesn't need to contain all labels in `classes`. + + Returns + ------- + self : object + Fitted estimator. + """ + if not hasattr(self, "classes_"): + self._more_validate_params(for_partial_fit=True) + + if self.class_weight == "balanced": + raise ValueError( + "class_weight 'balanced' is not supported for " + "partial_fit. For 'balanced' weights, use " + "`sklearn.utils.compute_class_weight` with " + "`class_weight='balanced'`. In place of y you " + "can use a large enough subset of the full " + "training set target to properly estimate the " + "class frequency distributions. Pass the " + "resulting weights as the class_weight " + "parameter." + ) + + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._partial_fit( + X, + y, + alpha=1.0, + C=self.C, + loss="hinge", + learning_rate=lr, + max_iter=1, + classes=classes, + sample_weight=None, + coef_init=None, + intercept_init=None, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + coef_init : ndarray of shape (n_classes, n_features) + The initial coefficients to warm-start the optimization. + + intercept_init : ndarray of shape (n_classes,) + The initial intercept to warm-start the optimization. + + Returns + ------- + self : object + Fitted estimator. + """ + self._more_validate_params() + + lr = "pa1" if self.loss == "hinge" else "pa2" + return self._fit( + X, + y, + alpha=1.0, + C=self.C, + loss="hinge", + learning_rate=lr, + coef_init=coef_init, + intercept_init=intercept_init, + ) + + +class PassiveAggressiveRegressor(BaseSGDRegressor): + """Passive Aggressive Regressor. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + C : float, default=1.0 + Maximum step size (regularization). Defaults to 1.0. + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. Defaults to True. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`~sklearn.linear_model.PassiveAggressiveRegressor.partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation. + score is not improving. If set to True, it will automatically set aside + a fraction of training data as validation and terminate + training when validation score is not improving by at least tol for + n_iter_no_change consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + loss : str, default="epsilon_insensitive" + The loss function to be used: + epsilon_insensitive: equivalent to PA-I in the reference paper. + squared_epsilon_insensitive: equivalent to PA-II in the reference + paper. + + epsilon : float, default=0.1 + If the difference between the current prediction and the correct label + is below this threshold, the model is not updated. + + random_state : int, RandomState instance, default=None + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + 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 `. + + 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. + + average : bool or int, default=False + 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. + + .. versionadded:: 0.19 + parameter *average* to use weights averaging in SGD. + + Attributes + ---------- + coef_ : array, shape = [1, n_features] if n_classes == 2 else [n_classes,\ + n_features] + Weights assigned to the features. + + intercept_ : array, shape = [1] if n_classes == 2 else [n_classes] + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_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 + 1)``. + + See Also + -------- + SGDRegressor : Linear model fitted by minimizing a regularized + empirical loss with SGD. + + References + ---------- + Online Passive-Aggressive Algorithms + + K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR (2006). + + Examples + -------- + >>> from sklearn.linear_model import PassiveAggressiveRegressor + >>> from sklearn.datasets import make_regression + + >>> X, y = make_regression(n_features=4, random_state=0) + >>> regr = PassiveAggressiveRegressor(max_iter=100, random_state=0, + ... tol=1e-3) + >>> regr.fit(X, y) + PassiveAggressiveRegressor(max_iter=100, random_state=0) + >>> print(regr.coef_) + [20.48736655 34.18818427 67.59122734 87.94731329] + >>> print(regr.intercept_) + [-0.02306214] + >>> print(regr.predict([[0, 0, 0, 0]])) + [-0.02306214] + """ + + _parameter_constraints: dict = { + **BaseSGDRegressor._parameter_constraints, + "loss": [StrOptions({"epsilon_insensitive", "squared_epsilon_insensitive"})], + "C": [Interval(Real, 0, None, closed="right")], + "epsilon": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + *, + C=1.0, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + shuffle=True, + verbose=0, + loss="epsilon_insensitive", + epsilon=DEFAULT_EPSILON, + random_state=None, + warm_start=False, + average=False, + ): + super().__init__( + penalty=None, + l1_ratio=0, + epsilon=epsilon, + eta0=1.0, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + warm_start=warm_start, + average=average, + ) + self.C = C + self.loss = loss + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Subset of training data. + + y : numpy array of shape [n_samples] + Subset of target values. + + Returns + ------- + self : object + Fitted estimator. + """ + if not hasattr(self, "coef_"): + self._more_validate_params(for_partial_fit=True) + + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._partial_fit( + X, + y, + alpha=1.0, + C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, + max_iter=1, + sample_weight=None, + coef_init=None, + intercept_init=None, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None): + """Fit linear model with Passive Aggressive algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : numpy array of shape [n_samples] + Target values. + + coef_init : array, shape = [n_features] + The initial coefficients to warm-start the optimization. + + intercept_init : array, shape = [1] + The initial intercept to warm-start the optimization. + + Returns + ------- + self : object + Fitted estimator. + """ + self._more_validate_params() + + lr = "pa1" if self.loss == "epsilon_insensitive" else "pa2" + return self._fit( + X, + y, + alpha=1.0, + C=self.C, + loss="epsilon_insensitive", + learning_rate=lr, + coef_init=coef_init, + intercept_init=intercept_init, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_perceptron.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_perceptron.py new file mode 100644 index 0000000000000000000000000000000000000000..e93200ba385faf037be75654061932ee6e886b7b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_perceptron.py @@ -0,0 +1,226 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Real + +from ..utils._param_validation import Interval, StrOptions +from ._stochastic_gradient import BaseSGDClassifier + + +class Perceptron(BaseSGDClassifier): + """Linear perceptron classifier. + + The implementation is a wrapper around :class:`~sklearn.linear_model.SGDClassifier` + by fixing the `loss` and `learning_rate` parameters as:: + + SGDClassifier(loss="perceptron", learning_rate="constant") + + Other available parameters are described below and are forwarded to + :class:`~sklearn.linear_model.SGDClassifier`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + + penalty : {'l2','l1','elasticnet'}, default=None + The penalty (aka regularization term) to be used. + + alpha : float, default=0.0001 + Constant that multiplies the regularization term if regularization is + used. + + l1_ratio : float, default=0.15 + The Elastic Net mixing parameter, with `0 <= l1_ratio <= 1`. + `l1_ratio=0` corresponds to L2 penalty, `l1_ratio=1` to L1. + Only used if `penalty='elasticnet'`. + + .. versionadded:: 0.24 + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`partial_fit` method. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). + + .. versionadded:: 0.19 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + + eta0 : float, default=1 + Constant by which the updates are multiplied. + + n_jobs : int, default=None + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance or None, default=0 + Used to shuffle the training data, when ``shuffle`` is set to + ``True``. Pass an int for reproducible output across multiple + function calls. + See :term:`Glossary `. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set aside + a stratified fraction of training data as validation and terminate + training when validation score is not improving by at least `tol` for + `n_iter_no_change` consecutive epochs. + + .. versionadded:: 0.20 + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + .. versionadded:: 0.20 + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before early stopping. + + .. versionadded:: 0.20 + + class_weight : dict, {class_label: weight} or "balanced", default=None + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + warm_start : bool, default=False + 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 `. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + The unique classes labels. + + coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \ + (n_classes, n_features) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations to reach the stopping criterion. + For multiclass fits, it is the maximum over every binary fit. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + See Also + -------- + sklearn.linear_model.SGDClassifier : Linear classifiers + (SVM, logistic regression, etc.) with SGD training. + + Notes + ----- + ``Perceptron`` is a classification algorithm which shares the same + underlying implementation with ``SGDClassifier``. In fact, + ``Perceptron()`` is equivalent to `SGDClassifier(loss="perceptron", + eta0=1, learning_rate="constant", penalty=None)`. + + References + ---------- + https://en.wikipedia.org/wiki/Perceptron and references therein. + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.linear_model import Perceptron + >>> X, y = load_digits(return_X_y=True) + >>> clf = Perceptron(tol=1e-3, random_state=0) + >>> clf.fit(X, y) + Perceptron() + >>> clf.score(X, y) + 0.939... + """ + + _parameter_constraints: dict = {**BaseSGDClassifier._parameter_constraints} + _parameter_constraints.pop("loss") + _parameter_constraints.pop("average") + _parameter_constraints.update( + { + "penalty": [StrOptions({"l2", "l1", "elasticnet"}), None], + "alpha": [Interval(Real, 0, None, closed="left")], + "l1_ratio": [Interval(Real, 0, 1, closed="both")], + "eta0": [Interval(Real, 0, None, closed="left")], + } + ) + + def __init__( + self, + *, + penalty=None, + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + eta0=1.0, + n_jobs=None, + random_state=0, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + class_weight=None, + warm_start=False, + ): + super().__init__( + loss="perceptron", + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + random_state=random_state, + learning_rate="constant", + eta0=eta0, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + power_t=0.5, + warm_start=warm_start, + class_weight=class_weight, + n_jobs=n_jobs, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_quantile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..446d232958e8dbe3fec247ab37c05b39469160e8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_quantile.py @@ -0,0 +1,301 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np +from scipy import sparse +from scipy.optimize import linprog + +from ..base import BaseEstimator, RegressorMixin, _fit_context +from ..exceptions import ConvergenceWarning +from ..utils import _safe_indexing +from ..utils._param_validation import Interval, StrOptions +from ..utils.fixes import parse_version, sp_version +from ..utils.validation import _check_sample_weight, validate_data +from ._base import LinearModel + + +class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator): + """Linear regression model that predicts conditional quantiles. + + The linear :class:`QuantileRegressor` optimizes the pinball loss for a + desired `quantile` and is robust to outliers. + + This model uses an L1 regularization like + :class:`~sklearn.linear_model.Lasso`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + quantile : float, default=0.5 + The quantile that the model tries to predict. It must be strictly + between 0 and 1. If 0.5 (default), the model predicts the 50% + quantile, i.e. the median. + + alpha : float, default=1.0 + Regularization constant that multiplies the L1 penalty term. + + fit_intercept : bool, default=True + Whether or not to fit the intercept. + + solver : {'highs-ds', 'highs-ipm', 'highs', 'interior-point', \ + 'revised simplex'}, default='highs' + Method used by :func:`scipy.optimize.linprog` to solve the linear + programming formulation. + + It is recommended to use the highs methods because + they are the fastest ones. Solvers "highs-ds", "highs-ipm" and "highs" + support sparse input data and, in fact, always convert to sparse csc. + + From `scipy>=1.11.0`, "interior-point" is not available anymore. + + .. versionchanged:: 1.4 + The default of `solver` changed to `"highs"` in version 1.4. + + solver_options : dict, default=None + Additional parameters passed to :func:`scipy.optimize.linprog` as + options. If `None` and if `solver='interior-point'`, then + `{"lstsq": True}` is passed to :func:`scipy.optimize.linprog` for the + sake of stability. + + Attributes + ---------- + coef_ : array of shape (n_features,) + Estimated coefficients for the features. + + intercept_ : float + The intercept of the model, aka bias term. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The actual number of iterations performed by the solver. + + See Also + -------- + Lasso : The Lasso is a linear model that estimates sparse coefficients + with l1 regularization. + HuberRegressor : Linear regression model that is robust to outliers. + + Examples + -------- + >>> from sklearn.linear_model import QuantileRegressor + >>> import numpy as np + >>> n_samples, n_features = 10, 2 + >>> rng = np.random.RandomState(0) + >>> y = rng.randn(n_samples) + >>> X = rng.randn(n_samples, n_features) + >>> # the two following lines are optional in practice + >>> from sklearn.utils.fixes import sp_version, parse_version + >>> reg = QuantileRegressor(quantile=0.8).fit(X, y) + >>> np.mean(y <= reg.predict(X)) + np.float64(0.8) + """ + + _parameter_constraints: dict = { + "quantile": [Interval(Real, 0, 1, closed="neither")], + "alpha": [Interval(Real, 0, None, closed="left")], + "fit_intercept": ["boolean"], + "solver": [ + StrOptions( + { + "highs-ds", + "highs-ipm", + "highs", + "interior-point", + "revised simplex", + } + ), + ], + "solver_options": [dict, None], + } + + def __init__( + self, + *, + quantile=0.5, + alpha=1.0, + fit_intercept=True, + solver="highs", + solver_options=None, + ): + self.quantile = quantile + self.alpha = alpha + self.fit_intercept = fit_intercept + self.solver = solver + self.solver_options = solver_options + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit the model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + self : object + Returns self. + """ + X, y = validate_data( + self, + X, + y, + accept_sparse=["csc", "csr", "coo"], + y_numeric=True, + multi_output=False, + ) + sample_weight = _check_sample_weight(sample_weight, X) + + n_features = X.shape[1] + n_params = n_features + + if self.fit_intercept: + n_params += 1 + # Note that centering y and X with _preprocess_data does not work + # for quantile regression. + + # The objective is defined as 1/n * sum(pinball loss) + alpha * L1. + # So we rescale the penalty term, which is equivalent. + alpha = np.sum(sample_weight) * self.alpha + + if self.solver == "interior-point" and sp_version >= parse_version("1.11.0"): + raise ValueError( + f"Solver {self.solver} is not anymore available in SciPy >= 1.11.0." + ) + + if sparse.issparse(X) and self.solver not in ["highs", "highs-ds", "highs-ipm"]: + raise ValueError( + f"Solver {self.solver} does not support sparse X. " + "Use solver 'highs' for example." + ) + # make default solver more stable + if self.solver_options is None and self.solver == "interior-point": + solver_options = {"lstsq": True} + else: + solver_options = self.solver_options + + # After rescaling alpha, the minimization problem is + # min sum(pinball loss) + alpha * L1 + # Use linear programming formulation of quantile regression + # min_x c x + # A_eq x = b_eq + # 0 <= x + # x = (s0, s, t0, t, u, v) = slack variables >= 0 + # intercept = s0 - t0 + # coef = s - t + # c = (0, alpha * 1_p, 0, alpha * 1_p, quantile * 1_n, (1-quantile) * 1_n) + # residual = y - X@coef - intercept = u - v + # A_eq = (1_n, X, -1_n, -X, diag(1_n), -diag(1_n)) + # b_eq = y + # p = n_features + # n = n_samples + # 1_n = vector of length n with entries equal one + # see https://stats.stackexchange.com/questions/384909/ + # + # Filtering out zero sample weights from the beginning makes life + # easier for the linprog solver. + 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 * self.quantile, + sample_weight * (1 - self.quantile), + ] + ) + if self.fit_intercept: + # do not penalize the intercept + c[0] = 0 + c[n_params] = 0 + + if self.solver in ["highs", "highs-ds", "highs-ipm"]: + # Note that highs methods always use a sparse CSC memory layout internally, + # even for optimization problems parametrized using dense numpy arrays. + # Therefore, we work with CSC matrices as early as possible to limit + # unnecessary repeated memory copies. + 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: + 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, + A_eq=A_eq, + b_eq=b_eq, + method=self.solver, + options=solver_options, + ) + solution = result.x + if not result.success: + failure = { + 1: "Iteration limit reached.", + 2: "Problem appears to be infeasible.", + 3: "Problem appears to be unbounded.", + 4: "Numerical difficulties encountered.", + } + warnings.warn( + "Linear programming for QuantileRegressor did not succeed.\n" + f"Status is {result.status}: " + + failure.setdefault(result.status, "unknown reason") + + "\n" + + "Result message of linprog:\n" + + result.message, + ConvergenceWarning, + ) + + # positive slack - negative slack + # solution is an array with (params_pos, params_neg, u, v) + params = solution[:n_params] - solution[n_params : 2 * n_params] + + self.n_iter_ = result.nit + + if self.fit_intercept: + self.coef_ = params[1:] + self.intercept_ = params[0] + else: + self.coef_ = params + self.intercept_ = 0.0 + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ransac.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ransac.py new file mode 100644 index 0000000000000000000000000000000000000000..c18065436dc3518ccb4a2359480cf7db7f36cd7e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ransac.py @@ -0,0 +1,726 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np + +from ..base import ( + BaseEstimator, + MetaEstimatorMixin, + MultiOutputMixin, + RegressorMixin, + _fit_context, + clone, +) +from ..exceptions import ConvergenceWarning +from ..utils import check_consistent_length, check_random_state, get_tags +from ..utils._bunch import Bunch +from ..utils._param_validation import ( + HasMethods, + Interval, + Options, + RealNotInt, + StrOptions, +) +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils.random import sample_without_replacement +from ..utils.validation import ( + _check_method_params, + _check_sample_weight, + check_is_fitted, + has_fit_parameter, + validate_data, +) +from ._base import LinearRegression + +_EPSILON = np.spacing(1) + + +def _dynamic_max_trials(n_inliers, n_samples, min_samples, probability): + """Determine number trials such that at least one outlier-free subset is + sampled for the given inlier/outlier ratio. + + Parameters + ---------- + n_inliers : int + Number of inliers in the data. + + n_samples : int + Total number of samples in the data. + + min_samples : int + Minimum number of samples chosen randomly from original data. + + probability : float + Probability (confidence) that one outlier-free sample is generated. + + Returns + ------- + trials : int + Number of trials. + + """ + inlier_ratio = n_inliers / float(n_samples) + nom = max(_EPSILON, 1 - probability) + denom = max(_EPSILON, 1 - inlier_ratio**min_samples) + if nom == 1: + return 0 + if denom == 1: + return float("inf") + return abs(float(np.ceil(np.log(nom) / np.log(denom)))) + + +class RANSACRegressor( + MetaEstimatorMixin, + RegressorMixin, + MultiOutputMixin, + BaseEstimator, +): + """RANSAC (RANdom SAmple Consensus) algorithm. + + RANSAC is an iterative algorithm for the robust estimation of parameters + from a subset of inliers from the complete data set. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object, default=None + Base estimator object which implements the following methods: + + * `fit(X, y)`: Fit model to given training data and target values. + * `score(X, y)`: Returns the mean accuracy on the given test data, + which is used for the stop criterion defined by `stop_score`. + Additionally, the score is used to decide which of two equally + large consensus sets is chosen as the better one. + * `predict(X)`: Returns predicted values using the linear model, + which is used to compute residual error using loss function. + + If `estimator` is None, then + :class:`~sklearn.linear_model.LinearRegression` is used for + target values of dtype float. + + Note that the current implementation only supports regression + estimators. + + min_samples : int (>= 1) or float ([0, 1]), default=None + Minimum number of samples chosen randomly from original data. Treated + 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 `estimator`. By default a + :class:`~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 `estimator` other than + :class:`~sklearn.linear_model.LinearRegression` is used, the user must + provide a value. + + residual_threshold : float, default=None + Maximum residual for a data sample to be classified as an inlier. + By default the threshold is chosen as the MAD (median absolute + deviation) of the target values `y`. Points whose residuals are + strictly equal to the threshold are considered as inliers. + + is_data_valid : callable, default=None + This function is called with the randomly selected data before the + model is fitted to it: `is_data_valid(X, y)`. If its return value is + False the current randomly chosen sub-sample is skipped. + + is_model_valid : callable, default=None + This function is called with the estimated model and the randomly + selected data: `is_model_valid(model, X, y)`. If its return value is + False the current randomly chosen sub-sample is skipped. + Rejecting samples with this function is computationally costlier than + with `is_data_valid`. `is_model_valid` should therefore only be used if + the estimated model is needed for making the rejection decision. + + max_trials : int, default=100 + Maximum number of iterations for random sample selection. + + max_skips : int, default=np.inf + Maximum number of iterations that can be skipped due to finding zero + inliers or invalid data defined by ``is_data_valid`` or invalid models + defined by ``is_model_valid``. + + .. versionadded:: 0.19 + + stop_n_inliers : int, default=np.inf + Stop iteration if at least this number of inliers are found. + + stop_score : float, default=np.inf + Stop iteration if score is greater equal than this threshold. + + stop_probability : float in range [0, 1], default=0.99 + RANSAC iteration stops if at least one outlier-free set of the training + data is sampled in RANSAC. This requires to generate at least N + samples (iterations):: + + N >= log(1 - probability) / log(1 - e**m) + + where the probability (confidence) is typically set to high value such + as 0.99 (the default) and e is the current fraction of inliers w.r.t. + the total number of samples. + + loss : str, callable, default='absolute_error' + String inputs, 'absolute_error' and 'squared_error' are supported which + find the absolute error and squared error per sample respectively. + + If ``loss`` is a callable, then it should be a function that takes + two arrays as inputs, the true and predicted value and returns a 1-D + array with the i-th value of the array corresponding to the loss + on ``X[i]``. + + If the loss on a sample is greater than the ``residual_threshold``, + then this sample is classified as an outlier. + + .. versionadded:: 0.18 + + random_state : int, RandomState instance, default=None + The generator used to initialize the centers. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + estimator_ : object + Final model fitted on the inliers predicted by the "best" model found + during RANSAC sampling (copy of the `estimator` object). + + n_trials_ : int + Number of random selection trials until one of the stop criteria is + met. It is always ``<= max_trials``. + + inlier_mask_ : bool array of shape [n_samples] + Boolean mask of inliers classified as ``True``. + + n_skips_no_inliers_ : int + Number of iterations skipped due to finding zero inliers. + + .. versionadded:: 0.19 + + n_skips_invalid_data_ : int + Number of iterations skipped due to invalid data defined by + ``is_data_valid``. + + .. versionadded:: 0.19 + + n_skips_invalid_model_ : int + Number of iterations skipped due to an invalid model defined by + ``is_model_valid``. + + .. versionadded:: 0.19 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + HuberRegressor : Linear regression model that is robust to outliers. + TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model. + SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/RANSAC + .. [2] https://www.sri.com/wp-content/uploads/2021/12/ransac-publication.pdf + .. [3] https://bmva-archive.org.uk/bmvc/2009/Papers/Paper355/Paper355.pdf + + Examples + -------- + >>> from sklearn.linear_model import RANSACRegressor + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression( + ... n_samples=200, n_features=2, noise=4.0, random_state=0) + >>> reg = RANSACRegressor(random_state=0).fit(X, y) + >>> reg.score(X, y) + 0.9885 + >>> reg.predict(X[:1,]) + array([-31.9417]) + + For a more detailed example, see + :ref:`sphx_glr_auto_examples_linear_model_plot_ransac.py` + """ + + _parameter_constraints: dict = { + "estimator": [HasMethods(["fit", "score", "predict"]), None], + "min_samples": [ + Interval(Integral, 1, None, closed="left"), + Interval(RealNotInt, 0, 1, closed="both"), + None, + ], + "residual_threshold": [Interval(Real, 0, None, closed="left"), None], + "is_data_valid": [callable, None], + "is_model_valid": [callable, None], + "max_trials": [ + Interval(Integral, 0, None, closed="left"), + Options(Real, {np.inf}), + ], + "max_skips": [ + Interval(Integral, 0, None, closed="left"), + Options(Real, {np.inf}), + ], + "stop_n_inliers": [ + Interval(Integral, 0, None, closed="left"), + Options(Real, {np.inf}), + ], + "stop_score": [Interval(Real, None, None, closed="both")], + "stop_probability": [Interval(Real, 0, 1, closed="both")], + "loss": [StrOptions({"absolute_error", "squared_error"}), callable], + "random_state": ["random_state"], + } + + def __init__( + self, + estimator=None, + *, + min_samples=None, + residual_threshold=None, + is_data_valid=None, + is_model_valid=None, + max_trials=100, + max_skips=np.inf, + stop_n_inliers=np.inf, + stop_score=np.inf, + stop_probability=0.99, + loss="absolute_error", + random_state=None, + ): + self.estimator = estimator + self.min_samples = min_samples + self.residual_threshold = residual_threshold + self.is_data_valid = is_data_valid + self.is_model_valid = is_model_valid + self.max_trials = max_trials + self.max_skips = max_skips + self.stop_n_inliers = stop_n_inliers + self.stop_score = stop_score + self.stop_probability = stop_probability + self.random_state = random_state + self.loss = loss + + @_fit_context( + # RansacRegressor.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y, sample_weight=None, **fit_params): + """Fit estimator using RANSAC algorithm. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Individual weights for each sample + raises error if sample_weight is passed and estimator + fit method does not support it. + + .. versionadded:: 0.18 + + **fit_params : dict + Parameters routed to the `fit` method of the sub-estimator via the + metadata routing API. + + .. versionadded:: 1.5 + + Only available if + `sklearn.set_config(enable_metadata_routing=True)` is set. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + self : object + Fitted `RANSACRegressor` estimator. + + Raises + ------ + ValueError + If no valid consensus set could be found. This occurs if + `is_data_valid` and `is_model_valid` return False for all + `max_trials` randomly chosen sub-samples. + """ + # Need to validate separately here. We can't pass multi_output=True + # because that would allow y to be csr. Delay expensive finiteness + # check to the estimator's own input validation. + _raise_for_params(fit_params, self, "fit") + check_X_params = dict(accept_sparse="csr", ensure_all_finite=False) + check_y_params = dict(ensure_2d=False) + X, y = validate_data( + self, X, y, validate_separately=(check_X_params, check_y_params) + ) + check_consistent_length(X, y) + + if self.estimator is not None: + estimator = clone(self.estimator) + else: + estimator = LinearRegression() + + if self.min_samples is None: + if not isinstance(estimator, LinearRegression): + raise ValueError( + "`min_samples` needs to be explicitly set when estimator " + "is not a LinearRegression." + ) + min_samples = X.shape[1] + 1 + elif 0 < self.min_samples < 1: + min_samples = np.ceil(self.min_samples * X.shape[0]) + elif self.min_samples >= 1: + min_samples = self.min_samples + if min_samples > X.shape[0]: + raise ValueError( + "`min_samples` may not be larger than number " + "of samples: n_samples = %d." % (X.shape[0]) + ) + + if self.residual_threshold is None: + # MAD (median absolute deviation) + residual_threshold = np.median(np.abs(y - np.median(y))) + else: + residual_threshold = self.residual_threshold + + if self.loss == "absolute_error": + if y.ndim == 1: + loss_function = lambda y_true, y_pred: np.abs(y_true - y_pred) + else: + loss_function = lambda y_true, y_pred: np.sum( + np.abs(y_true - y_pred), axis=1 + ) + elif self.loss == "squared_error": + if y.ndim == 1: + loss_function = lambda y_true, y_pred: (y_true - y_pred) ** 2 + else: + loss_function = lambda y_true, y_pred: np.sum( + (y_true - y_pred) ** 2, axis=1 + ) + + elif callable(self.loss): + loss_function = self.loss + + random_state = check_random_state(self.random_state) + + try: # Not all estimator accept a random_state + estimator.set_params(random_state=random_state) + except ValueError: + pass + + 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. Sample" + " weights are only used for the calibration" + " itself." % estimator_name + ) + + if sample_weight is not None: + fit_params["sample_weight"] = sample_weight + + if _routing_enabled(): + routed_params = process_routing(self, "fit", **fit_params) + else: + routed_params = Bunch() + routed_params.estimator = Bunch(fit={}, predict={}, score={}) + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + routed_params.estimator.fit = {"sample_weight": sample_weight} + + n_inliers_best = 1 + score_best = -np.inf + inlier_mask_best = None + X_inlier_best = None + y_inlier_best = None + inlier_best_idxs_subset = None + self.n_skips_no_inliers_ = 0 + self.n_skips_invalid_data_ = 0 + self.n_skips_invalid_model_ = 0 + + # number of data samples + n_samples = X.shape[0] + sample_idxs = np.arange(n_samples) + + self.n_trials_ = 0 + max_trials = self.max_trials + while self.n_trials_ < max_trials: + self.n_trials_ += 1 + + if ( + self.n_skips_no_inliers_ + + self.n_skips_invalid_data_ + + self.n_skips_invalid_model_ + ) > self.max_skips: + break + + # choose random sample set + subset_idxs = sample_without_replacement( + n_samples, min_samples, random_state=random_state + ) + X_subset = X[subset_idxs] + y_subset = y[subset_idxs] + + # check if random sample set is valid + if self.is_data_valid is not None and not self.is_data_valid( + X_subset, y_subset + ): + self.n_skips_invalid_data_ += 1 + continue + + # cut `fit_params` down to `subset_idxs` + fit_params_subset = _check_method_params( + X, params=routed_params.estimator.fit, indices=subset_idxs + ) + + # fit model for current random sample set + estimator.fit(X_subset, y_subset, **fit_params_subset) + + # check if estimated model is valid + if self.is_model_valid is not None and not self.is_model_valid( + estimator, X_subset, y_subset + ): + self.n_skips_invalid_model_ += 1 + continue + + # residuals of all data for current random sample model + y_pred = estimator.predict(X) + residuals_subset = loss_function(y, y_pred) + + # classify data into inliers and outliers + inlier_mask_subset = residuals_subset <= residual_threshold + n_inliers_subset = np.sum(inlier_mask_subset) + + # less inliers -> skip current random sample + if n_inliers_subset < n_inliers_best: + self.n_skips_no_inliers_ += 1 + continue + + # extract inlier data set + inlier_idxs_subset = sample_idxs[inlier_mask_subset] + X_inlier_subset = X[inlier_idxs_subset] + y_inlier_subset = y[inlier_idxs_subset] + + # cut `fit_params` down to `inlier_idxs_subset` + score_params_inlier_subset = _check_method_params( + X, params=routed_params.estimator.score, indices=inlier_idxs_subset + ) + + # score of inlier data set + score_subset = estimator.score( + X_inlier_subset, + y_inlier_subset, + **score_params_inlier_subset, + ) + + # same number of inliers but worse score -> skip current random + # sample + if n_inliers_subset == n_inliers_best and score_subset < score_best: + continue + + # save current random sample as best sample + n_inliers_best = n_inliers_subset + score_best = score_subset + inlier_mask_best = inlier_mask_subset + X_inlier_best = X_inlier_subset + y_inlier_best = y_inlier_subset + inlier_best_idxs_subset = inlier_idxs_subset + + max_trials = min( + max_trials, + _dynamic_max_trials( + n_inliers_best, n_samples, min_samples, self.stop_probability + ), + ) + + # break if sufficient number of inliers or score is reached + if n_inliers_best >= self.stop_n_inliers or score_best >= self.stop_score: + break + + # if none of the iterations met the required criteria + if inlier_mask_best is None: + if ( + self.n_skips_no_inliers_ + + self.n_skips_invalid_data_ + + self.n_skips_invalid_model_ + ) > self.max_skips: + raise ValueError( + "RANSAC skipped more iterations than `max_skips` without" + " finding a valid consensus set. Iterations were skipped" + " because each randomly chosen sub-sample failed the" + " passing criteria. See estimator attributes for" + " diagnostics (n_skips*)." + ) + else: + raise ValueError( + "RANSAC could not find a valid consensus set. All" + " `max_trials` iterations were skipped because each" + " randomly chosen sub-sample failed the passing criteria." + " See estimator attributes for diagnostics (n_skips*)." + ) + else: + if ( + self.n_skips_no_inliers_ + + self.n_skips_invalid_data_ + + self.n_skips_invalid_model_ + ) > self.max_skips: + warnings.warn( + ( + "RANSAC found a valid consensus set but exited" + " early due to skipping more iterations than" + " `max_skips`. See estimator attributes for" + " diagnostics (n_skips*)." + ), + ConvergenceWarning, + ) + + # estimate final model using all inliers + fit_params_best_idxs_subset = _check_method_params( + X, params=routed_params.estimator.fit, indices=inlier_best_idxs_subset + ) + + estimator.fit(X_inlier_best, y_inlier_best, **fit_params_best_idxs_subset) + + self.estimator_ = estimator + self.inlier_mask_ = inlier_mask_best + return self + + def predict(self, X, **params): + """Predict using the estimated model. + + This is a wrapper for `estimator_.predict(X)`. + + Parameters + ---------- + X : {array-like or sparse matrix} of shape (n_samples, n_features) + Input data. + + **params : dict + Parameters routed to the `predict` method of the sub-estimator via + the metadata routing API. + + .. versionadded:: 1.5 + + Only available if + `sklearn.set_config(enable_metadata_routing=True)` is set. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + y : array, shape = [n_samples] or [n_samples, n_targets] + Returns predicted values. + """ + check_is_fitted(self) + X = validate_data( + self, + X, + ensure_all_finite=False, + accept_sparse=True, + reset=False, + ) + + _raise_for_params(params, self, "predict") + + if _routing_enabled(): + predict_params = process_routing(self, "predict", **params).estimator[ + "predict" + ] + else: + predict_params = {} + + return self.estimator_.predict(X, **predict_params) + + def score(self, X, y, **params): + """Return the score of the prediction. + + This is a wrapper for `estimator_.score(X, y)`. + + Parameters + ---------- + X : (array-like or sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + **params : dict + Parameters routed to the `score` method of the sub-estimator via + the metadata routing API. + + .. versionadded:: 1.5 + + Only available if + `sklearn.set_config(enable_metadata_routing=True)` is set. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + z : float + Score of the prediction. + """ + check_is_fitted(self) + X = validate_data( + self, + X, + ensure_all_finite=False, + accept_sparse=True, + reset=False, + ) + + _raise_for_params(params, self, "score") + if _routing_enabled(): + score_params = process_routing(self, "score", **params).estimator["score"] + else: + score_params = {} + + return self.estimator_.score(X, y, **score_params) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.5 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + estimator=self.estimator, + method_mapping=MethodMapping() + .add(caller="fit", callee="fit") + .add(caller="fit", callee="score") + .add(caller="score", callee="score") + .add(caller="predict", callee="predict"), + ) + return router + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + if self.estimator is None: + tags.input_tags.sparse = True # default estimator is LinearRegression + else: + tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ridge.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ridge.py new file mode 100644 index 0000000000000000000000000000000000000000..0a55291a70ace22716d07fecffc931c8dadb093e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_ridge.py @@ -0,0 +1,2899 @@ +""" +Ridge regression +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import warnings +from abc import ABCMeta, abstractmethod +from functools import partial +from numbers import Integral, Real + +import numpy as np +from scipy import linalg, optimize, sparse +from scipy.sparse import linalg as sp_linalg + +from sklearn.base import BaseEstimator + +from ..base import MultiOutputMixin, RegressorMixin, _fit_context, is_classifier +from ..exceptions import ConvergenceWarning +from ..metrics import check_scoring, get_scorer_names +from ..model_selection import GridSearchCV +from ..preprocessing import LabelBinarizer +from ..utils import ( + Bunch, + check_array, + check_consistent_length, + check_scalar, + column_or_1d, + compute_sample_weight, +) +from ..utils._array_api import ( + _is_numpy_namespace, + _ravel, + device, + get_namespace, + get_namespace_and_device, +) +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import row_norms, safe_sparse_dot +from ..utils.fixes import _sparse_linalg_cg +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils.sparsefuncs import mean_variance_axis +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data +from ._base import LinearClassifierMixin, LinearModel, _preprocess_data, _rescale_data +from ._sag import sag_solver + + +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, + alpha, + max_iter=None, + tol=1e-4, + verbose=0, + X_offset=None, + X_scale=None, + sample_weight_sqrt=None, +): + if sample_weight_sqrt is None: + sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) + + n_samples, n_features = X.shape + + if X_offset is None or X_scale is None: + X1 = sp_linalg.aslinearoperator(X) + else: + 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) + + if n_features > n_samples: + + def create_mv(curr_alpha): + def _mv(x): + return X1.matvec(X1.rmatvec(x)) + curr_alpha * x + + return _mv + + else: + + def create_mv(curr_alpha): + def _mv(x): + return X1.rmatvec(X1.matvec(x)) + curr_alpha * x + + return _mv + + for i in range(y.shape[1]): + y_column = y[:, i] + + mv = create_mv(alpha[i]) + if n_features > n_samples: + # kernel ridge + # w = X.T * inv(X X^t + alpha*Id) y + C = sp_linalg.LinearOperator( + (n_samples, n_samples), matvec=mv, dtype=X.dtype + ) + coef, info = _sparse_linalg_cg(C, y_column, rtol=tol) + coefs[i] = X1.rmatvec(coef) + else: + # linear ridge + # w = inv(X^t X + alpha*Id) * X.T y + y_column = X1.rmatvec(y_column) + C = sp_linalg.LinearOperator( + (n_features, n_features), matvec=mv, dtype=X.dtype + ) + coefs[i], info = _sparse_linalg_cg(C, y_column, maxiter=max_iter, rtol=tol) + + if info < 0: + raise ValueError("Failed with error code %d" % info) + + if max_iter is None and info > 0 and verbose: + warnings.warn( + "sparse_cg did not converge after %d iterations." % info, + ConvergenceWarning, + ) + + return coefs + + +def _solve_lsqr( + X, + y, + *, + alpha, + fit_intercept=True, + max_iter=None, + tol=1e-4, + 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) + + # According to the lsqr documentation, alpha = damp^2. + sqrt_alpha = np.sqrt(alpha) + + for i in range(y.shape[1]): + y_column = y[:, i] + info = sp_linalg.lsqr( + X1, y_column, damp=sqrt_alpha[i], atol=tol, btol=tol, iter_lim=max_iter + ) + coefs[i] = info[0] + n_iter[i] = info[2] + + return coefs, n_iter + + +def _solve_cholesky(X, y, alpha): + # w = inv(X^t X + alpha*Id) * X.T y + n_features = X.shape[1] + n_targets = y.shape[1] + + A = safe_sparse_dot(X.T, X, dense_output=True) + Xy = safe_sparse_dot(X.T, y, dense_output=True) + + one_alpha = np.array_equal(alpha, len(alpha) * [alpha[0]]) + + if one_alpha: + A.flat[:: n_features + 1] += alpha[0] + return linalg.solve(A, Xy, assume_a="pos", overwrite_a=True).T + else: + coefs = np.empty([n_targets, n_features], dtype=X.dtype) + for coef, target, current_alpha in zip(coefs, Xy.T, alpha): + A.flat[:: n_features + 1] += current_alpha + coef[:] = linalg.solve(A, target, assume_a="pos", overwrite_a=False).ravel() + A.flat[:: n_features + 1] -= current_alpha + return coefs + + +def _solve_cholesky_kernel(K, y, alpha, sample_weight=None, copy=False): + # dual_coef = inv(X X^t + alpha*Id) y + n_samples = K.shape[0] + n_targets = y.shape[1] + + if copy: + K = K.copy() + + alpha = np.atleast_1d(alpha) + one_alpha = (alpha == alpha[0]).all() + has_sw = isinstance(sample_weight, np.ndarray) or sample_weight not in [1.0, None] + + if has_sw: + # Unlike other solvers, we need to support sample_weight directly + # because K might be a pre-computed kernel. + sw = np.sqrt(np.atleast_1d(sample_weight)) + y = y * sw[:, np.newaxis] + K *= np.outer(sw, sw) + + if one_alpha: + # Only one penalty, we can solve multi-target problems in one time. + K.flat[:: n_samples + 1] += alpha[0] + + try: + # Note: we must use overwrite_a=False in order to be able to + # use the fall-back solution below in case a LinAlgError + # is raised + dual_coef = linalg.solve(K, y, assume_a="pos", overwrite_a=False) + except np.linalg.LinAlgError: + warnings.warn( + "Singular matrix in solving dual problem. Using " + "least-squares solution instead." + ) + dual_coef = linalg.lstsq(K, y)[0] + + # K is expensive to compute and store in memory so change it back in + # case it was user-given. + K.flat[:: n_samples + 1] -= alpha[0] + + if has_sw: + dual_coef *= sw[:, np.newaxis] + + return dual_coef + else: + # One penalty per target. We need to solve each target separately. + dual_coefs = np.empty([n_targets, n_samples], K.dtype) + + for dual_coef, target, current_alpha in zip(dual_coefs, y.T, alpha): + K.flat[:: n_samples + 1] += current_alpha + + dual_coef[:] = linalg.solve( + K, target, assume_a="pos", overwrite_a=False + ).ravel() + + K.flat[:: n_samples + 1] -= current_alpha + + if has_sw: + dual_coefs *= sw[np.newaxis, :] + + return dual_coefs.T + + +def _solve_svd(X, y, alpha, xp=None): + xp, _ = get_namespace(X, xp=xp) + U, s, Vt = xp.linalg.svd(X, full_matrices=False) + idx = s > 1e-15 # same default value as scipy.linalg.pinv + s_nnz = s[idx][:, None] + UTy = U.T @ y + d = xp.zeros((s.shape[0], alpha.shape[0]), dtype=X.dtype, device=device(X)) + d[idx] = s_nnz / (s_nnz**2 + alpha) + d_UT_y = d * UTy + return (Vt.T @ d_UT_y).T + + +def _solve_lbfgs( + X, + y, + alpha, + positive=True, + max_iter=None, + tol=1e-4, + X_offset=None, + X_scale=None, + sample_weight_sqrt=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 + + if sample_weight_sqrt is None: + sample_weight_sqrt = np.ones(X.shape[0], dtype=X.dtype) + + 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 -= sample_weight_sqrt * 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 * residual.dot(sample_weight_sqrt) + + 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" + else: + return ["csr", "csc", "coo"] + + +@validate_params( + { + "X": ["array-like", "sparse matrix", sp_linalg.LinearOperator], + "y": ["array-like"], + "alpha": [Interval(Real, 0, None, closed="left"), "array-like"], + "sample_weight": [ + Interval(Real, None, None, closed="neither"), + "array-like", + None, + ], + "solver": [ + StrOptions( + {"auto", "svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga", "lbfgs"} + ) + ], + "max_iter": [Interval(Integral, 0, None, closed="left"), None], + "tol": [Interval(Real, 0, None, closed="left")], + "verbose": ["verbose"], + "positive": ["boolean"], + "random_state": ["random_state"], + "return_n_iter": ["boolean"], + "return_intercept": ["boolean"], + "check_input": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def ridge_regression( + X, + y, + alpha, + *, + sample_weight=None, + solver="auto", + max_iter=None, + tol=1e-4, + verbose=0, + positive=False, + random_state=None, + return_n_iter=False, + return_intercept=False, + check_input=True, +): + """Solve the ridge equation by the method of normal equations. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix, LinearOperator} of shape \ + (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) or (n_samples, n_targets) + Target values. + + alpha : float or array-like of shape (n_targets,) + Constant that multiplies the L2 term, controlling regularization + strength. `alpha` must be a non-negative float i.e. in `[0, inf)`. + + When `alpha = 0`, the objective is equivalent to ordinary least + squares, solved by the :class:`LinearRegression` object. For numerical + reasons, using `alpha = 0` with the `Ridge` object is not advised. + Instead, you should use the :class:`LinearRegression` object. + + If an array is passed, penalties are assumed to be specific to the + targets. Hence they must correspond in number. + + sample_weight : float or array-like of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. If sample_weight is not None and + solver='auto', the solver will be set to 'cholesky'. + + .. versionadded:: 0.17 + + 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. + + - 'svd' uses a Singular Value Decomposition of X to compute the Ridge + coefficients. It is the most stable solver, in particular more stable + for singular matrices than 'cholesky' at the cost of being slower. + + - 'cholesky' uses the standard scipy.linalg.solve function to + obtain a closed-form solution via a Cholesky decomposition of + dot(X.T, X) + + - 'sparse_cg' uses the conjugate gradient solver as found in + scipy.sparse.linalg.cg. As an iterative algorithm, this solver is + more appropriate than 'cholesky' for large-scale data + (possibility to set `tol` and `max_iter`). + + - 'lsqr' uses the dedicated regularized least-squares routine + scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative + procedure. + + - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses + its improved, unbiased version named SAGA. Both methods also use an + iterative procedure, and are often faster than other solvers when + both n_samples and n_features are large. Note that 'sag' and + 'saga' fast convergence is only guaranteed on features with + 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 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. + .. versionadded:: 0.19 + SAGA solver. + + max_iter : int, default=None + 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. For 'lbfgs' solver, the default value is 15000. + + tol : float, default=1e-4 + Precision of the solution. Note that `tol` has no effect for solvers 'svd' and + 'cholesky'. + + .. versionchanged:: 1.2 + Default value changed from 1e-3 to 1e-4 for consistency with other linear + models. + + verbose : int, default=0 + 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 ` for details. + + return_n_iter : bool, default=False + If True, the method also returns `n_iter`, the actual number of + iteration performed by the solver. + + .. versionadded:: 0.17 + + return_intercept : bool, default=False + If True and if X is sparse, the method also returns the intercept, + and the solver is automatically changed to 'sag'. This is only a + temporary fix for fitting the intercept with sparse data. For dense + data, use sklearn.linear_model._preprocess_data before your regression. + + .. versionadded:: 0.17 + + check_input : bool, default=True + If False, the input arrays X and y will not be checked. + + .. versionadded:: 0.21 + + Returns + ------- + coef : ndarray of shape (n_features,) or (n_targets, n_features) + Weight vector(s). + + n_iter : int, optional + The actual number of iteration performed by the solver. + Only returned if `return_n_iter` is True. + + intercept : float or ndarray of shape (n_targets,) + The intercept of the model. Only returned if `return_intercept` + is True and if X is a scipy sparse array. + + Notes + ----- + This function won't compute the intercept. + + Regularization improves the conditioning of the problem and + reduces the variance of the estimates. Larger values specify stronger + regularization. Alpha corresponds to ``1 / (2C)`` in other linear + models such as :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. If an array is passed, penalties are + assumed to be specific to the targets. Hence they must correspond in + number. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.datasets import make_regression + >>> from sklearn.linear_model import ridge_regression + >>> rng = np.random.RandomState(0) + >>> X = rng.randn(100, 4) + >>> y = 2.0 * X[:, 0] - 1.0 * X[:, 1] + 0.1 * rng.standard_normal(100) + >>> coef, intercept = ridge_regression(X, y, alpha=1.0, return_intercept=True, + ... random_state=0) + >>> coef + array([ 1.97, -1., -2.69e-3, -9.27e-4 ]) + >>> intercept + np.float64(-.0012) + """ + return _ridge_regression( + X, + y, + alpha, + sample_weight=sample_weight, + solver=solver, + max_iter=max_iter, + tol=tol, + verbose=verbose, + positive=positive, + random_state=random_state, + return_n_iter=return_n_iter, + return_intercept=return_intercept, + X_scale=None, + X_offset=None, + check_input=check_input, + ) + + +def _ridge_regression( + X, + y, + alpha, + sample_weight=None, + solver="auto", + max_iter=None, + tol=1e-4, + verbose=0, + positive=False, + random_state=None, + return_n_iter=False, + return_intercept=False, + return_solver=False, + X_scale=None, + X_offset=None, + check_input=True, + fit_intercept=False, +): + xp, is_array_api_compliant, device_ = get_namespace_and_device( + X, y, sample_weight, X_scale, X_offset + ) + is_numpy_namespace = _is_numpy_namespace(xp) + X_is_sparse = sparse.issparse(X) + + has_sw = sample_weight is not None + + solver = resolve_solver(solver, positive, return_intercept, X_is_sparse, xp) + + if is_numpy_namespace and not X_is_sparse: + X = np.asarray(X) + + if not is_numpy_namespace and solver != "svd": + raise ValueError( + f"Array API dispatch to namespace {xp.__name__} only supports " + f"solver 'svd'. Got '{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": + raise ValueError( + "In Ridge, only 'sag' solver can directly fit the " + "intercept. Please change solver to 'sag' or set " + "return_intercept=False." + ) + + if check_input: + _dtype = [xp.float64, xp.float32] + _accept_sparse = _get_valid_accept_sparse(X_is_sparse, solver) + X = check_array(X, accept_sparse=_accept_sparse, dtype=_dtype, order="C") + y = check_array(y, dtype=X.dtype, ensure_2d=False, order=None) + check_consistent_length(X, y) + + n_samples, n_features = X.shape + + if y.ndim > 2: + raise ValueError("Target y has the wrong shape %s" % str(y.shape)) + + if y.ndim == 1: + y = xp.reshape(y, (-1, 1)) + + n_samples_, n_targets = y.shape + + if n_samples != n_samples_: + raise ValueError( + "Number of samples in X and y does not correspond: %d != %d" + % (n_samples, n_samples_) + ) + + if has_sw: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + if solver not in ["sag", "saga"]: + # SAG supports sample_weight directly. For other solvers, + # we implement sample_weight via a simple rescaling. + X, y, sample_weight_sqrt = _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, type(xp.asarray([0.0]))): + 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 = _ravel(xp.asarray(alpha, device=device_, dtype=X.dtype), xp=xp) + if alpha.shape[0] not in [1, n_targets]: + raise ValueError( + "Number of targets and number of penalties do not correspond: %d != %d" + % (alpha.shape[0], n_targets) + ) + + if alpha.shape[0] == 1 and n_targets > 1: + alpha = xp.full( + shape=(n_targets,), fill_value=alpha[0], dtype=alpha.dtype, device=device_ + ) + + n_iter = None + if solver == "sparse_cg": + coef = _solve_sparse_cg( + X, + y, + alpha, + max_iter=max_iter, + tol=tol, + verbose=verbose, + X_offset=X_offset, + X_scale=X_scale, + sample_weight_sqrt=sample_weight_sqrt if has_sw else None, + ) + + elif solver == "lsqr": + 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: + K = safe_sparse_dot(X, X.T, dense_output=True) + try: + dual_coef = _solve_cholesky_kernel(K, y, alpha) + + coef = safe_sparse_dot(X.T, dual_coef, dense_output=True).T + except linalg.LinAlgError: + # use SVD solver if matrix is singular + solver = "svd" + else: + try: + coef = _solve_cholesky(X, y, alpha) + except linalg.LinAlgError: + # use SVD solver if matrix is singular + solver = "svd" + + elif solver in ["sag", "saga"]: + # precompute max_squared_sum for all targets + max_squared_sum = row_norms(X, squared=True).max() + + coef = np.empty((y.shape[1], n_features), dtype=X.dtype) + n_iter = np.empty(y.shape[1], dtype=np.int32) + intercept = np.zeros((y.shape[1],), dtype=X.dtype) + for i, (alpha_i, target) in enumerate(zip(alpha, y.T)): + init = { + "coef": np.zeros((n_features + int(return_intercept), 1), dtype=X.dtype) + } + coef_, n_iter_, _ = sag_solver( + X, + target.ravel(), + sample_weight, + "squared", + alpha_i, + 0, + max_iter, + tol, + verbose, + random_state, + False, + max_squared_sum, + init, + is_saga=solver == "saga", + ) + if return_intercept: + coef[i] = coef_[:-1] + intercept[i] = coef_[-1] + else: + coef[i] = coef_ + n_iter[i] = n_iter_ + + if intercept.shape[0] == 1: + intercept = intercept[0] + + 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, + sample_weight_sqrt=sample_weight_sqrt if has_sw else None, + ) + + if solver == "svd": + if X_is_sparse: + raise TypeError("SVD solver does not support sparse inputs currently") + coef = _solve_svd(X, y, alpha, xp) + + if n_targets == 1: + coef = _ravel(coef) + + coef = xp.asarray(coef) + + if return_n_iter and return_intercept: + res = coef, n_iter, intercept + elif return_intercept: + res = coef, intercept + elif return_n_iter: + res = coef, n_iter + else: + res = coef + + return (*res, solver) if return_solver else res + + +def resolve_solver(solver, positive, return_intercept, is_sparse, xp): + if solver != "auto": + return solver + + is_numpy_namespace = _is_numpy_namespace(xp) + + auto_solver_np = resolve_solver_for_numpy(positive, return_intercept, is_sparse) + if is_numpy_namespace: + return auto_solver_np + + if positive: + raise ValueError( + "The solvers that support positive fitting do not support " + f"Array API dispatch to namespace {xp.__name__}. Please " + "either disable Array API dispatch, or use a numpy-like " + "namespace, or set `positive=False`." + ) + + # At the moment, Array API dispatch only supports the "svd" solver. + solver = "svd" + if solver != auto_solver_np: + warnings.warn( + f"Using Array API dispatch to namespace {xp.__name__} with " + f"`solver='auto'` will result in using the solver '{solver}'. " + "The results may differ from those when using a Numpy array, " + f"because in that case the preferred solver would be {auto_solver_np}. " + f"Set `solver='{solver}'` to suppress this warning." + ) + + return solver + + +def resolve_solver_for_numpy(positive, return_intercept, is_sparse): + if positive: + return "lbfgs" + + if return_intercept: + # sag supports fitting intercept directly + return "sag" + + if not is_sparse: + return "cholesky" + + return "sparse_cg" + + +class _BaseRidge(LinearModel, metaclass=ABCMeta): + _parameter_constraints: dict = { + "alpha": [Interval(Real, 0, None, closed="left"), np.ndarray], + "fit_intercept": ["boolean"], + "copy_X": ["boolean"], + "max_iter": [Interval(Integral, 1, None, closed="left"), None], + "tol": [Interval(Real, 0, None, closed="left")], + "solver": [ + StrOptions( + {"auto", "svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga", "lbfgs"} + ) + ], + "positive": ["boolean"], + "random_state": ["random_state"], + } + + @abstractmethod + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + copy_X=True, + max_iter=None, + tol=1e-4, + solver="auto", + positive=False, + random_state=None, + ): + self.alpha = alpha + self.fit_intercept = fit_intercept + self.copy_X = copy_X + 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): + xp, is_array_api_compliant = get_namespace(X, y, sample_weight) + + 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", "lbfgs", "lsqr", "sag", "sparse_cg"]: + raise ValueError( + "solver='{}' does not support fitting the intercept " + "on sparse data. Please set the solver to 'auto' or " + "'lsqr', 'sparse_cg', 'sag', 'lbfgs' " + "or set `fit_intercept=False`".format(self.solver) + ) + 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 ' + "an intercept with sparse inputs. Either set the " + 'solver to "auto" or "sparse_cg", or set a low ' + '"tol" and a high "max_iter" (especially if inputs are ' + "not standardized)." + ) + solver = "sag" + else: + solver = "sparse_cg" + else: + solver = self.solver + + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + # when X is sparse we only remove offset from y + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, + y, + fit_intercept=self.fit_intercept, + copy=self.copy_X, + sample_weight=sample_weight, + ) + + if solver == "sag" and sparse.issparse(X) and self.fit_intercept: + self.coef_, self.n_iter_, self.intercept_, self.solver_ = _ridge_regression( + X, + y, + alpha=self.alpha, + sample_weight=sample_weight, + 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, + return_solver=True, + check_input=False, + ) + # add the offset which was subtracted by _preprocess_data + self.intercept_ += y_offset + + else: + if sparse.issparse(X) and self.fit_intercept: + # required to fit intercept with sparse_cg and lbfgs solver + params = {"X_offset": X_offset, "X_scale": X_scale} + else: + # for dense matrices or when intercept is set to 0 + params = {} + + self.coef_, self.n_iter_, self.solver_ = _ridge_regression( + X, + y, + alpha=self.alpha, + sample_weight=sample_weight, + 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, + return_solver=True, + check_input=False, + fit_intercept=self.fit_intercept, + **params, + ) + self._set_intercept(X_offset, y_offset, X_scale) + + return self + + +class Ridge(MultiOutputMixin, RegressorMixin, _BaseRidge): + """Linear least squares with l2 regularization. + + Minimizes the objective function:: + + ||y - Xw||^2_2 + alpha * ||w||^2_2 + + This model solves a regression model where the loss function is + the linear least squares function and regularization is given by + the l2-norm. Also known as Ridge Regression or Tikhonov regularization. + This estimator has built-in support for multi-variate regression + (i.e., when y is a 2d-array of shape (n_samples, n_targets)). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : {float, ndarray of shape (n_targets,)}, default=1.0 + Constant that multiplies the L2 term, controlling regularization + strength. `alpha` must be a non-negative float i.e. in `[0, inf)`. + + When `alpha = 0`, the objective is equivalent to ordinary least + squares, solved by the :class:`LinearRegression` object. For numerical + reasons, using `alpha = 0` with the `Ridge` object is not advised. + Instead, you should use the :class:`LinearRegression` object. + + If an array is passed, penalties are assumed to be specific to the + targets. Hence they must correspond in number. + + fit_intercept : bool, default=True + Whether to fit the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. ``X`` and ``y`` are expected to be centered). + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + max_iter : int, default=None + 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-4 + The precision of the solution (`coef_`) is determined by `tol` which + specifies a different convergence criterion for each solver: + + - 'svd': `tol` has no impact. + + - 'cholesky': `tol` has no impact. + + - 'sparse_cg': norm of residuals smaller than `tol`. + + - 'lsqr': `tol` is set as atol and btol of scipy.sparse.linalg.lsqr, + which control the norm of the residual vector in terms of the norms of + matrix and coefficients. + + - 'sag' and 'saga': relative change of coef smaller than `tol`. + + - 'lbfgs': maximum of the absolute (projected) gradient=max|residuals| + smaller than `tol`. + + .. versionchanged:: 1.2 + Default value changed from 1e-3 to 1e-4 for consistency with other linear + models. + + 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. + + - 'svd' uses a Singular Value Decomposition of X to compute the Ridge + coefficients. It is the most stable solver, in particular more stable + for singular matrices than 'cholesky' at the cost of being slower. + + - 'cholesky' uses the standard scipy.linalg.solve function to + obtain a closed-form solution. + + - 'sparse_cg' uses the conjugate gradient solver as found in + scipy.sparse.linalg.cg. As an iterative algorithm, this solver is + more appropriate than 'cholesky' for large-scale data + (possibility to set `tol` and `max_iter`). + + - 'lsqr' uses the dedicated regularized least-squares routine + scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative + procedure. + + - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses + its improved, unbiased version named SAGA. Both methods also use an + iterative procedure, and are often faster than other solvers when + both n_samples and n_features are large. Note that 'sag' and + 'saga' fast convergence is only guaranteed on features with + 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 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. + .. 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 ` for details. + + .. versionadded:: 0.17 + `random_state` to support Stochastic Average Gradient. + + Attributes + ---------- + coef_ : ndarray of shape (n_features,) or (n_targets, n_features) + Weight vector(s). + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + + n_iter_ : None or ndarray of shape (n_targets,) + Actual number of iterations for each target. Available only for + sag and lsqr solvers. Other solvers will return None. + + .. versionadded:: 0.17 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + solver_ : str + The solver that was used at fit time by the computational + routines. + + .. versionadded:: 1.5 + + See Also + -------- + RidgeClassifier : Ridge classifier. + RidgeCV : Ridge regression with built-in cross validation. + :class:`~sklearn.kernel_ridge.KernelRidge` : Kernel ridge regression + combines ridge regression with the kernel trick. + + Notes + ----- + Regularization improves the conditioning of the problem and + reduces the variance of the estimates. Larger values specify stronger + regularization. Alpha corresponds to ``1 / (2C)`` in other linear + models such as :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. + + Examples + -------- + >>> from sklearn.linear_model import Ridge + >>> import numpy as np + >>> n_samples, n_features = 10, 5 + >>> rng = np.random.RandomState(0) + >>> y = rng.randn(n_samples) + >>> X = rng.randn(n_samples, n_features) + >>> clf = Ridge(alpha=1.0) + >>> clf.fit(X, y) + Ridge() + """ + + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + copy_X=True, + max_iter=None, + tol=1e-4, + solver="auto", + positive=False, + random_state=None, + ): + super().__init__( + alpha=alpha, + fit_intercept=fit_intercept, + copy_X=copy_X, + max_iter=max_iter, + tol=tol, + solver=solver, + positive=positive, + random_state=random_state, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit Ridge regression model. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Target values. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + Returns + ------- + self : object + Fitted estimator. + """ + _accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver) + xp, _ = get_namespace(X, y, sample_weight) + X, y = validate_data( + self, + X, + y, + accept_sparse=_accept_sparse, + dtype=[xp.float64, xp.float32], + force_writeable=True, + multi_output=True, + y_numeric=True, + ) + return super().fit(X, y, sample_weight=sample_weight) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.array_api_support = True + tags.input_tags.sparse = (self.solver != "svd") and ( + self.solver != "cholesky" or not self.fit_intercept + ) + return tags + + +class _RidgeClassifierMixin(LinearClassifierMixin): + def _prepare_data(self, X, y, sample_weight, solver): + """Validate `X` and `y` and binarize `y`. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + solver : str + The solver used in `Ridge` to know which sparse format to support. + + Returns + ------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Validated training data. + + y : ndarray of shape (n_samples,) + Validated target values. + + sample_weight : ndarray of shape (n_samples,) + Validated sample weights. + + Y : ndarray of shape (n_samples, n_classes) + The binarized version of `y`. + """ + accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), solver) + X, y = validate_data( + self, + X, + y, + accept_sparse=accept_sparse, + multi_output=True, + y_numeric=False, + force_writeable=True, + ) + + self._label_binarizer = LabelBinarizer(pos_label=1, neg_label=-1) + Y = self._label_binarizer.fit_transform(y) + if not self._label_binarizer.y_type_.startswith("multilabel"): + y = column_or_1d(y, warn=True) + + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + if self.class_weight: + sample_weight = sample_weight * compute_sample_weight(self.class_weight, y) + return X, y, sample_weight, Y + + def predict(self, X): + """Predict class labels for samples in `X`. + + Parameters + ---------- + X : {array-like, spare matrix} of shape (n_samples, n_features) + The data matrix for which we want to predict the targets. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) or (n_samples, n_outputs) + Vector or matrix containing the predictions. In binary and + multiclass problems, this is a vector containing `n_samples`. In + a multilabel problem, it returns a matrix of shape + `(n_samples, n_outputs)`. + """ + check_is_fitted(self, attributes=["_label_binarizer"]) + if self._label_binarizer.y_type_.startswith("multilabel"): + # Threshold such that the negative label is -1 and positive label + # is 1 to use the inverse transform of the label binarizer fitted + # during fit. + scores = 2 * (self.decision_function(X) > 0) - 1 + return self._label_binarizer.inverse_transform(scores) + return super().predict(X) + + @property + def classes_(self): + """Classes labels.""" + return self._label_binarizer.classes_ + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_label = True + return tags + + +class RidgeClassifier(_RidgeClassifierMixin, _BaseRidge): + """Classifier using Ridge regression. + + This classifier first converts the target values into ``{-1, 1}`` and + then treats the problem as a regression task (multi-output regression in + the multiclass case). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alpha : float, default=1.0 + Regularization strength; must be a positive float. Regularization + improves the conditioning of the problem and reduces the variance of + the estimates. Larger values specify stronger regularization. + Alpha corresponds to ``1 / (2C)`` in other linear models such as + :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set to false, no + intercept will be used in calculations (e.g. data is expected to be + already centered). + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + max_iter : int, default=None + Maximum number of iterations for conjugate gradient solver. + The default value is determined by scipy.sparse.linalg. + + tol : float, default=1e-4 + The precision of the solution (`coef_`) is determined by `tol` which + specifies a different convergence criterion for each solver: + + - 'svd': `tol` has no impact. + + - 'cholesky': `tol` has no impact. + + - 'sparse_cg': norm of residuals smaller than `tol`. + + - 'lsqr': `tol` is set as atol and btol of scipy.sparse.linalg.lsqr, + which control the norm of the residual vector in terms of the norms of + matrix and coefficients. + + - 'sag' and 'saga': relative change of coef smaller than `tol`. + + - 'lbfgs': maximum of the absolute (projected) gradient=max|residuals| + smaller than `tol`. + + .. versionchanged:: 1.2 + Default value changed from 1e-3 to 1e-4 for consistency with other linear + models. + + class_weight : dict or 'balanced', default=None + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + 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. + + - 'svd' uses a Singular Value Decomposition of X to compute the Ridge + coefficients. It is the most stable solver, in particular more stable + for singular matrices than 'cholesky' at the cost of being slower. + + - 'cholesky' uses the standard scipy.linalg.solve function to + obtain a closed-form solution. + + - 'sparse_cg' uses the conjugate gradient solver as found in + scipy.sparse.linalg.cg. As an iterative algorithm, this solver is + more appropriate than 'cholesky' for large-scale data + (possibility to set `tol` and `max_iter`). + + - 'lsqr' uses the dedicated regularized least-squares routine + scipy.sparse.linalg.lsqr. It is the fastest and uses an iterative + procedure. + + - 'sag' uses a Stochastic Average Gradient descent, and 'saga' uses + its unbiased and more flexible version named SAGA. Both methods + use an iterative procedure, and are often faster than other solvers + when both n_samples and n_features are large. Note that 'sag' and + 'saga' fast convergence is only guaranteed on features with + approximately the same scale. You can preprocess the data with a + scaler from sklearn.preprocessing. + + .. versionadded:: 0.17 + Stochastic Average Gradient descent solver. + .. 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 ` for details. + + Attributes + ---------- + coef_ : ndarray of shape (1, n_features) or (n_classes, n_features) + Coefficient of the features in the decision function. + + ``coef_`` is of shape (1, n_features) when the given problem is binary. + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + + n_iter_ : None or ndarray of shape (n_targets,) + Actual number of iterations for each target. Available only for + sag and lsqr solvers. Other solvers will return None. + + classes_ : ndarray of shape (n_classes,) + The classes labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + solver_ : str + The solver that was used at fit time by the computational + routines. + + .. versionadded:: 1.5 + + See Also + -------- + Ridge : Ridge regression. + RidgeClassifierCV : Ridge classifier with built-in cross validation. + + Notes + ----- + For multi-class classification, n_class classifiers are trained in + a one-versus-all approach. Concretely, this is implemented by taking + advantage of the multi-variate response support in Ridge. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.linear_model import RidgeClassifier + >>> X, y = load_breast_cancer(return_X_y=True) + >>> clf = RidgeClassifier().fit(X, y) + >>> clf.score(X, y) + 0.9595... + """ + + _parameter_constraints: dict = { + **_BaseRidge._parameter_constraints, + "class_weight": [dict, StrOptions({"balanced"}), None], + } + + def __init__( + self, + alpha=1.0, + *, + fit_intercept=True, + copy_X=True, + max_iter=None, + tol=1e-4, + class_weight=None, + solver="auto", + positive=False, + random_state=None, + ): + super().__init__( + alpha=alpha, + fit_intercept=fit_intercept, + copy_X=copy_X, + max_iter=max_iter, + tol=tol, + solver=solver, + positive=positive, + random_state=random_state, + ) + self.class_weight = class_weight + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit Ridge classifier model. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + .. versionadded:: 0.17 + *sample_weight* support to RidgeClassifier. + + Returns + ------- + self : object + Instance of the estimator. + """ + X, y, sample_weight, Y = self._prepare_data(X, y, sample_weight, self.solver) + + super().fit(X, Y, sample_weight=sample_weight) + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = (self.solver != "svd") and ( + self.solver != "cholesky" or not self.fit_intercept + ) + return tags + + +def _check_gcv_mode(X, gcv_mode): + if gcv_mode in ["eigen", "svd"]: + return gcv_mode + # if X has more rows than columns, use decomposition of X^T.X, + # otherwise X.X^T + if X.shape[0] > X.shape[1]: + return "svd" + return "eigen" + + +def _find_smallest_angle(query, vectors): + """Find the column of vectors that is most aligned with the query. + + Both query and the columns of vectors must have their l2 norm equal to 1. + + Parameters + ---------- + query : ndarray of shape (n_samples,) + Normalized query vector. + + vectors : ndarray of shape (n_samples, n_features) + Vectors to which we compare query, as columns. Must be normalized. + """ + abs_cosine = np.abs(query.dot(vectors)) + index = np.argmax(abs_cosine) + return index + + +class _X_CenterStackOp(sparse.linalg.LinearOperator): + """Behaves as centered and scaled X with an added intercept column. + + This operator behaves as + np.hstack([X - sqrt_sw[:, None] * X_mean, sqrt_sw[:, None]]) + """ + + def __init__(self, X, X_mean, sqrt_sw): + n_samples, n_features = X.shape + super().__init__(X.dtype, (n_samples, n_features + 1)) + self.X = X + self.X_mean = X_mean + self.sqrt_sw = sqrt_sw + + def _matvec(self, v): + v = v.ravel() + return ( + safe_sparse_dot(self.X, v[:-1], dense_output=True) + - self.sqrt_sw * self.X_mean.dot(v[:-1]) + + v[-1] * self.sqrt_sw + ) + + def _matmat(self, v): + return ( + safe_sparse_dot(self.X, v[:-1], dense_output=True) + - self.sqrt_sw[:, None] * self.X_mean.dot(v[:-1]) + + v[-1] * self.sqrt_sw[:, None] + ) + + def _transpose(self): + return _XT_CenterStackOp(self.X, self.X_mean, self.sqrt_sw) + + +class _XT_CenterStackOp(sparse.linalg.LinearOperator): + """Behaves as transposed centered and scaled X with an intercept column. + + This operator behaves as + np.hstack([X - sqrt_sw[:, None] * X_mean, sqrt_sw[:, None]]).T + """ + + def __init__(self, X, X_mean, sqrt_sw): + n_samples, n_features = X.shape + super().__init__(X.dtype, (n_features + 1, n_samples)) + self.X = X + self.X_mean = X_mean + self.sqrt_sw = sqrt_sw + + def _matvec(self, v): + v = v.ravel() + n_features = self.shape[0] + res = np.empty(n_features, dtype=self.X.dtype) + res[:-1] = safe_sparse_dot(self.X.T, v, dense_output=True) - ( + self.X_mean * self.sqrt_sw.dot(v) + ) + res[-1] = np.dot(v, self.sqrt_sw) + return res + + def _matmat(self, v): + n_features = self.shape[0] + res = np.empty((n_features, v.shape[1]), dtype=self.X.dtype) + res[:-1] = safe_sparse_dot(self.X.T, v, dense_output=True) - self.X_mean[ + :, None + ] * self.sqrt_sw.dot(v) + res[-1] = np.dot(self.sqrt_sw, v) + return res + + +class _IdentityRegressor(RegressorMixin, BaseEstimator): + """Fake regressor which will directly output the prediction.""" + + def decision_function(self, y_predict): + return y_predict + + def predict(self, y_predict): + return y_predict + + +class _IdentityClassifier(LinearClassifierMixin, BaseEstimator): + """Fake classifier which will directly output the prediction. + + We inherit from LinearClassifierMixin to get the proper shape for the + output `y`. + """ + + def __init__(self, classes): + self.classes_ = classes + + def decision_function(self, y_predict): + return y_predict + + +class _RidgeGCV(LinearModel): + """Ridge regression with built-in Leave-one-out Cross-Validation. + + This class is not intended to be used directly. Use RidgeCV instead. + + `_RidgeGCV` uses a Generalized Cross-Validation for model selection. It's an + efficient approximation of leave-one-out cross-validation (LOO-CV), where instead of + computing multiple models by excluding one data point at a time, it uses an + algebraic shortcut to approximate the LOO-CV error, making it faster and + computationally more efficient. + + Using a naive grid-search approach with a leave-one-out cross-validation in contrast + requires to fit `n_samples` models to compute the prediction error for each sample + and then to repeat this process for each alpha in the grid. + + Here, the prediction error for each sample is computed by solving a **single** + linear system (in other words a single model) via a matrix factorization (i.e. + eigendecomposition or SVD) solving the problem stated in the Notes section. Finally, + we need to repeat this process for each alpha in the grid. The detailed complexity + is further discussed in Sect. 4 in [1]. + + This algebraic approach is only applicable for regularized least squares + problems. It could potentially be extended to kernel ridge regression. + + See the Notes section and references for more details regarding the formulation + and the linear system that is solved. + + Notes + ----- + + We want to solve (K + alpha*Id)c = y, + where K = X X^T is the kernel matrix. + + Let G = (K + alpha*Id). + + Dual solution: c = G^-1y + Primal solution: w = X^T c + + Compute eigendecomposition K = Q V Q^T. + Then G^-1 = Q (V + alpha*Id)^-1 Q^T, + where (V + alpha*Id) is diagonal. + It is thus inexpensive to inverse for many alphas. + + Let loov be the vector of prediction values for each example + when the model was fitted with all examples but this example. + + loov = (KG^-1Y - diag(KG^-1)Y) / diag(I-KG^-1) + + Let looe be the vector of prediction errors for each example + when the model was fitted with all examples but this example. + + looe = y - loov = c / diag(G^-1) + + The best score (negative mean squared error or user-provided scoring) is + stored in the `best_score_` attribute, and the selected hyperparameter in + `alpha_`. + + References + ---------- + [1] http://cbcl.mit.edu/publications/ps/MIT-CSAIL-TR-2007-025.pdf + [2] https://www.mit.edu/~9.520/spring07/Classes/rlsslides.pdf + """ + + def __init__( + self, + alphas=(0.1, 1.0, 10.0), + *, + fit_intercept=True, + scoring=None, + copy_X=True, + gcv_mode=None, + store_cv_results=False, + is_clf=False, + alpha_per_target=False, + ): + self.alphas = alphas + self.fit_intercept = fit_intercept + self.scoring = scoring + self.copy_X = copy_X + self.gcv_mode = gcv_mode + self.store_cv_results = store_cv_results + self.is_clf = is_clf + self.alpha_per_target = alpha_per_target + + @staticmethod + def _decomp_diag(v_prime, Q): + # compute diagonal of the matrix: dot(Q, dot(diag(v_prime), Q^T)) + return (v_prime * Q**2).sum(axis=-1) + + @staticmethod + def _diag_dot(D, B): + # compute dot(diag(D), B) + if len(B.shape) > 1: + # handle case where B is > 1-d + D = D[(slice(None),) + (np.newaxis,) * (len(B.shape) - 1)] + return D * B + + def _compute_gram(self, X, sqrt_sw): + """Computes the Gram matrix XX^T with possible centering. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + The preprocessed design matrix. + + sqrt_sw : ndarray of shape (n_samples,) + square roots of sample weights + + Returns + ------- + gram : ndarray of shape (n_samples, n_samples) + The Gram matrix. + X_mean : ndarray of shape (n_feature,) + The weighted mean of ``X`` for each feature. + + Notes + ----- + When X is dense the centering has been done in preprocessing + so the mean is 0 and we just compute XX^T. + + When X is sparse it has not been centered in preprocessing, but it has + been scaled by sqrt(sample weights). + + When self.fit_intercept is False no centering is done. + + The centered X is never actually computed because centering would break + the sparsity of X. + """ + center = self.fit_intercept and sparse.issparse(X) + if not center: + # in this case centering has been done in preprocessing + # or we are not fitting an intercept. + X_mean = np.zeros(X.shape[1], dtype=X.dtype) + return safe_sparse_dot(X, X.T, dense_output=True), X_mean + # X is sparse + n_samples = X.shape[0] + sample_weight_matrix = sparse.dia_matrix( + (sqrt_sw, 0), shape=(n_samples, n_samples) + ) + X_weighted = sample_weight_matrix.dot(X) + X_mean, _ = mean_variance_axis(X_weighted, axis=0) + X_mean *= n_samples / sqrt_sw.dot(sqrt_sw) + X_mX = sqrt_sw[:, None] * safe_sparse_dot(X_mean, X.T, dense_output=True) + X_mX_m = np.outer(sqrt_sw, sqrt_sw) * np.dot(X_mean, X_mean) + return ( + safe_sparse_dot(X, X.T, dense_output=True) + X_mX_m - X_mX - X_mX.T, + X_mean, + ) + + def _compute_covariance(self, X, sqrt_sw): + """Computes covariance matrix X^TX with possible centering. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + The preprocessed design matrix. + + sqrt_sw : ndarray of shape (n_samples,) + square roots of sample weights + + Returns + ------- + covariance : ndarray of shape (n_features, n_features) + The covariance matrix. + X_mean : ndarray of shape (n_feature,) + The weighted mean of ``X`` for each feature. + + Notes + ----- + Since X is sparse it has not been centered in preprocessing, but it has + been scaled by sqrt(sample weights). + + When self.fit_intercept is False no centering is done. + + The centered X is never actually computed because centering would break + the sparsity of X. + """ + if not self.fit_intercept: + # in this case centering has been done in preprocessing + # or we are not fitting an intercept. + X_mean = np.zeros(X.shape[1], dtype=X.dtype) + return safe_sparse_dot(X.T, X, dense_output=True), X_mean + # this function only gets called for sparse X + n_samples = X.shape[0] + sample_weight_matrix = sparse.dia_matrix( + (sqrt_sw, 0), shape=(n_samples, n_samples) + ) + X_weighted = sample_weight_matrix.dot(X) + X_mean, _ = mean_variance_axis(X_weighted, axis=0) + X_mean = X_mean * n_samples / sqrt_sw.dot(sqrt_sw) + weight_sum = sqrt_sw.dot(sqrt_sw) + return ( + safe_sparse_dot(X.T, X, dense_output=True) + - weight_sum * np.outer(X_mean, X_mean), + X_mean, + ) + + def _sparse_multidot_diag(self, X, A, X_mean, sqrt_sw): + """Compute the diagonal of (X - X_mean).dot(A).dot((X - X_mean).T) + without explicitly centering X nor computing X.dot(A) + when X is sparse. + + Parameters + ---------- + X : sparse matrix of shape (n_samples, n_features) + + A : ndarray of shape (n_features, n_features) + + X_mean : ndarray of shape (n_features,) + + sqrt_sw : ndarray of shape (n_features,) + square roots of sample weights + + Returns + ------- + diag : np.ndarray, shape (n_samples,) + The computed diagonal. + """ + intercept_col = scale = sqrt_sw + batch_size = X.shape[1] + diag = np.empty(X.shape[0], dtype=X.dtype) + for start in range(0, X.shape[0], batch_size): + batch = slice(start, min(X.shape[0], start + batch_size), 1) + X_batch = np.empty( + (X[batch].shape[0], X.shape[1] + self.fit_intercept), dtype=X.dtype + ) + if self.fit_intercept: + X_batch[:, :-1] = X[batch].toarray() - X_mean * scale[batch][:, None] + X_batch[:, -1] = intercept_col[batch] + else: + X_batch = X[batch].toarray() + diag[batch] = (X_batch.dot(A) * X_batch).sum(axis=1) + return diag + + def _eigen_decompose_gram(self, X, y, sqrt_sw): + """Eigendecomposition of X.X^T, used when n_samples <= n_features.""" + # if X is dense it has already been centered in preprocessing + K, X_mean = self._compute_gram(X, sqrt_sw) + if self.fit_intercept: + # to emulate centering X with sample weights, + # ie removing the weighted average, we add a column + # containing the square roots of the sample weights. + # by centering, it is orthogonal to the other columns + K += np.outer(sqrt_sw, sqrt_sw) + eigvals, Q = linalg.eigh(K) + QT_y = np.dot(Q.T, y) + return X_mean, eigvals, Q, QT_y + + def _solve_eigen_gram(self, alpha, y, sqrt_sw, X_mean, eigvals, Q, QT_y): + """Compute dual coefficients and diagonal of G^-1. + + Used when we have a decomposition of X.X^T (n_samples <= n_features). + """ + w = 1.0 / (eigvals + alpha) + if self.fit_intercept: + # the vector containing the square roots of the sample weights (1 + # when no sample weights) is the eigenvector of XX^T which + # corresponds to the intercept; we cancel the regularization on + # this dimension. the corresponding eigenvalue is + # sum(sample_weight). + normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) + intercept_dim = _find_smallest_angle(normalized_sw, Q) + w[intercept_dim] = 0 # cancel regularization for the intercept + + c = np.dot(Q, self._diag_dot(w, QT_y)) + G_inverse_diag = self._decomp_diag(w, Q) + # handle case where y is 2-d + if len(y.shape) != 1: + G_inverse_diag = G_inverse_diag[:, np.newaxis] + return G_inverse_diag, c + + def _eigen_decompose_covariance(self, X, y, sqrt_sw): + """Eigendecomposition of X^T.X, used when n_samples > n_features + and X is sparse. + """ + n_samples, n_features = X.shape + cov = np.empty((n_features + 1, n_features + 1), dtype=X.dtype) + cov[:-1, :-1], X_mean = self._compute_covariance(X, sqrt_sw) + if not self.fit_intercept: + cov = cov[:-1, :-1] + # to emulate centering X with sample weights, + # ie removing the weighted average, we add a column + # containing the square roots of the sample weights. + # by centering, it is orthogonal to the other columns + # when all samples have the same weight we add a column of 1 + else: + cov[-1] = 0 + cov[:, -1] = 0 + cov[-1, -1] = sqrt_sw.dot(sqrt_sw) + nullspace_dim = max(0, n_features - n_samples) + eigvals, V = linalg.eigh(cov) + # remove eigenvalues and vectors in the null space of X^T.X + eigvals = eigvals[nullspace_dim:] + V = V[:, nullspace_dim:] + return X_mean, eigvals, V, X + + def _solve_eigen_covariance_no_intercept( + self, alpha, y, sqrt_sw, X_mean, eigvals, V, X + ): + """Compute dual coefficients and diagonal of G^-1. + + Used when we have a decomposition of X^T.X + (n_samples > n_features and X is sparse), and not fitting an intercept. + """ + w = 1 / (eigvals + alpha) + A = (V * w).dot(V.T) + AXy = A.dot(safe_sparse_dot(X.T, y, dense_output=True)) + y_hat = safe_sparse_dot(X, AXy, dense_output=True) + hat_diag = self._sparse_multidot_diag(X, A, X_mean, sqrt_sw) + if len(y.shape) != 1: + # handle case where y is 2-d + hat_diag = hat_diag[:, np.newaxis] + return (1 - hat_diag) / alpha, (y - y_hat) / alpha + + def _solve_eigen_covariance_intercept( + self, alpha, y, sqrt_sw, X_mean, eigvals, V, X + ): + """Compute dual coefficients and diagonal of G^-1. + + Used when we have a decomposition of X^T.X + (n_samples > n_features and X is sparse), + and we are fitting an intercept. + """ + # the vector [0, 0, ..., 0, 1] + # is the eigenvector of X^TX which + # corresponds to the intercept; we cancel the regularization on + # this dimension. the corresponding eigenvalue is + # sum(sample_weight), e.g. n when uniform sample weights. + intercept_sv = np.zeros(V.shape[0]) + intercept_sv[-1] = 1 + intercept_dim = _find_smallest_angle(intercept_sv, V) + w = 1 / (eigvals + alpha) + w[intercept_dim] = 1 / eigvals[intercept_dim] + A = (V * w).dot(V.T) + # add a column to X containing the square roots of sample weights + X_op = _X_CenterStackOp(X, X_mean, sqrt_sw) + AXy = A.dot(X_op.T.dot(y)) + y_hat = X_op.dot(AXy) + hat_diag = self._sparse_multidot_diag(X, A, X_mean, sqrt_sw) + # return (1 - hat_diag), (y - y_hat) + if len(y.shape) != 1: + # handle case where y is 2-d + hat_diag = hat_diag[:, np.newaxis] + return (1 - hat_diag) / alpha, (y - y_hat) / alpha + + def _solve_eigen_covariance(self, alpha, y, sqrt_sw, X_mean, eigvals, V, X): + """Compute dual coefficients and diagonal of G^-1. + + Used when we have a decomposition of X^T.X + (n_samples > n_features and X is sparse). + """ + if self.fit_intercept: + return self._solve_eigen_covariance_intercept( + alpha, y, sqrt_sw, X_mean, eigvals, V, X + ) + return self._solve_eigen_covariance_no_intercept( + alpha, y, sqrt_sw, X_mean, eigvals, V, X + ) + + def _svd_decompose_design_matrix(self, X, y, sqrt_sw): + # X already centered + X_mean = np.zeros(X.shape[1], dtype=X.dtype) + if self.fit_intercept: + # to emulate fit_intercept=True situation, add a column + # containing the square roots of the sample weights + # by centering, the other columns are orthogonal to that one + intercept_column = sqrt_sw[:, None] + X = np.hstack((X, intercept_column)) + U, singvals, _ = linalg.svd(X, full_matrices=0) + singvals_sq = singvals**2 + UT_y = np.dot(U.T, y) + return X_mean, singvals_sq, U, UT_y + + def _solve_svd_design_matrix(self, alpha, y, sqrt_sw, X_mean, singvals_sq, U, UT_y): + """Compute dual coefficients and diagonal of G^-1. + + Used when we have an SVD decomposition of X + (n_samples > n_features and X is dense). + """ + w = ((singvals_sq + alpha) ** -1) - (alpha**-1) + if self.fit_intercept: + # detect intercept column + normalized_sw = sqrt_sw / np.linalg.norm(sqrt_sw) + intercept_dim = _find_smallest_angle(normalized_sw, U) + # cancel the regularization for the intercept + w[intercept_dim] = -(alpha**-1) + c = np.dot(U, self._diag_dot(w, UT_y)) + (alpha**-1) * y + G_inverse_diag = self._decomp_diag(w, U) + (alpha**-1) + if len(y.shape) != 1: + # handle case where y is 2-d + G_inverse_diag = G_inverse_diag[:, np.newaxis] + return G_inverse_diag, c + + def fit(self, X, y, sample_weight=None, score_params=None): + """Fit Ridge regression model with gcv. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples, n_features) + Training data. Will be cast to float64 if necessary. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Target values. Will be cast to float64 if necessary. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. Note that the scale of `sample_weight` + has an impact on the loss; i.e. multiplying all weights by `k` + is equivalent to setting `alpha / k`. + + score_params : dict, default=None + Parameters to be passed to the underlying scorer. + + .. versionadded:: 1.5 + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + """ + X, y = validate_data( + self, + X, + y, + accept_sparse=["csr", "csc", "coo"], + 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) + + self.alphas = np.asarray(self.alphas) + + unscaled_y = y + X, y, X_offset, y_offset, X_scale = _preprocess_data( + X, + y, + fit_intercept=self.fit_intercept, + copy=self.copy_X, + sample_weight=sample_weight, + ) + + gcv_mode = _check_gcv_mode(X, self.gcv_mode) + + if gcv_mode == "eigen": + decompose = self._eigen_decompose_gram + solve = self._solve_eigen_gram + elif gcv_mode == "svd": + if sparse.issparse(X): + decompose = self._eigen_decompose_covariance + solve = self._solve_eigen_covariance + else: + decompose = self._svd_decompose_design_matrix + solve = self._solve_svd_design_matrix + + n_samples = X.shape[0] + + if sample_weight is not None: + X, y, sqrt_sw = _rescale_data(X, y, sample_weight) + else: + sqrt_sw = np.ones(n_samples, dtype=X.dtype) + + X_mean, *decomposition = decompose(X, y, sqrt_sw) + + 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_results: + self.cv_results_ = np.empty((n_samples * n_y, n_alphas), dtype=X.dtype) + + best_coef, best_score, best_alpha = None, None, None + + for i, alpha in enumerate(np.atleast_1d(self.alphas)): + G_inverse_diag, c = solve(float(alpha), y, sqrt_sw, X_mean, *decomposition) + if self.scoring is None: + squared_errors = (c / G_inverse_diag) ** 2 + alpha_score = self._score_without_scorer(squared_errors=squared_errors) + if self.store_cv_results: + self.cv_results_[:, i] = squared_errors.ravel() + else: + predictions = y - (c / G_inverse_diag) + # Rescale predictions back to original scale + if sample_weight is not None: # avoid the unnecessary division by ones + if predictions.ndim > 1: + predictions /= sqrt_sw[:, None] + else: + predictions /= sqrt_sw + predictions += y_offset + + if self.store_cv_results: + self.cv_results_[:, i] = predictions.ravel() + + score_params = score_params or {} + alpha_score = self._score( + predictions=predictions, + y=unscaled_y, + n_y=n_y, + scorer=self.scoring, + score_params=score_params, + ) + + # 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 + self.dual_coef_ = best_coef + self.coef_ = safe_sparse_dot(self.dual_coef_.T, X) + if y.ndim == 1 or y.shape[1] == 1: + self.coef_ = self.coef_.ravel() + + 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_results: + if len(y.shape) == 1: + cv_results_shape = n_samples, n_alphas + else: + cv_results_shape = n_samples, n_y, n_alphas + self.cv_results_ = self.cv_results_.reshape(cv_results_shape) + + return self + + def _score_without_scorer(self, squared_errors): + """Performs scoring using squared errors when the scorer is None.""" + if self.alpha_per_target: + _score = -squared_errors.mean(axis=0) + else: + _score = -squared_errors.mean() + + return _score + + def _score(self, *, predictions, y, n_y, scorer, score_params): + """Performs scoring with the specified scorer using the + predictions and the true y values. + """ + if self.is_clf: + identity_estimator = _IdentityClassifier(classes=np.arange(n_y)) + _score = scorer( + identity_estimator, + predictions, + y.argmax(axis=1), + **score_params, + ) + else: + identity_estimator = _IdentityRegressor() + if self.alpha_per_target: + _score = np.array( + [ + scorer( + identity_estimator, + predictions[:, j], + y[:, j], + **score_params, + ) + for j in range(n_y) + ] + ) + else: + _score = scorer(identity_estimator, predictions, y, **score_params) + + return _score + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + # Required since this is neither a RegressorMixin nor a ClassifierMixin + tags.target_tags.required = True + return tags + + +class _BaseRidgeCV(LinearModel): + _parameter_constraints: dict = { + "alphas": ["array-like", Interval(Real, 0, None, closed="neither")], + "fit_intercept": ["boolean"], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "cv": ["cv_object"], + "gcv_mode": [StrOptions({"auto", "svd", "eigen"}), None], + "store_cv_results": ["boolean"], + "alpha_per_target": ["boolean"], + } + + def __init__( + self, + alphas=(0.1, 1.0, 10.0), + *, + fit_intercept=True, + scoring=None, + cv=None, + gcv_mode=None, + store_cv_results=False, + alpha_per_target=False, + ): + self.alphas = alphas + self.fit_intercept = fit_intercept + self.scoring = scoring + self.cv = cv + self.gcv_mode = gcv_mode + self.store_cv_results = store_cv_results + self.alpha_per_target = alpha_per_target + + def fit(self, X, y, sample_weight=None, **params): + """Fit Ridge regression model with cv. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. If using GCV, will be cast to float64 + if necessary. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Target values. Will be cast to X's dtype if necessary. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + **params : dict, default=None + Extra parameters for the underlying scorer. + + .. versionadded:: 1.5 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Fitted estimator. + + Notes + ----- + When sample_weight is provided, the selected hyperparameter may depend + on whether we use leave-one-out cross-validation (cv=None) + or another form of cross-validation, because only leave-one-out + cross-validation takes the sample weights into account when computing + the validation score. + """ + _raise_for_params(params, self, "fit") + cv = self.cv + scorer = self._get_scorer() + + # `_RidgeGCV` does not work for alpha = 0 + if cv is None: + check_scalar_alpha = partial( + check_scalar, + target_type=numbers.Real, + min_val=0.0, + include_boundaries="neither", + ) + else: + check_scalar_alpha = partial( + check_scalar, + target_type=numbers.Real, + min_val=0.0, + include_boundaries="left", + ) + + 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") + alphas = np.asarray(self.alphas) + + if sample_weight is not None: + params["sample_weight"] = sample_weight + + if cv is None: + if _routing_enabled(): + routed_params = process_routing( + self, + "fit", + **params, + ) + else: + routed_params = Bunch(scorer=Bunch(score={})) + if sample_weight is not None: + routed_params.scorer.score["sample_weight"] = sample_weight + + # reset `scorer` variable to original user-intend if no scoring is passed + if self.scoring is None: + scorer = None + + estimator = _RidgeGCV( + alphas, + fit_intercept=self.fit_intercept, + scoring=scorer, + gcv_mode=self.gcv_mode, + store_cv_results=self.store_cv_results, + is_clf=is_classifier(self), + alpha_per_target=self.alpha_per_target, + ) + estimator.fit( + X, + y, + sample_weight=sample_weight, + score_params=routed_params.scorer.score, + ) + self.alpha_ = estimator.alpha_ + self.best_score_ = estimator.best_score_ + if self.store_cv_results: + self.cv_results_ = estimator.cv_results_ + else: + if self.store_cv_results: + raise ValueError("cv!=None and store_cv_results=True are incompatible") + if self.alpha_per_target: + raise ValueError("cv!=None and alpha_per_target=True are incompatible") + + parameters = {"alpha": alphas} + solver = "sparse_cg" if sparse.issparse(X) else "auto" + model = RidgeClassifier if is_classifier(self) else Ridge + estimator = model( + fit_intercept=self.fit_intercept, + solver=solver, + ) + if _routing_enabled(): + estimator.set_fit_request(sample_weight=True) + + grid_search = GridSearchCV( + estimator, + parameters, + cv=cv, + scoring=scorer, + ) + + grid_search.fit(X, y, **params) + estimator = grid_search.best_estimator_ + self.alpha_ = grid_search.best_estimator_.alpha + self.best_score_ = grid_search.best_score_ + + self.coef_ = estimator.coef_ + self.intercept_ = estimator.intercept_ + self.n_features_in_ = estimator.n_features_in_ + if hasattr(estimator, "feature_names_in_"): + self.feature_names_in_ = estimator.feature_names_in_ + + return self + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.5 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = ( + MetadataRouter(owner=self.__class__.__name__) + .add_self_request(self) + .add( + scorer=self.scoring, + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + .add( + splitter=self.cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + ) + return router + + def _get_scorer(self): + scorer = check_scoring(estimator=self, scoring=self.scoring, allow_none=True) + if _routing_enabled() and self.scoring is None: + # This estimator passes an array of 1s as sample_weight even if + # sample_weight is not provided by the user. Therefore we need to + # always request it. But we don't set it if it's passed explicitly + # by the user. + scorer.set_score_request(sample_weight=True) + return scorer + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class RidgeCV(MultiOutputMixin, RegressorMixin, _BaseRidgeCV): + """Ridge regression with built-in cross-validation. + + See glossary entry for :term:`cross-validation estimator`. + + By default, it performs efficient Leave-One-Out Cross-Validation. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alphas : array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) + Array of alpha values to try. + Regularization strength; must be a positive float. Regularization + improves the conditioning of the problem and reduces the variance of + the estimates. Larger values specify stronger regularization. + Alpha corresponds to ``1 / (2C)`` in other linear models such as + :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. + If using Leave-One-Out cross-validation, alphas must be strictly positive. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + scoring : str, callable, default=None + The scoring method to use for cross-validation. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: negative :ref:`mean squared error ` if cv is + None (i.e. when using leave-one-out cross-validation), or + :ref:`coefficient of determination ` (:math:`R^2`) otherwise. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the efficient Leave-One-Out cross-validation + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if ``y`` is binary or multiclass, + :class:`~sklearn.model_selection.StratifiedKFold` is used, else, + :class:`~sklearn.model_selection.KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + gcv_mode : {'auto', 'svd', 'eigen'}, default='auto' + Flag indicating which strategy to use when performing + Leave-One-Out Cross-Validation. Options are:: + + 'auto' : use 'svd' if n_samples > n_features, otherwise use 'eigen' + 'svd' : force use of singular value decomposition of X when X is + dense, eigenvalue decomposition of X^T.X when X is sparse. + 'eigen' : force computation via eigendecomposition of X.X^T + + The 'auto' mode is the default and is intended to pick the cheaper + option of the two depending on the shape of the training data. + + store_cv_results : bool, default=False + Flag indicating if the cross-validation values corresponding to + each alpha should be stored in the ``cv_results_`` attribute (see + below). This flag is only compatible with ``cv=None`` (i.e. using + Leave-One-Out Cross-Validation). + + .. versionchanged:: 1.5 + Parameter name changed from `store_cv_values` to `store_cv_results`. + + 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. + + .. versionadded:: 0.24 + + Attributes + ---------- + cv_results_ : 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_results=True`` and ``cv=None``). After ``fit()`` has been + called, this attribute will contain the mean squared errors if + `scoring is None` otherwise it will contain standardized per point + prediction values. + + .. versionchanged:: 1.5 + `cv_values_` changed to `cv_results_`. + + coef_ : ndarray of shape (n_features) or (n_targets, n_features) + Weight vector(s). + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + + 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 or ndarray of shape (n_targets,) + Score of base estimator with best alpha, or, if + ``alpha_per_target=True``, a score for each target. + + .. versionadded:: 0.23 + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + Ridge : Ridge regression. + RidgeClassifier : Classifier based on ridge regression on {-1, 1} labels. + RidgeClassifierCV : Ridge classifier with built-in cross validation. + + Examples + -------- + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import RidgeCV + >>> X, y = load_diabetes(return_X_y=True) + >>> clf = RidgeCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y) + >>> clf.score(X, y) + 0.5166... + """ + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None, **params): + """Fit Ridge regression model with cv. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. If using GCV, will be cast to float64 + if necessary. + + y : ndarray of shape (n_samples,) or (n_samples, n_targets) + Target values. Will be cast to X's dtype if necessary. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + **params : dict, default=None + Parameters to be passed to the underlying scorer. + + .. versionadded:: 1.5 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Fitted estimator. + + Notes + ----- + When sample_weight is provided, the selected hyperparameter may depend + on whether we use leave-one-out cross-validation (cv=None) + or another form of cross-validation, because only leave-one-out + cross-validation takes the sample weights into account when computing + the validation score. + """ + super().fit(X, y, sample_weight=sample_weight, **params) + return self + + +class RidgeClassifierCV(_RidgeClassifierMixin, _BaseRidgeCV): + """Ridge classifier with built-in cross-validation. + + See glossary entry for :term:`cross-validation estimator`. + + By default, it performs Leave-One-Out Cross-Validation. Currently, + only the n_features > n_samples case is handled efficiently. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + alphas : array-like of shape (n_alphas,), default=(0.1, 1.0, 10.0) + Array of alpha values to try. + Regularization strength; must be a positive float. Regularization + improves the conditioning of the problem and reduces the variance of + the estimates. Larger values specify stronger regularization. + Alpha corresponds to ``1 / (2C)`` in other linear models such as + :class:`~sklearn.linear_model.LogisticRegression` or + :class:`~sklearn.svm.LinearSVC`. + If using Leave-One-Out cross-validation, alphas must be strictly positive. + + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations + (i.e. data is expected to be centered). + + scoring : str, callable, default=None + The scoring method to use for cross-validation. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: negative :ref:`mean squared error ` if cv is + None (i.e. when using leave-one-out cross-validation), or + :ref:`accuracy ` otherwise. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the efficient Leave-One-Out cross-validation + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + class_weight : dict or 'balanced', default=None + Weights associated with classes in the form ``{class_label: weight}``. + If not given, all classes are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + store_cv_results : bool, default=False + Flag indicating if the cross-validation results corresponding to + each alpha should be stored in the ``cv_results_`` attribute (see + below). This flag is only compatible with ``cv=None`` (i.e. using + Leave-One-Out Cross-Validation). + + .. versionchanged:: 1.5 + Parameter name changed from `store_cv_values` to `store_cv_results`. + + Attributes + ---------- + cv_results_ : ndarray of shape (n_samples, n_targets, n_alphas), optional + Cross-validation results for each alpha (only if ``store_cv_results=True`` and + ``cv=None``). After ``fit()`` has been called, this attribute will + contain the mean squared errors if `scoring is None` otherwise it + will contain standardized per point prediction values. + + .. versionchanged:: 1.5 + `cv_values_` changed to `cv_results_`. + + coef_ : ndarray of shape (1, n_features) or (n_targets, n_features) + Coefficient of the features in the decision function. + + ``coef_`` is of shape (1, n_features) when the given problem is binary. + + intercept_ : float or ndarray of shape (n_targets,) + Independent term in decision function. Set to 0.0 if + ``fit_intercept = False``. + + alpha_ : float + Estimated regularization parameter. + + best_score_ : float + Score of base estimator with best alpha. + + .. versionadded:: 0.23 + + classes_ : ndarray of shape (n_classes,) + The classes labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + Ridge : Ridge regression. + RidgeClassifier : Ridge classifier. + RidgeCV : Ridge regression with built-in cross validation. + + Notes + ----- + For multi-class classification, n_class classifiers are trained in + a one-versus-all approach. Concretely, this is implemented by taking + advantage of the multi-variate response support in Ridge. + + Examples + -------- + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.linear_model import RidgeClassifierCV + >>> X, y = load_breast_cancer(return_X_y=True) + >>> clf = RidgeClassifierCV(alphas=[1e-3, 1e-2, 1e-1, 1]).fit(X, y) + >>> clf.score(X, y) + 0.9630... + """ + + _parameter_constraints: dict = { + **_BaseRidgeCV._parameter_constraints, + "class_weight": [dict, StrOptions({"balanced"}), None], + } + for param in ("gcv_mode", "alpha_per_target"): + _parameter_constraints.pop(param) + + def __init__( + self, + alphas=(0.1, 1.0, 10.0), + *, + fit_intercept=True, + scoring=None, + cv=None, + class_weight=None, + store_cv_results=False, + ): + super().__init__( + alphas=alphas, + fit_intercept=fit_intercept, + scoring=scoring, + cv=cv, + store_cv_results=store_cv_results, + ) + self.class_weight = class_weight + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None, **params): + """Fit Ridge classifier with cv. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples + and `n_features` is the number of features. When using GCV, + will be cast to float64 if necessary. + + y : ndarray of shape (n_samples,) + Target values. Will be cast to X's dtype if necessary. + + sample_weight : float or ndarray of shape (n_samples,), default=None + Individual weights for each sample. If given a float, every sample + will have the same weight. + + **params : dict, default=None + Parameters to be passed to the underlying scorer. + + .. versionadded:: 1.5 + Only available if `enable_metadata_routing=True`, + which can be set by using + ``sklearn.set_config(enable_metadata_routing=True)``. + See :ref:`Metadata Routing User Guide ` for + more details. + + Returns + ------- + self : object + Fitted estimator. + """ + # `RidgeClassifier` does not accept "sag" or "saga" solver and thus support + # csr, csc, and coo sparse matrices. By using solver="eigen" we force to accept + # all sparse format. + X, y, sample_weight, Y = self._prepare_data(X, y, sample_weight, solver="eigen") + + # If cv is None, gcv mode will be used and we used the binarized Y + # since y will not be binarized in _RidgeGCV estimator. + # If cv is not None, a GridSearchCV with some RidgeClassifier + # estimators are used where y will be binarized. Thus, we pass y + # instead of the binarized Y. + target = Y if self.cv is None else y + super().fit(X, target, sample_weight=sample_weight, **params) + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag.py new file mode 100644 index 0000000000000000000000000000000000000000..12e5d049b0b1f88b17405f5633d6d7371a3cca83 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag.py @@ -0,0 +1,370 @@ +"""Solvers for Ridge and LogisticRegression using SAG algorithm""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np + +from ..exceptions import ConvergenceWarning +from ..utils import check_array +from ..utils.extmath import row_norms +from ..utils.validation import _check_sample_weight +from ._base import make_dataset +from ._sag_fast import sag32, sag64 + + +def get_auto_step_size( + max_squared_sum, alpha_scaled, loss, fit_intercept, n_samples=None, is_saga=False +): + """Compute automatic step size for SAG solver. + + The step size is set to 1 / (alpha_scaled + L + fit_intercept) where L is + the max sum of squares for over all samples. + + Parameters + ---------- + max_squared_sum : float + Maximum squared sum of X over samples. + + alpha_scaled : float + Constant that multiplies the regularization term, scaled by + 1. / n_samples, the number of samples. + + loss : {'log', 'squared', 'multinomial'} + The loss function used in SAG solver. + + fit_intercept : bool + Specifies if a constant (a.k.a. bias or intercept) will be + added to the decision function. + + n_samples : int, default=None + Number of rows in X. Useful if is_saga=True. + + is_saga : bool, default=False + Whether to return step size for the SAGA algorithm or the SAG + algorithm. + + Returns + ------- + step_size : float + Step size used in SAG solver. + + References + ---------- + Schmidt, M., Roux, N. L., & Bach, F. (2013). + Minimizing finite sums with the stochastic average gradient + https://hal.inria.fr/hal-00860051/document + + :arxiv:`Defazio, A., Bach F. & Lacoste-Julien S. (2014). + "SAGA: A Fast Incremental Gradient Method With Support + for Non-Strongly Convex Composite Objectives" <1407.0202>` + """ + if loss in ("log", "multinomial"): + L = 0.25 * (max_squared_sum + int(fit_intercept)) + alpha_scaled + elif loss == "squared": + # inverse Lipschitz constant for squared loss + L = max_squared_sum + int(fit_intercept) + alpha_scaled + else: + raise ValueError( + "Unknown loss function for SAG solver, got %s instead of 'log' or 'squared'" + % loss + ) + if is_saga: + # SAGA theoretical step size is 1/3L or 1 / (2 * (L + mu n)) + # See Defazio et al. 2014 + mun = min(2 * n_samples * alpha_scaled, L) + step = 1.0 / (2 * L + mun) + else: + # SAG theoretical step size is 1/16L but it is recommended to use 1 / L + # see http://www.birs.ca//workshops//2014/14w5003/files/schmidt.pdf, + # slide 65 + step = 1.0 / L + return step + + +def sag_solver( + X, + y, + sample_weight=None, + loss="log", + alpha=1.0, + beta=0.0, + max_iter=1000, + tol=0.001, + verbose=0, + random_state=None, + check_input=True, + max_squared_sum=None, + warm_start_mem=None, + is_saga=False, +): + """SAG solver for Ridge and LogisticRegression. + + SAG stands for Stochastic Average Gradient: the gradient of the loss is + estimated each sample at a time and the model is updated along the way with + a constant learning rate. + + IMPORTANT NOTE: 'sag' solver converges faster on columns that are on the + same scale. You can normalize the data by using + sklearn.preprocessing.StandardScaler on your data before passing it to the + fit method. + + This implementation works with data represented as dense numpy arrays or + sparse scipy arrays of floating point values for the features. It will + fit the data according to squared loss or log loss. + + The regularizer is a penalty added to the loss function that shrinks model + parameters towards the zero vector using the squared euclidean norm L2. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. With loss='multinomial', y must be label encoded + (see preprocessing.LabelEncoder). For loss='log' it must be in [0, 1]. + + sample_weight : array-like of shape (n_samples,), default=None + Weights applied to individual samples (1. for unweighted). + + loss : {'log', 'squared', 'multinomial'}, default='log' + Loss function that will be optimized: + -'log' is the binary logistic loss, as used in LogisticRegression. + -'squared' is the squared loss, as used in Ridge. + -'multinomial' is the multinomial logistic loss, as used in + LogisticRegression. + + .. versionadded:: 0.18 + *loss='multinomial'* + + alpha : float, default=1. + L2 regularization term in the objective function + ``(0.5 * alpha * || W ||_F^2)``. + + beta : float, default=0. + L1 regularization term in the objective function + ``(beta * || W ||_1)``. Only applied if ``is_saga`` is set to True. + + max_iter : int, default=1000 + The max number of passes over the training data if the stopping + criteria is not reached. + + tol : float, default=0.001 + The stopping criteria for the weights. The iterations will stop when + max(change in weights) / max(weights) < tol. + + verbose : int, default=0 + The verbosity level. + + random_state : int, RandomState instance or None, default=None + Used when shuffling the data. Pass an int for reproducible output + across multiple function calls. + See :term:`Glossary `. + + check_input : bool, default=True + If False, the input arrays X and y will not be checked. + + max_squared_sum : float, default=None + Maximum squared sum of X over samples. If None, it will be computed, + going through all the samples. The value should be precomputed + to speed up cross validation. + + warm_start_mem : dict, default=None + The initialization parameters used for warm starting. Warm starting is + currently used in LogisticRegression but not in Ridge. + It contains: + - 'coef': the weight vector, with the intercept in last line + if the intercept is fitted. + - 'gradient_memory': the scalar gradient for all seen samples. + - 'sum_gradient': the sum of gradient over all seen samples, + for each feature. + - 'intercept_sum_gradient': the sum of gradient over all seen + samples, for the intercept. + - 'seen': array of boolean describing the seen samples. + - 'num_seen': the number of seen samples. + + is_saga : bool, default=False + Whether to use the SAGA algorithm or the SAG algorithm. SAGA behaves + better in the first epochs, and allow for l1 regularisation. + + Returns + ------- + coef_ : ndarray of shape (n_features,) + Weight vector. + + n_iter_ : int + The number of full pass on all samples. + + warm_start_mem : dict + Contains a 'coef' key with the fitted result, and possibly the + fitted intercept at the end of the array. Contains also other keys + used for warm starting. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import linear_model + >>> n_samples, n_features = 10, 5 + >>> rng = np.random.RandomState(0) + >>> X = rng.randn(n_samples, n_features) + >>> y = rng.randn(n_samples) + >>> clf = linear_model.Ridge(solver='sag') + >>> clf.fit(X, y) + Ridge(solver='sag') + + >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) + >>> y = np.array([1, 1, 2, 2]) + >>> clf = linear_model.LogisticRegression(solver='sag') + >>> clf.fit(X, y) + LogisticRegression(solver='sag') + + References + ---------- + Schmidt, M., Roux, N. L., & Bach, F. (2013). + Minimizing finite sums with the stochastic average gradient + https://hal.inria.fr/hal-00860051/document + + :arxiv:`Defazio, A., Bach F. & Lacoste-Julien S. (2014). + "SAGA: A Fast Incremental Gradient Method With Support + for Non-Strongly Convex Composite Objectives" <1407.0202>` + + See Also + -------- + Ridge, SGDRegressor, ElasticNet, Lasso, SVR, + LogisticRegression, SGDClassifier, LinearSVC, Perceptron + """ + if warm_start_mem is None: + warm_start_mem = {} + # Ridge default max_iter is None + if max_iter is None: + max_iter = 1000 + + if check_input: + _dtype = [np.float64, np.float32] + X = check_array(X, dtype=_dtype, accept_sparse="csr", order="C") + y = check_array(y, dtype=_dtype, ensure_2d=False, order="C") + + n_samples, n_features = X.shape[0], X.shape[1] + # As in SGD, the alpha is scaled by n_samples. + alpha_scaled = float(alpha) / n_samples + beta_scaled = float(beta) / n_samples + + # if loss == 'multinomial', y should be label encoded. + n_classes = int(y.max()) + 1 if loss == "multinomial" else 1 + + # initialization + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + if "coef" in warm_start_mem.keys(): + coef_init = warm_start_mem["coef"] + else: + # assume fit_intercept is False + coef_init = np.zeros((n_features, n_classes), dtype=X.dtype, order="C") + + # coef_init contains possibly the intercept_init at the end. + # Note that Ridge centers the data before fitting, so fit_intercept=False. + fit_intercept = coef_init.shape[0] == (n_features + 1) + if fit_intercept: + intercept_init = coef_init[-1, :] + coef_init = coef_init[:-1, :] + else: + intercept_init = np.zeros(n_classes, dtype=X.dtype) + + if "intercept_sum_gradient" in warm_start_mem.keys(): + intercept_sum_gradient = warm_start_mem["intercept_sum_gradient"] + else: + intercept_sum_gradient = np.zeros(n_classes, dtype=X.dtype) + + if "gradient_memory" in warm_start_mem.keys(): + gradient_memory_init = warm_start_mem["gradient_memory"] + else: + gradient_memory_init = np.zeros( + (n_samples, n_classes), dtype=X.dtype, order="C" + ) + if "sum_gradient" in warm_start_mem.keys(): + sum_gradient_init = warm_start_mem["sum_gradient"] + else: + sum_gradient_init = np.zeros((n_features, n_classes), dtype=X.dtype, order="C") + + if "seen" in warm_start_mem.keys(): + seen_init = warm_start_mem["seen"] + else: + seen_init = np.zeros(n_samples, dtype=np.int32, order="C") + + if "num_seen" in warm_start_mem.keys(): + num_seen_init = warm_start_mem["num_seen"] + else: + num_seen_init = 0 + + dataset, intercept_decay = make_dataset(X, y, sample_weight, random_state) + + if max_squared_sum is None: + max_squared_sum = row_norms(X, squared=True).max() + step_size = get_auto_step_size( + max_squared_sum, + alpha_scaled, + loss, + fit_intercept, + n_samples=n_samples, + is_saga=is_saga, + ) + if step_size * alpha_scaled == 1: + raise ZeroDivisionError( + "Current sag implementation does not handle " + "the case step_size * alpha_scaled == 1" + ) + + sag = sag64 if X.dtype == np.float64 else sag32 + num_seen, n_iter_ = sag( + dataset, + coef_init, + intercept_init, + n_samples, + n_features, + n_classes, + tol, + max_iter, + loss, + step_size, + alpha_scaled, + beta_scaled, + sum_gradient_init, + gradient_memory_init, + seen_init, + num_seen_init, + fit_intercept, + intercept_sum_gradient, + intercept_decay, + is_saga, + verbose, + ) + + if n_iter_ == max_iter: + warnings.warn( + "The max_iter was reached which means the coef_ did not converge", + ConvergenceWarning, + ) + + if fit_intercept: + coef_init = np.vstack((coef_init, intercept_init)) + + warm_start_mem = { + "coef": coef_init, + "sum_gradient": sum_gradient_init, + "intercept_sum_gradient": intercept_sum_gradient, + "gradient_memory": gradient_memory_init, + "seen": seen_init, + "num_seen": num_seen, + } + + if loss == "multinomial": + coef_ = coef_init.T + else: + coef_ = coef_init[:, 0] + + return coef_, n_iter_, warm_start_mem diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..906928673b0b7570cd7d5e819f9dd521539f5233 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.pyx.tp @@ -0,0 +1,642 @@ +{{py: + +""" + +Template file for easily generate fused types consistent code using Tempita +(https://github.com/cython/cython/blob/master/Cython/Tempita/_tempita.py). + +Generated file: sag_fast.pyx + +Each class is duplicated for all dtypes (float and double). The keywords +between double braces are substituted during the build. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# name_suffix, c_type, np_type +dtypes = [('64', 'double', 'np.float64'), + ('32', 'float', 'np.float32')] + +}} +"""SAG and SAGA implementation""" + +import numpy as np +from libc.math cimport exp, fabs, isfinite, log +from libc.time cimport time, time_t +from libc.stdio cimport printf + +from .._loss._loss cimport ( + CyLossFunction, + CyHalfBinomialLoss, + CyHalfMultinomialLoss, + CyHalfSquaredError, +) +from ..utils._seq_dataset cimport SequentialDataset32, SequentialDataset64 + + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef inline {{c_type}} fmax{{name_suffix}}({{c_type}} x, {{c_type}} y) noexcept nogil: + if x > y: + return x + return y + +{{endfor}} + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef inline {{c_type}} _soft_thresholding{{name_suffix}}({{c_type}} x, {{c_type}} shrinkage) noexcept nogil: + return fmax{{name_suffix}}(x - shrinkage, 0) - fmax{{name_suffix}}(- x - shrinkage, 0) + +{{endfor}} + + +{{for name_suffix, c_type, np_type in dtypes}} + +def sag{{name_suffix}}( + SequentialDataset{{name_suffix}} dataset, + {{c_type}}[:, ::1] weights_array, + {{c_type}}[::1] intercept_array, + int n_samples, + int n_features, + int n_classes, + double tol, + int max_iter, + str loss_function, + double step_size, + double alpha, + double beta, + {{c_type}}[:, ::1] sum_gradient_init, + {{c_type}}[:, ::1] gradient_memory_init, + bint[::1] seen_init, + int num_seen, + bint fit_intercept, + {{c_type}}[::1] intercept_sum_gradient_init, + double intercept_decay, + bint saga, + bint verbose +): + """Stochastic Average Gradient (SAG) and SAGA solvers. + + Used in Ridge and LogisticRegression. + + Some implementation details: + + - Just-in-time (JIT) update: In SAG(A), the average-gradient update is + collinear with the drawn sample X_i. Therefore, if the data is sparse, the + random sample X_i will change the average gradient only on features j where + X_ij != 0. In some cases, the average gradient on feature j might change + only after k random samples with no change. In these cases, instead of + applying k times the same gradient step on feature j, we apply the gradient + step only once, scaled by k. This is called the "just-in-time update", and + it is performed in `lagged_update{{name_suffix}}`. This function also + applies the proximal operator after the gradient step (if L1 regularization + is used in SAGA). + + - Weight scale: In SAG(A), the weights are scaled down at each iteration + due to the L2 regularization. To avoid updating all the weights at each + iteration, the weight scale is factored out in a separate variable `wscale` + which is only used in the JIT update. When this variable is too small, it + is reset for numerical stability using the function + `scale_weights{{name_suffix}}`. This reset requires applying all remaining + JIT updates. This reset is also performed every `n_samples` iterations + before each convergence check, so when the algorithm stops, we are sure + that there is no remaining JIT updates. + + Reference + --------- + Schmidt, M., Roux, N. L., & Bach, F. (2013). + Minimizing finite sums with the stochastic average gradient + https://hal.inria.fr/hal-00860051/document + (section 4.3) + + :arxiv:`Defazio, A., Bach F. & Lacoste-Julien S. (2014). + "SAGA: A Fast Incremental Gradient Method With Support + for Non-Strongly Convex Composite Objectives" <1407.0202>` + """ + # the data pointer for x, the current sample + cdef {{c_type}} *x_data_ptr = NULL + # the index pointer for the column of the data + cdef int *x_ind_ptr = NULL + # the number of non-zero features for current sample + cdef int xnnz = -1 + # the label value for current sample + # the label value for current sample + cdef {{c_type}} y + # the sample weight + cdef {{c_type}} sample_weight + + # helper variable for indexes + cdef int f_idx, s_idx, feature_ind, class_ind, j + # the number of pass through all samples + cdef int n_iter = 0 + # helper to track iterations through samples + cdef int sample_itr + # the index (row number) of the current sample + cdef int sample_ind + + # the maximum change in weights, used to compute stopping criteria + cdef {{c_type}} max_change + # a holder variable for the max weight, used to compute stopping criteria + cdef {{c_type}} max_weight + + # the start time of the fit + cdef time_t start_time + # the end time of the fit + cdef time_t end_time + + # precomputation since the step size does not change in this implementation + cdef {{c_type}} wscale_update = 1.0 - step_size * alpha + + # helper for cumulative sum + cdef {{c_type}} cum_sum + + # the pointer to the coef_ or weights + cdef {{c_type}}* weights = &weights_array[0, 0] + + # the sum of gradients for each feature + cdef {{c_type}}* sum_gradient = &sum_gradient_init[0, 0] + + # the previously seen gradient for each sample + cdef {{c_type}}* gradient_memory = &gradient_memory_init[0, 0] + + # the cumulative sums needed for JIT params + cdef {{c_type}}[::1] cumulative_sums = np.empty(n_samples, dtype={{np_type}}, order="c") + + # the index for the last time this feature was updated + cdef int[::1] feature_hist = np.zeros(n_features, dtype=np.int32, order="c") + + # the previous weights to use to compute stopping criteria + cdef {{c_type}}[:, ::1] previous_weights_array = np.zeros((n_features, n_classes), dtype={{np_type}}, order="c") + cdef {{c_type}}* previous_weights = &previous_weights_array[0, 0] + + cdef {{c_type}}[::1] prediction = np.zeros(n_classes, dtype={{np_type}}, order="c") + + cdef {{c_type}}[::1] gradient = np.zeros(n_classes, dtype={{np_type}}, order="c") + + # Intermediate variable that need declaration since cython cannot infer when templating + cdef {{c_type}} val + + # Bias correction term in saga + cdef {{c_type}} gradient_correction + + # the scalar used for multiplying z + cdef {{c_type}} wscale = 1.0 + + # return value (-1 if an error occurred, 0 otherwise) + cdef int status = 0 + + # the cumulative sums for each iteration for the sparse implementation + cumulative_sums[0] = 0.0 + + # the multipliative scale needed for JIT params + cdef {{c_type}}[::1] cumulative_sums_prox + cdef {{c_type}}* cumulative_sums_prox_ptr + + cdef bint prox = beta > 0 and saga + + # Loss function to optimize + cdef CyLossFunction loss + # Whether the loss function is multinomial + cdef bint multinomial = False + # Multinomial loss function + cdef CyHalfMultinomialLoss multiloss + + if loss_function == "multinomial": + multinomial = True + multiloss = CyHalfMultinomialLoss() + elif loss_function == "log": + loss = CyHalfBinomialLoss() + elif loss_function == "squared": + loss = CyHalfSquaredError() + else: + raise ValueError("Invalid loss parameter: got %s instead of " + "one of ('log', 'squared', 'multinomial')" + % loss_function) + + if prox: + cumulative_sums_prox = np.empty(n_samples, dtype={{np_type}}, order="c") + cumulative_sums_prox_ptr = &cumulative_sums_prox[0] + else: + cumulative_sums_prox = None + cumulative_sums_prox_ptr = NULL + + with nogil: + start_time = time(NULL) + for n_iter in range(max_iter): + for sample_itr in range(n_samples): + # extract a random sample + sample_ind = dataset.random(&x_data_ptr, &x_ind_ptr, &xnnz, &y, &sample_weight) + + # cached index for gradient_memory + s_idx = sample_ind * n_classes + + # update the number of samples seen and the seen array + if seen_init[sample_ind] == 0: + num_seen += 1 + seen_init[sample_ind] = 1 + + # make the weight updates (just-in-time gradient step, and prox operator) + if sample_itr > 0: + status = lagged_update{{name_suffix}}( + weights=weights, + wscale=wscale, + xnnz=xnnz, + n_samples=n_samples, + n_classes=n_classes, + sample_itr=sample_itr, + cumulative_sums=&cumulative_sums[0], + cumulative_sums_prox=cumulative_sums_prox_ptr, + feature_hist=&feature_hist[0], + prox=prox, + sum_gradient=sum_gradient, + x_ind_ptr=x_ind_ptr, + reset=False, + n_iter=n_iter + ) + if status == -1: + break + + # find the current prediction + predict_sample{{name_suffix}}( + x_data_ptr=x_data_ptr, + x_ind_ptr=x_ind_ptr, + xnnz=xnnz, + w_data_ptr=weights, + wscale=wscale, + intercept=&intercept_array[0], + prediction=&prediction[0], + n_classes=n_classes + ) + + # compute the gradient for this sample, given the prediction + if multinomial: + multiloss.cy_gradient( + y_true=y, + raw_prediction=prediction, + sample_weight=sample_weight, + gradient_out=gradient, + ) + else: + gradient[0] = loss.cy_gradient(y, prediction[0]) * sample_weight + + # L2 regularization by simply rescaling the weights + wscale *= wscale_update + + # make the updates to the sum of gradients + for j in range(xnnz): + feature_ind = x_ind_ptr[j] + val = x_data_ptr[j] + f_idx = feature_ind * n_classes + for class_ind in range(n_classes): + gradient_correction = \ + val * (gradient[class_ind] - + gradient_memory[s_idx + class_ind]) + if saga: + # Note that this is not the main gradient step, + # which is performed just-in-time in lagged_update. + # This part is done outside the JIT update + # as it does not depend on the average gradient. + # The prox operator is applied after the JIT update + weights[f_idx + class_ind] -= \ + (gradient_correction * step_size + * (1 - 1. / num_seen) / wscale) + sum_gradient[f_idx + class_ind] += gradient_correction + + # fit the intercept + if fit_intercept: + for class_ind in range(n_classes): + gradient_correction = (gradient[class_ind] - + gradient_memory[s_idx + class_ind]) + intercept_sum_gradient_init[class_ind] += gradient_correction + gradient_correction *= step_size * (1. - 1. / num_seen) + if saga: + intercept_array[class_ind] -= \ + (step_size * intercept_sum_gradient_init[class_ind] / + num_seen * intercept_decay) + gradient_correction + else: + intercept_array[class_ind] -= \ + (step_size * intercept_sum_gradient_init[class_ind] / + num_seen * intercept_decay) + + # check to see that the intercept is not inf or NaN + if not isfinite(intercept_array[class_ind]): + status = -1 + break + # Break from the n_samples outer loop if an error happened + # in the fit_intercept n_classes inner loop + if status == -1: + break + + # update the gradient memory for this sample + for class_ind in range(n_classes): + gradient_memory[s_idx + class_ind] = gradient[class_ind] + + if sample_itr == 0: + cumulative_sums[0] = step_size / (wscale * num_seen) + if prox: + cumulative_sums_prox[0] = step_size * beta / wscale + else: + cumulative_sums[sample_itr] = \ + (cumulative_sums[sample_itr - 1] + + step_size / (wscale * num_seen)) + if prox: + cumulative_sums_prox[sample_itr] = \ + (cumulative_sums_prox[sample_itr - 1] + + step_size * beta / wscale) + # If wscale gets too small, we need to reset the scale. + # This also resets the just-in-time update system. + if wscale < 1e-9: + if verbose: + with gil: + print("rescaling...") + status = scale_weights{{name_suffix}}( + weights=weights, + wscale=&wscale, + n_features=n_features, + n_samples=n_samples, + n_classes=n_classes, + sample_itr=sample_itr, + cumulative_sums=&cumulative_sums[0], + cumulative_sums_prox=cumulative_sums_prox_ptr, + feature_hist=&feature_hist[0], + prox=prox, + sum_gradient=sum_gradient, + n_iter=n_iter + ) + if status == -1: + break + + # Break from the n_iter outer loop if an error happened in the + # n_samples inner loop + if status == -1: + break + + # We scale the weights every n_samples iterations and reset the + # just-in-time update system for numerical stability. + # Because this reset is done before every convergence check, we are + # sure there is no remaining lagged update when the algorithm stops. + status = scale_weights{{name_suffix}}( + weights=weights, + wscale=&wscale, + n_features=n_features, + n_samples=n_samples, + n_classes=n_classes, + sample_itr=n_samples - 1, + cumulative_sums=&cumulative_sums[0], + cumulative_sums_prox=cumulative_sums_prox_ptr, + feature_hist=&feature_hist[0], + prox=prox, + sum_gradient=sum_gradient, + n_iter=n_iter + ) + if status == -1: + break + + # check if the stopping criteria is reached + max_change = 0.0 + max_weight = 0.0 + for idx in range(n_features * n_classes): + max_weight = fmax{{name_suffix}}(max_weight, fabs(weights[idx])) + max_change = fmax{{name_suffix}}(max_change, fabs(weights[idx] - previous_weights[idx])) + previous_weights[idx] = weights[idx] + if ((max_weight != 0 and max_change / max_weight <= tol) + or max_weight == 0 and max_change == 0): + if verbose: + end_time = time(NULL) + with gil: + print("convergence after %d epochs took %d seconds" % + (n_iter + 1, end_time - start_time)) + break + elif verbose: + printf('Epoch %d, change: %.8g\n', n_iter + 1, + max_change / max_weight) + n_iter += 1 + # We do the error treatment here based on error code in status to avoid + # re-acquiring the GIL within the cython code, which slows the computation + # when the sag/saga solver is used concurrently in multiple Python threads. + if status == -1: + raise ValueError(("Floating-point under-/overflow occurred at epoch" + " #%d. Scaling input data with StandardScaler or" + " MinMaxScaler might help.") % n_iter) + + if verbose and n_iter >= max_iter: + end_time = time(NULL) + print(("max_iter reached after %d seconds") % + (end_time - start_time)) + + return num_seen, n_iter + +{{endfor}} + + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef int scale_weights{{name_suffix}}( + {{c_type}}* weights, + {{c_type}}* wscale, + int n_features, + int n_samples, + int n_classes, + int sample_itr, + {{c_type}}* cumulative_sums, + {{c_type}}* cumulative_sums_prox, + int* feature_hist, + bint prox, + {{c_type}}* sum_gradient, + int n_iter +) noexcept nogil: + """Scale the weights and reset wscale to 1.0 for numerical stability, and + reset the just-in-time (JIT) update system. + + See `sag{{name_suffix}}`'s docstring about the JIT update system. + + wscale = (1 - step_size * alpha) ** (n_iter * n_samples + sample_itr) + can become very small, so we reset it every n_samples iterations to 1.0 for + numerical stability. To be able to scale, we first need to update every + coefficients and reset the just-in-time update system. + This also limits the size of `cumulative_sums`. + """ + + cdef int status + status = lagged_update{{name_suffix}}( + weights, + wscale[0], + n_features, + n_samples, + n_classes, + sample_itr + 1, + cumulative_sums, + cumulative_sums_prox, + feature_hist, + prox, + sum_gradient, + NULL, + True, + n_iter + ) + # if lagged update succeeded, reset wscale to 1.0 + if status == 0: + wscale[0] = 1.0 + return status + +{{endfor}} + + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef int lagged_update{{name_suffix}}( + {{c_type}}* weights, + {{c_type}} wscale, + int xnnz, + int n_samples, + int n_classes, + int sample_itr, + {{c_type}}* cumulative_sums, + {{c_type}}* cumulative_sums_prox, + int* feature_hist, + bint prox, + {{c_type}}* sum_gradient, + int* x_ind_ptr, + bint reset, + int n_iter +) noexcept nogil: + """Hard perform the JIT updates for non-zero features of present sample. + + See `sag{{name_suffix}}`'s docstring about the JIT update system. + + The updates that awaits are kept in memory using cumulative_sums, + cumulative_sums_prox, wscale and feature_hist. See original SAGA paper + (Defazio et al. 2014) for details. If reset=True, we also reset wscale to + 1 (this is done at the end of each epoch). + """ + cdef int feature_ind, class_ind, idx, f_idx, lagged_ind, last_update_ind + cdef {{c_type}} cum_sum, grad_step, prox_step, cum_sum_prox + for feature_ind in range(xnnz): + if not reset: + feature_ind = x_ind_ptr[feature_ind] + f_idx = feature_ind * n_classes + + cum_sum = cumulative_sums[sample_itr - 1] + if prox: + cum_sum_prox = cumulative_sums_prox[sample_itr - 1] + if feature_hist[feature_ind] != 0: + cum_sum -= cumulative_sums[feature_hist[feature_ind] - 1] + if prox: + cum_sum_prox -= cumulative_sums_prox[feature_hist[feature_ind] - 1] + if not prox: + for class_ind in range(n_classes): + idx = f_idx + class_ind + weights[idx] -= cum_sum * sum_gradient[idx] + if reset: + weights[idx] *= wscale + if not isfinite(weights[idx]): + # returning here does not require the gil as the return + # type is a C integer + return -1 + else: + for class_ind in range(n_classes): + idx = f_idx + class_ind + if fabs(sum_gradient[idx] * cum_sum) < cum_sum_prox: + # In this case, we can perform all the gradient steps and + # all the proximal steps in this order, which is more + # efficient than unrolling all the lagged updates. + # Idea taken from scikit-learn-contrib/lightning. + weights[idx] -= cum_sum * sum_gradient[idx] + weights[idx] = _soft_thresholding{{name_suffix}}(weights[idx], + cum_sum_prox) + else: + last_update_ind = feature_hist[feature_ind] + if last_update_ind == -1: + last_update_ind = sample_itr - 1 + for lagged_ind in range(sample_itr - 1, + last_update_ind - 1, -1): + if lagged_ind > 0: + grad_step = (cumulative_sums[lagged_ind] + - cumulative_sums[lagged_ind - 1]) + prox_step = (cumulative_sums_prox[lagged_ind] + - cumulative_sums_prox[lagged_ind - 1]) + else: + grad_step = cumulative_sums[lagged_ind] + prox_step = cumulative_sums_prox[lagged_ind] + weights[idx] -= sum_gradient[idx] * grad_step + weights[idx] = _soft_thresholding{{name_suffix}}(weights[idx], + prox_step) + + if reset: + weights[idx] *= wscale + # check to see that the weight is not inf or NaN + if not isfinite(weights[idx]): + return -1 + if reset: + feature_hist[feature_ind] = sample_itr % n_samples + else: + feature_hist[feature_ind] = sample_itr + + if reset: + cumulative_sums[sample_itr - 1] = 0.0 + if prox: + cumulative_sums_prox[sample_itr - 1] = 0.0 + + return 0 + +{{endfor}} + + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef void predict_sample{{name_suffix}}( + {{c_type}}* x_data_ptr, + int* x_ind_ptr, + int xnnz, + {{c_type}}* w_data_ptr, + {{c_type}} wscale, + {{c_type}}* intercept, + {{c_type}}* prediction, + int n_classes +) noexcept nogil: + """Compute the prediction given sparse sample x and dense weight w. + + Parameters + ---------- + x_data_ptr : pointer + Pointer to the data of the sample x + + x_ind_ptr : pointer + Pointer to the indices of the sample x + + xnnz : int + Number of non-zero element in the sample x + + w_data_ptr : pointer + Pointer to the data of the weights w + + wscale : {{c_type}} + Scale of the weights w + + intercept : pointer + Pointer to the intercept + + prediction : pointer + Pointer to store the resulting prediction + + n_classes : int + Number of classes in multinomial case. Equals 1 in binary case. + + """ + cdef int feature_ind, class_ind, j + cdef {{c_type}} innerprod + + for class_ind in range(n_classes): + innerprod = 0.0 + # Compute the dot product only on non-zero elements of x + for j in range(xnnz): + feature_ind = x_ind_ptr[j] + innerprod += (w_data_ptr[feature_ind * n_classes + class_ind] * + x_data_ptr[j]) + + prediction[class_ind] = wscale * innerprod + intercept[class_ind] + + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sgd_fast.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sgd_fast.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..45cdf9172d8c455e3ba27f5755337683dd704aad --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_sgd_fast.pyx.tp @@ -0,0 +1,661 @@ +{{py: + +""" +Template file to easily generate fused types consistent code using Tempita +(https://github.com/cython/cython/blob/master/Cython/Tempita/_tempita.py). + +Generated file: _sgd_fast.pyx + +Each relevant function is duplicated for the dtypes float and double. +The keywords between double braces are substituted during the build. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# The dtypes are defined as follows (name_suffix, c_type, np_type) +dtypes = [ + ("64", "double", "np.float64"), + ("32", "float", "np.float32"), +] + +}} +"""SGD implementation""" + +import numpy as np +from time import time + +from cython cimport floating +from libc.math cimport exp, fabs, isfinite, log, pow, INFINITY + +from .._loss._loss cimport CyLossFunction +from ..utils._typedefs cimport uint32_t, uint8_t +from ..utils._weight_vector cimport WeightVector32, WeightVector64 +from ..utils._seq_dataset cimport SequentialDataset32, SequentialDataset64 + + +cdef extern from *: + """ + /* Penalty constants */ + #define NO_PENALTY 0 + #define L1 1 + #define L2 2 + #define ELASTICNET 3 + + /* Learning rate constants */ + #define CONSTANT 1 + #define OPTIMAL 2 + #define INVSCALING 3 + #define ADAPTIVE 4 + #define PA1 5 + #define PA2 6 + """ + int NO_PENALTY = 0 + int L1 = 1 + int L2 = 2 + int ELASTICNET = 3 + + int CONSTANT = 1 + int OPTIMAL = 2 + int INVSCALING = 3 + int ADAPTIVE = 4 + int PA1 = 5 + int PA2 = 6 + + +# ---------------------------------------- +# Extension Types for Loss Functions +# ---------------------------------------- + +cdef class Regression(CyLossFunction): + """Base class for loss functions for regression""" + + def py_loss(self, double p, double y): + """Python version of `loss` for testing only. + + Pytest needs a python function and can't use cdef functions. + + Parameters + ---------- + p : double + The prediction, `p = w^T x + intercept`. + y : double + The true value (aka target). + + Returns + ------- + double + The loss evaluated at `p` and `y`. + """ + return self.cy_loss(y, p) + + def py_dloss(self, double p, double y): + """Python version of `dloss` for testing only. + + Pytest needs a python function and can't use cdef functions. + + Parameters + ---------- + p : double + The prediction, `p = w^T x`. + y : double + The true value (aka target). + + Returns + ------- + double + The derivative of the loss function with regards to `p`. + """ + return self.cy_gradient(y, p) + + +cdef class Classification(CyLossFunction): + """Base class for loss functions for classification""" + + def py_loss(self, double p, double y): + """Python version of `loss` for testing only.""" + return self.cy_loss(y, p) + + def py_dloss(self, double p, double y): + """Python version of `dloss` for testing only.""" + return self.cy_gradient(y, p) + + +cdef class ModifiedHuber(Classification): + """Modified Huber loss for binary classification with y in {-1, 1} + + This is equivalent to quadratically smoothed SVM with gamma = 2. + + See T. Zhang 'Solving Large Scale Linear Prediction Problems Using + Stochastic Gradient Descent', ICML'04. + """ + cdef double cy_loss(self, double y, double p) noexcept nogil: + cdef double z = p * y + if z >= 1.0: + return 0.0 + elif z >= -1.0: + return (1.0 - z) * (1.0 - z) + else: + return -4.0 * z + + cdef double cy_gradient(self, double y, double p) noexcept nogil: + cdef double z = p * y + if z >= 1.0: + return 0.0 + elif z >= -1.0: + return 2.0 * (1.0 - z) * -y + else: + return -4.0 * y + + def __reduce__(self): + return ModifiedHuber, () + + +cdef class Hinge(Classification): + """Hinge loss for binary classification tasks with y in {-1,1} + + Parameters + ---------- + + threshold : float > 0.0 + Margin threshold. When threshold=1.0, one gets the loss used by SVM. + When threshold=0.0, one gets the loss used by the Perceptron. + """ + + cdef double threshold + + def __init__(self, double threshold=1.0): + self.threshold = threshold + + cdef double cy_loss(self, double y, double p) noexcept nogil: + cdef double z = p * y + if z <= self.threshold: + return self.threshold - z + return 0.0 + + cdef double cy_gradient(self, double y, double p) noexcept nogil: + cdef double z = p * y + if z <= self.threshold: + return -y + return 0.0 + + def __reduce__(self): + return Hinge, (self.threshold,) + + +cdef class SquaredHinge(Classification): + """Squared Hinge loss for binary classification tasks with y in {-1,1} + + Parameters + ---------- + + threshold : float > 0.0 + Margin threshold. When threshold=1.0, one gets the loss used by + (quadratically penalized) SVM. + """ + + cdef double threshold + + def __init__(self, double threshold=1.0): + self.threshold = threshold + + cdef double cy_loss(self, double y, double p) noexcept nogil: + cdef double z = self.threshold - p * y + if z > 0: + return z * z + return 0.0 + + cdef double cy_gradient(self, double y, double p) noexcept nogil: + cdef double z = self.threshold - p * y + if z > 0: + return -2 * y * z + return 0.0 + + def __reduce__(self): + return SquaredHinge, (self.threshold,) + + +cdef class EpsilonInsensitive(Regression): + """Epsilon-Insensitive loss (used by SVR). + + loss = max(0, |y - p| - epsilon) + """ + + cdef double epsilon + + def __init__(self, double epsilon): + self.epsilon = epsilon + + cdef double cy_loss(self, double y, double p) noexcept nogil: + cdef double ret = fabs(y - p) - self.epsilon + return ret if ret > 0 else 0 + + cdef double cy_gradient(self, double y, double p) noexcept nogil: + if y - p > self.epsilon: + return -1 + elif p - y > self.epsilon: + return 1 + else: + return 0 + + def __reduce__(self): + return EpsilonInsensitive, (self.epsilon,) + + +cdef class SquaredEpsilonInsensitive(Regression): + """Epsilon-Insensitive loss. + + loss = max(0, |y - p| - epsilon)^2 + """ + + cdef double epsilon + + def __init__(self, double epsilon): + self.epsilon = epsilon + + cdef double cy_loss(self, double y, double p) noexcept nogil: + cdef double ret = fabs(y - p) - self.epsilon + return ret * ret if ret > 0 else 0 + + cdef double cy_gradient(self, double y, double p) noexcept nogil: + cdef double z + z = y - p + if z > self.epsilon: + return -2 * (z - self.epsilon) + elif z < -self.epsilon: + return 2 * (-z - self.epsilon) + else: + return 0 + + def __reduce__(self): + return SquaredEpsilonInsensitive, (self.epsilon,) + +{{for name_suffix, c_type, np_type in dtypes}} + +def _plain_sgd{{name_suffix}}( + const {{c_type}}[::1] weights, + double intercept, + const {{c_type}}[::1] average_weights, + double average_intercept, + CyLossFunction loss, + int penalty_type, + double alpha, + double C, + double l1_ratio, + SequentialDataset{{name_suffix}} dataset, + const uint8_t[::1] validation_mask, + bint early_stopping, + validation_score_cb, + int n_iter_no_change, + unsigned int max_iter, + double tol, + int fit_intercept, + int verbose, + bint shuffle, + uint32_t seed, + 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, +): + """SGD for generic loss functions and penalties with optional averaging + + Parameters + ---------- + weights : ndarray[{{c_type}}, ndim=1] + The allocated vector of weights. + intercept : double + The initial intercept. + average_weights : ndarray[{{c_type}}, ndim=1] + The average weights as computed for ASGD. Should be None if average + is 0. + average_intercept : double + The average intercept for ASGD. Should be 0 if average is 0. + loss : CyLossFunction + A concrete ``CyLossFunction`` object. + penalty_type : int + The penalty 2 for L2, 1 for L1, and 3 for Elastic-Net. + alpha : float + The regularization parameter. + C : float + Maximum step size for passive aggressive. + l1_ratio : float + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + dataset : SequentialDataset + A concrete ``SequentialDataset`` object. + validation_mask : ndarray[uint8_t, ndim=1] + Equal to True on the validation set. + early_stopping : boolean + Whether to use a stopping criterion based on the validation set. + validation_score_cb : callable + A callable to compute a validation score given the current + coefficients and intercept values. + Used only if early_stopping is True. + n_iter_no_change : int + Number of iteration with no improvement to wait before stopping. + max_iter : int + The maximum number of iterations (epochs). + tol: double + The tolerance for the stopping criterion. + fit_intercept : int + Whether or not to fit the intercept (1 or 0). + verbose : int + Print verbose output; 0 for quite. + shuffle : boolean + Whether to shuffle the training data before each epoch. + weight_pos : float + The weight of the positive class. + weight_neg : float + The weight of the negative class. + seed : uint32_t + Seed of the pseudorandom number generator used to shuffle the data. + learning_rate : int + The learning rate: + (1) constant, eta = eta0 + (2) optimal, eta = 1.0/(alpha * t). + (3) inverse scaling, eta = eta0 / pow(t, power_t) + (4) adaptive decrease + (5) Passive Aggressive-I, eta = min(alpha, loss/norm(x)) + (6) Passive Aggressive-II, eta = 1.0 / (norm(x) + 0.5*alpha) + eta0 : double + 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`. + Default: 1.0. + average : int + The number of iterations before averaging starts. average=1 is + equivalent to averaging for all iterations. + + + Returns + ------- + weights : array, shape=[n_features] + The fitted weight vector. + intercept : float + The fitted intercept term. + average_weights : array shape=[n_features] + The averaged weights across iterations. Values are valid only if + average > 0. + average_intercept : float + The averaged intercept across iterations. + Values are valid only if average > 0. + n_iter_ : int + The actual number of iter (epochs). + """ + + # get the data information into easy vars + cdef Py_ssize_t n_samples = dataset.n_samples + cdef Py_ssize_t n_features = weights.shape[0] + + cdef WeightVector{{name_suffix}} w = WeightVector{{name_suffix}}(weights, average_weights) + cdef {{c_type}} *x_data_ptr = NULL + cdef int *x_ind_ptr = NULL + + # helper variables + cdef int no_improvement_count = 0 + cdef bint infinity = False + cdef int xnnz + 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 + cdef double best_score = -INFINITY + cdef {{c_type}} y = 0.0 + cdef {{c_type}} sample_weight + cdef {{c_type}} class_weight = 1.0 + cdef unsigned int count = 0 + cdef unsigned int train_count = n_samples - np.sum(validation_mask) + cdef unsigned int epoch = 0 + cdef unsigned int i = 0 + cdef int is_hinge = isinstance(loss, Hinge) + cdef double optimal_init = 0.0 + cdef double dloss = 0.0 + cdef double MAX_DLOSS = 1e12 + + cdef long long sample_index + + # q vector is only used for L1 regularization + cdef {{c_type}}[::1] q = None + cdef {{c_type}} * q_data_ptr = NULL + if penalty_type == L1 or penalty_type == ELASTICNET: + q = np.zeros((n_features,), dtype={{np_type}}, order="c") + q_data_ptr = &q[0] + cdef double u = 0.0 + + if penalty_type == L2: + l1_ratio = 0.0 + elif penalty_type == L1: + l1_ratio = 1.0 + + eta = eta0 + + if learning_rate == OPTIMAL: + typw = np.sqrt(1.0 / np.sqrt(alpha)) + # computing eta0, the initial learning rate + initial_eta0 = typw / max(1.0, loss.cy_gradient(1.0, -typw)) + # initialize t such that eta at first sample equals eta0 + optimal_init = 1.0 / (initial_eta0 * alpha) + + t_start = time() + with nogil: + for epoch in range(max_iter): + sumloss = 0 + if verbose > 0: + with gil: + print("-- Epoch %d" % (epoch + 1)) + if shuffle: + dataset.shuffle(seed) + for i in range(n_samples): + dataset.next(&x_data_ptr, &x_ind_ptr, &xnnz, + &y, &sample_weight) + + sample_index = dataset.index_data_ptr[dataset.current_index] + if validation_mask[sample_index]: + # do not learn on the validation set + continue + + p = w.dot(x_data_ptr, x_ind_ptr, xnnz) + intercept + if learning_rate == OPTIMAL: + eta = 1.0 / (alpha * (optimal_init + t - 1)) + elif learning_rate == INVSCALING: + eta = eta0 / pow(t, power_t) + + if verbose or not early_stopping: + sumloss += loss.cy_loss(y, p) + + if y > 0.0: + class_weight = weight_pos + else: + class_weight = weight_neg + + if learning_rate == PA1: + update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + if update == 0: + continue + update = min(C, loss.cy_loss(y, p) / update) + elif learning_rate == PA2: + update = sqnorm(x_data_ptr, x_ind_ptr, xnnz) + update = loss.cy_loss(y, p) / (update + 0.5 / C) + else: + dloss = loss.cy_gradient(y, p) + # clip dloss with large values to avoid numerical + # instabilities + if dloss < -MAX_DLOSS: + dloss = -MAX_DLOSS + elif dloss > MAX_DLOSS: + dloss = MAX_DLOSS + update = -eta * dloss + + if learning_rate >= PA1: + if is_hinge: + # classification + update *= y + elif y - p < 0: + # regression + update *= -1 + + update *= class_weight * sample_weight + + if penalty_type >= L2: + # 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 = 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 + # average weights, this is done regardless as to whether + # the update is 0 + + w.add_average(x_data_ptr, x_ind_ptr, xnnz, + update, (t - average + 1)) + average_intercept += ((intercept - average_intercept) / + (t - average + 1)) + + if penalty_type == L1 or penalty_type == ELASTICNET: + u += (l1_ratio * eta * alpha) + l1penalty{{name_suffix}}(w, q_data_ptr, x_ind_ptr, xnnz, u) + + t += 1 + count += 1 + + # report epoch information + if verbose > 0: + with gil: + print("Norm: %.2f, NNZs: %d, Bias: %.6f, T: %d, " + "Avg. loss: %f" + % (w.norm(), np.nonzero(weights)[0].shape[0], + intercept, count, sumloss / train_count)) + print("Total training time: %.2f seconds." + % (time() - t_start)) + + # floating-point under-/overflow check. + if (not isfinite(intercept) or any_nonfinite(weights)): + infinity = True + break + + # evaluate the score on the validation set + if early_stopping: + with gil: + score = validation_score_cb(weights.base, intercept) + if tol > -INFINITY and score < best_score + tol: + no_improvement_count += 1 + else: + no_improvement_count = 0 + if score > best_score: + best_score = score + # or evaluate the loss on the training set + else: + if tol > -INFINITY and sumloss > best_loss - tol * train_count: + no_improvement_count += 1 + else: + no_improvement_count = 0 + if sumloss < best_loss: + best_loss = sumloss + + # if there is no improvement several times in a row + if no_improvement_count >= n_iter_no_change: + if learning_rate == ADAPTIVE and eta > 1e-6: + eta = eta / 5 + no_improvement_count = 0 + else: + if verbose: + with gil: + print("Convergence after %d epochs took %.2f " + "seconds" % (epoch + 1, time() - t_start)) + break + + if infinity: + raise ValueError(("Floating-point under-/overflow occurred at epoch" + " #%d. Scaling input data with StandardScaler or" + " MinMaxScaler might help.") % (epoch + 1)) + + w.reset_wscale() + + return ( + weights.base, + intercept, + None if average_weights is None else average_weights.base, + average_intercept, + epoch + 1 + ) + +{{endfor}} + + +cdef inline bint any_nonfinite(const floating[::1] w) noexcept nogil: + for i in range(w.shape[0]): + if not isfinite(w[i]): + return True + return 0 + + +cdef inline double sqnorm( + floating * x_data_ptr, + int * x_ind_ptr, + int xnnz, +) noexcept nogil: + cdef double x_norm = 0.0 + cdef int j + cdef double z + for j in range(xnnz): + z = x_data_ptr[j] + x_norm += z * z + return x_norm + + +{{for name_suffix, c_type, np_type in dtypes}} + +cdef void l1penalty{{name_suffix}}( + WeightVector{{name_suffix}} w, + {{c_type}} * q_data_ptr, + int *x_ind_ptr, + int xnnz, + double u, +) noexcept nogil: + """Apply the L1 penalty to each updated feature + + This implements the truncated gradient approach by + [Tsuruoka, Y., Tsujii, J., and Ananiadou, S., 2009]. + """ + cdef double z = 0.0 + cdef int j = 0 + cdef int idx = 0 + cdef double wscale = w.wscale + cdef {{c_type}} *w_data_ptr = w.w_data_ptr + for j in range(xnnz): + idx = x_ind_ptr[j] + z = w_data_ptr[idx] + if wscale * z > 0.0: + w_data_ptr[idx] = max( + 0.0, w_data_ptr[idx] - ((u + q_data_ptr[idx]) / wscale)) + + elif wscale * z < 0.0: + w_data_ptr[idx] = min( + 0.0, w_data_ptr[idx] + ((u - q_data_ptr[idx]) / wscale)) + + q_data_ptr[idx] += wscale * (w_data_ptr[idx] - z) + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_stochastic_gradient.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_stochastic_gradient.py new file mode 100644 index 0000000000000000000000000000000000000000..8f7c814000614e91e2daf605835c0ebc69fc76c3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_stochastic_gradient.py @@ -0,0 +1,2604 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +"""Classification, regression and One-Class SVM using Stochastic Gradient +Descent (SGD). +""" + +import warnings +from abc import ABCMeta, abstractmethod +from numbers import Integral, Real + +import numpy as np + +from .._loss._loss import CyHalfBinomialLoss, CyHalfSquaredError, CyHuberLoss +from ..base import ( + BaseEstimator, + OutlierMixin, + RegressorMixin, + _fit_context, + clone, + is_classifier, +) +from ..exceptions import ConvergenceWarning +from ..model_selection import ShuffleSplit, StratifiedShuffleSplit +from ..utils import check_random_state, compute_class_weight +from ..utils._param_validation import Hidden, Interval, StrOptions +from ..utils.extmath import safe_sparse_dot +from ..utils.metaestimators import available_if +from ..utils.multiclass import _check_partial_fit_first_call +from ..utils.parallel import Parallel, delayed +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data +from ._base import LinearClassifierMixin, SparseCoefMixin, make_dataset +from ._sgd_fast import ( + EpsilonInsensitive, + Hinge, + ModifiedHuber, + SquaredEpsilonInsensitive, + SquaredHinge, + _plain_sgd32, + _plain_sgd64, +) + +LEARNING_RATE_TYPES = { + "constant": 1, + "optimal": 2, + "invscaling": 3, + "adaptive": 4, + "pa1": 5, + "pa2": 6, +} + +PENALTY_TYPES = {"none": 0, "l2": 2, "l1": 1, "elasticnet": 3} + +DEFAULT_EPSILON = 0.1 +# Default value of ``epsilon`` parameter. + +MAX_INT = np.iinfo(np.int32).max + + +class _ValidationScoreCallback: + """Callback for early stopping based on validation score""" + + def __init__(self, estimator, X_val, y_val, sample_weight_val, classes=None): + self.estimator = clone(estimator) + self.estimator.t_ = 1 # to pass check_is_fitted + if classes is not None: + self.estimator.classes_ = classes + self.X_val = X_val + self.y_val = y_val + self.sample_weight_val = sample_weight_val + + def __call__(self, coef, intercept): + est = self.estimator + est.coef_ = coef.reshape(1, -1) + est.intercept_ = np.atleast_1d(intercept) + return est.score(self.X_val, self.y_val, self.sample_weight_val) + + +class BaseSGD(SparseCoefMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for SGD classification and regression.""" + + _parameter_constraints: dict = { + "fit_intercept": ["boolean"], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left"), None], + "shuffle": ["boolean"], + "verbose": ["verbose"], + "random_state": ["random_state"], + "warm_start": ["boolean"], + "average": [Interval(Integral, 0, None, closed="neither"), "boolean"], + } + + def __init__( + self, + loss, + *, + penalty="l2", + alpha=0.0001, + C=1.0, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + epsilon=0.1, + random_state=None, + learning_rate="optimal", + eta0=0.0, + power_t=0.5, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + warm_start=False, + average=False, + ): + self.loss = loss + self.penalty = penalty + self.learning_rate = learning_rate + self.epsilon = epsilon + self.alpha = alpha + self.C = C + self.l1_ratio = l1_ratio + self.fit_intercept = fit_intercept + self.shuffle = shuffle + self.random_state = random_state + self.verbose = verbose + self.eta0 = eta0 + self.power_t = power_t + self.early_stopping = early_stopping + self.validation_fraction = validation_fraction + self.n_iter_no_change = n_iter_no_change + self.warm_start = warm_start + self.average = average + self.max_iter = max_iter + self.tol = tol + + @abstractmethod + def fit(self, X, y): + """Fit model.""" + + def _more_validate_params(self, for_partial_fit=False): + """Validate input params.""" + if self.early_stopping and for_partial_fit: + raise ValueError("early_stopping should be False with partial_fit") + if ( + self.learning_rate in ("constant", "invscaling", "adaptive") + and self.eta0 <= 0.0 + ): + raise ValueError("eta0 must be > 0") + if self.learning_rate == "optimal" and self.alpha == 0: + raise ValueError( + "alpha must be > 0 since " + "learning_rate is 'optimal'. alpha is used " + "to compute the optimal learning rate." + ) + if self.penalty == "elasticnet" and self.l1_ratio is None: + raise ValueError("l1_ratio must be set when penalty is 'elasticnet'") + + # raises ValueError if not registered + self._get_penalty_type(self.penalty) + self._get_learning_rate_type(self.learning_rate) + + def _get_l1_ratio(self): + if self.l1_ratio is None: + # plain_sgd expects a float. Any value is fine since at this point + # penalty can't be "elsaticnet" so l1_ratio is not used. + return 0.0 + return self.l1_ratio + + def _get_loss_function(self, loss): + """Get concrete ``LossFunction`` object for str ``loss``.""" + loss_ = self.loss_functions[loss] + loss_class, args = loss_[0], loss_[1:] + if loss in ("huber", "epsilon_insensitive", "squared_epsilon_insensitive"): + args = (self.epsilon,) + return loss_class(*args) + + def _get_learning_rate_type(self, learning_rate): + return LEARNING_RATE_TYPES[learning_rate] + + def _get_penalty_type(self, penalty): + penalty = str(penalty).lower() + return PENALTY_TYPES[penalty] + + def _allocate_parameter_mem( + self, + n_classes, + n_features, + input_dtype, + coef_init=None, + intercept_init=None, + one_class=0, + ): + """Allocate mem for parameters; initialize if provided.""" + if n_classes > 2: + # allocate coef_ for multi-class + if coef_init is not None: + coef_init = np.asarray(coef_init, dtype=input_dtype, order="C") + if coef_init.shape != (n_classes, n_features): + raise ValueError("Provided ``coef_`` does not match dataset. ") + self.coef_ = coef_init + else: + self.coef_ = np.zeros( + (n_classes, n_features), dtype=input_dtype, order="C" + ) + + # allocate intercept_ for multi-class + if intercept_init is not None: + intercept_init = np.asarray( + intercept_init, order="C", dtype=input_dtype + ) + if intercept_init.shape != (n_classes,): + raise ValueError("Provided intercept_init does not match dataset.") + self.intercept_ = intercept_init + else: + self.intercept_ = np.zeros(n_classes, dtype=input_dtype, order="C") + else: + # allocate coef_ + if coef_init is not None: + coef_init = np.asarray(coef_init, dtype=input_dtype, order="C") + coef_init = coef_init.ravel() + if coef_init.shape != (n_features,): + raise ValueError("Provided coef_init does not match dataset.") + self.coef_ = coef_init + else: + self.coef_ = np.zeros(n_features, dtype=input_dtype, order="C") + + # allocate intercept_ + if intercept_init is not None: + intercept_init = np.asarray(intercept_init, dtype=input_dtype) + if intercept_init.shape != (1,) and intercept_init.shape != (): + raise ValueError("Provided intercept_init does not match dataset.") + if one_class: + self.offset_ = intercept_init.reshape( + 1, + ) + else: + self.intercept_ = intercept_init.reshape( + 1, + ) + else: + if one_class: + self.offset_ = np.zeros(1, dtype=input_dtype, order="C") + else: + self.intercept_ = np.zeros(1, dtype=input_dtype, order="C") + + # initialize average parameters + if self.average > 0: + self._standard_coef = self.coef_ + self._average_coef = np.zeros( + self.coef_.shape, dtype=input_dtype, 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=input_dtype, order="C" + ) + + def _make_validation_split(self, y, sample_mask): + """Split the dataset between training set and validation set. + + Parameters + ---------- + y : ndarray of shape (n_samples, ) + Target values. + + sample_mask : ndarray of shape (n_samples, ) + A boolean array indicating whether each sample should be included + for validation set. + + Returns + ------- + validation_mask : ndarray of shape (n_samples, ) + Equal to True on the validation set, False on the training set. + """ + n_samples = y.shape[0] + validation_mask = np.zeros(n_samples, dtype=np.bool_) + if not self.early_stopping: + # use the full set for training, with an empty validation set + return validation_mask + + if is_classifier(self): + splitter_type = StratifiedShuffleSplit + else: + splitter_type = ShuffleSplit + cv = splitter_type( + test_size=self.validation_fraction, random_state=self.random_state + ) + idx_train, idx_val = next(cv.split(np.zeros(shape=(y.shape[0], 1)), y)) + + if not np.any(sample_mask[idx_val]): + raise ValueError( + "The sample weights for validation set are all zero, consider using a" + " different random state." + ) + + if idx_train.shape[0] == 0 or idx_val.shape[0] == 0: + raise ValueError( + "Splitting %d samples into a train set and a validation set " + "with validation_fraction=%r led to an empty set (%d and %d " + "samples). Please either change validation_fraction, increase " + "number of samples, or disable early_stopping." + % ( + n_samples, + self.validation_fraction, + idx_train.shape[0], + idx_val.shape[0], + ) + ) + + validation_mask[idx_val] = True + return validation_mask + + def _make_validation_score_cb( + self, validation_mask, X, y, sample_weight, classes=None + ): + if not self.early_stopping: + return None + + return _ValidationScoreCallback( + self, + X[validation_mask], + y[validation_mask], + sample_weight[validation_mask], + classes=classes, + ) + + +def _prepare_fit_binary(est, y, i, input_dtype, label_encode=True): + """Initialization for fit_binary. + + Returns y, coef, intercept, average_coef, average_intercept. + """ + y_i = np.ones(y.shape, dtype=input_dtype, order="C") + if label_encode: + # y in {0, 1} + y_i[y != est.classes_[i]] = 0.0 + else: + # y in {-1, +1} + y_i[y != est.classes_[i]] = -1.0 + average_intercept = 0 + average_coef = None + + if len(est.classes_) == 2: + if not est.average: + coef = est.coef_.ravel() + intercept = est.intercept_[0] + else: + coef = est._standard_coef.ravel() + intercept = est._standard_intercept[0] + average_coef = est._average_coef.ravel() + average_intercept = est._average_intercept[0] + else: + if not est.average: + coef = est.coef_[i] + intercept = est.intercept_[i] + else: + coef = est._standard_coef[i] + intercept = est._standard_intercept[i] + average_coef = est._average_coef[i] + average_intercept = est._average_intercept[i] + + return y_i, coef, intercept, average_coef, average_intercept + + +def fit_binary( + est, + i, + X, + y, + alpha, + C, + learning_rate, + max_iter, + pos_weight, + neg_weight, + sample_weight, + validation_mask=None, + random_state=None, +): + """Fit a single binary classifier. + + The i'th class is considered the "positive" class. + + Parameters + ---------- + est : Estimator object + The estimator to fit + + i : int + Index of the positive class + + X : numpy array or sparse matrix of shape [n_samples,n_features] + Training data + + y : numpy array of shape [n_samples, ] + Target values + + alpha : float + The regularization parameter + + C : float + Maximum step size for passive aggressive + + learning_rate : str + The learning rate. Accepted values are 'constant', 'optimal', + 'invscaling', 'pa1' and 'pa2'. + + max_iter : int + The maximum number of iterations (epochs) + + pos_weight : float + The weight of the positive class + + neg_weight : float + The weight of the negative class + + sample_weight : numpy array of shape [n_samples, ] + The weight of each sample + + validation_mask : numpy array of shape [n_samples, ], default=None + Precomputed validation mask in case _fit_binary is called in the + context of a one-vs-rest reduction. + + random_state : int, RandomState instance, default=None + 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`. + """ + # if average is not true, average_coef, and average_intercept will be + # unused + label_encode = isinstance(est._loss_function_, CyHalfBinomialLoss) + y_i, coef, intercept, average_coef, average_intercept = _prepare_fit_binary( + est, y, i, input_dtype=X.dtype, label_encode=label_encode + ) + assert y_i.shape[0] == y.shape[0] == sample_weight.shape[0] + + random_state = check_random_state(random_state) + dataset, intercept_decay = make_dataset( + X, y_i, sample_weight, random_state=random_state + ) + + penalty_type = est._get_penalty_type(est.penalty) + learning_rate_type = est._get_learning_rate_type(learning_rate) + + if validation_mask is None: + validation_mask = est._make_validation_split(y_i, sample_mask=sample_weight > 0) + classes = np.array([-1, 1], dtype=y_i.dtype) + validation_score_cb = est._make_validation_score_cb( + validation_mask, X, y_i, sample_weight, classes=classes + ) + + # numpy mtrand expects a C long which is a signed 32 bit integer under + # Windows + seed = random_state.randint(MAX_INT) + + tol = est.tol if est.tol is not None else -np.inf + + _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) + coef, intercept, average_coef, average_intercept, n_iter_ = _plain_sgd( + coef, + intercept, + average_coef, + average_intercept, + est._loss_function_, + penalty_type, + alpha, + C, + est._get_l1_ratio(), + dataset, + validation_mask, + 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, + 0, + est.t_, + intercept_decay, + est.average, + ) + + if est.average: + if len(est.classes_) == 2: + est._average_intercept[0] = average_intercept + else: + est._average_intercept[i] = average_intercept + + return coef, intercept, n_iter_ + + +def _get_plain_sgd_function(input_dtype): + return _plain_sgd32 if input_dtype == np.float32 else _plain_sgd64 + + +class BaseSGDClassifier(LinearClassifierMixin, BaseSGD, metaclass=ABCMeta): + loss_functions = { + "hinge": (Hinge, 1.0), + "squared_hinge": (SquaredHinge, 1.0), + "perceptron": (Hinge, 0.0), + "log_loss": (CyHalfBinomialLoss,), + "modified_huber": (ModifiedHuber,), + "squared_error": (CyHalfSquaredError,), + "huber": (CyHuberLoss, DEFAULT_EPSILON), + "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), + "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), + } + + _parameter_constraints: dict = { + **BaseSGD._parameter_constraints, + "loss": [StrOptions(set(loss_functions))], + "early_stopping": ["boolean"], + "validation_fraction": [Interval(Real, 0, 1, closed="neither")], + "n_iter_no_change": [Interval(Integral, 1, None, closed="left")], + "n_jobs": [Integral, None], + "class_weight": [StrOptions({"balanced"}), dict, None], + } + + @abstractmethod + def __init__( + self, + loss="hinge", + *, + penalty="l2", + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + epsilon=DEFAULT_EPSILON, + n_jobs=None, + random_state=None, + learning_rate="optimal", + eta0=0.0, + power_t=0.5, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + class_weight=None, + warm_start=False, + average=False, + ): + super().__init__( + loss=loss, + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, + power_t=power_t, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + warm_start=warm_start, + average=average, + ) + self.class_weight = class_weight + self.n_jobs = n_jobs + + def _partial_fit( + self, + X, + y, + alpha, + C, + loss, + learning_rate, + max_iter, + classes, + sample_weight, + coef_init, + intercept_init, + ): + first_call = not hasattr(self, "classes_") + X, y = validate_data( + self, + X, + y, + accept_sparse="csr", + dtype=[np.float64, np.float32], + order="C", + accept_large_sparse=False, + reset=first_call, + ) + + n_samples, n_features = X.shape + + _check_partial_fit_first_call(self, classes) + + n_classes = self.classes_.shape[0] + + # Allocate datastructures from input arguments + self._expanded_class_weight = compute_class_weight( + self.class_weight, classes=self.classes_, y=y + ) + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + if getattr(self, "coef_", None) is None or coef_init is not None: + self._allocate_parameter_mem( + n_classes=n_classes, + n_features=n_features, + input_dtype=X.dtype, + coef_init=coef_init, + intercept_init=intercept_init, + ) + 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]) + ) + + self._loss_function_ = self._get_loss_function(loss) + if not hasattr(self, "t_"): + self.t_ = 1.0 + + # delegate to concrete training procedure + if n_classes > 2: + self._fit_multiclass( + X, + y, + alpha=alpha, + C=C, + learning_rate=learning_rate, + sample_weight=sample_weight, + max_iter=max_iter, + ) + elif n_classes == 2: + self._fit_binary( + X, + y, + alpha=alpha, + C=C, + learning_rate=learning_rate, + sample_weight=sample_weight, + max_iter=max_iter, + ) + else: + raise ValueError( + "The number of classes has to be greater than one; got %d class" + % n_classes + ) + + return self + + def _fit( + self, + X, + y, + alpha, + C, + loss, + learning_rate, + coef_init=None, + intercept_init=None, + sample_weight=None, + ): + if hasattr(self, "classes_"): + # delete the attribute otherwise _partial_fit thinks it's not the first call + delattr(self, "classes_") + + # labels can be encoded as float, int, or string literals + # np.unique sorts in asc order; largest class id is positive class + y = validate_data(self, y=y) + classes = np.unique(y) + + if self.warm_start and hasattr(self, "coef_"): + if coef_init is None: + coef_init = self.coef_ + if intercept_init is None: + intercept_init = self.intercept_ + else: + self.coef_ = None + self.intercept_ = None + + if self.average > 0: + self._standard_coef = self.coef_ + self._standard_intercept = self.intercept_ + self._average_coef = None + self._average_intercept = None + + # Clear iteration count for multiple call to fit. + self.t_ = 1.0 + + self._partial_fit( + X, + y, + alpha, + C, + loss, + learning_rate, + self.max_iter, + classes, + sample_weight, + coef_init, + intercept_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_binary(self, X, y, alpha, C, sample_weight, learning_rate, max_iter): + """Fit a binary classifier on X and y.""" + coef, intercept, n_iter_ = fit_binary( + self, + 1, + X, + y, + alpha, + C, + learning_rate, + max_iter, + self._expanded_class_weight[1], + self._expanded_class_weight[0], + sample_weight, + random_state=self.random_state, + ) + + self.t_ += n_iter_ * X.shape[0] + self.n_iter_ = n_iter_ + + # need to be 2d + if self.average > 0: + if self.average <= self.t_ - 1: + self.coef_ = self._average_coef.reshape(1, -1) + self.intercept_ = self._average_intercept + else: + self.coef_ = self._standard_coef.reshape(1, -1) + self._standard_intercept = np.atleast_1d(intercept) + self.intercept_ = self._standard_intercept + else: + self.coef_ = coef.reshape(1, -1) + # intercept is a float, need to convert it to an array of length 1 + self.intercept_ = np.atleast_1d(intercept) + + def _fit_multiclass(self, X, y, alpha, C, learning_rate, sample_weight, max_iter): + """Fit a multi-class classifier by combining binary classifiers + + Each binary classifier predicts one class versus all others. This + strategy is called OvA (One versus All) or OvR (One versus Rest). + """ + # Precompute the validation split using the multiclass labels + # to ensure proper balancing of the classes. + validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0) + + # Use joblib to fit OvA in parallel. + # Pick the random seed for each job outside of fit_binary to avoid + # sharing the estimator random state between threads which could lead + # to non-deterministic behavior + random_state = check_random_state(self.random_state) + seeds = random_state.randint(MAX_INT, size=len(self.classes_)) + result = Parallel( + n_jobs=self.n_jobs, verbose=self.verbose, require="sharedmem" + )( + delayed(fit_binary)( + self, + i, + X, + y, + alpha, + C, + learning_rate, + max_iter, + self._expanded_class_weight[i], + 1.0, + sample_weight, + validation_mask=validation_mask, + random_state=seed, + ) + for i, seed in enumerate(seeds) + ) + + # take the maximum of n_iter_ over every binary fit + n_iter_ = 0.0 + for i, (_, intercept, n_iter_i) in enumerate(result): + self.intercept_[i] = intercept + n_iter_ = max(n_iter_, n_iter_i) + + self.t_ += n_iter_ * X.shape[0] + self.n_iter_ = n_iter_ + + if self.average > 0: + if self.average <= self.t_ - 1.0: + self.coef_ = self._average_coef + self.intercept_ = self._average_intercept + else: + self.coef_ = self._standard_coef + self._standard_intercept = np.atleast_1d(self.intercept_) + self.intercept_ = self._standard_intercept + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, classes=None, sample_weight=None): + """Perform one epoch of stochastic gradient descent on given samples. + + Internally, this method uses ``max_iter = 1``. Therefore, it is not + guaranteed that a minimum of the cost function is reached after calling + it once. Matters such as objective convergence, early stopping, and + learning rate adjustments should be handled by the user. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Subset of the training data. + + y : ndarray of shape (n_samples,) + Subset of the target values. + + classes : ndarray of shape (n_classes,), default=None + Classes across all calls to partial_fit. + Can be obtained by via `np.unique(y_all)`, where y_all is the + target vector of the entire dataset. + This argument is required for the first call to partial_fit + and can be omitted in the subsequent calls. + Note that y doesn't need to contain all labels in `classes`. + + sample_weight : array-like, shape (n_samples,), default=None + Weights applied to individual samples. + If not provided, uniform weights are assumed. + + Returns + ------- + self : object + Returns an instance of self. + """ + if not hasattr(self, "classes_"): + self._more_validate_params(for_partial_fit=True) + + if self.class_weight == "balanced": + raise ValueError( + "class_weight '{0}' is not supported for " + "partial_fit. In order to use 'balanced' weights," + " use compute_class_weight('{0}', " + "classes=classes, y=y). " + "In place of y you can use a large enough sample " + "of the full training set target to properly " + "estimate the class frequency distributions. " + "Pass the resulting weights as the class_weight " + "parameter.".format(self.class_weight) + ) + + return self._partial_fit( + X, + y, + alpha=self.alpha, + C=1.0, + loss=self.loss, + learning_rate=self.learning_rate, + max_iter=1, + classes=classes, + sample_weight=sample_weight, + coef_init=None, + intercept_init=None, + ) + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): + """Fit linear model with Stochastic Gradient Descent. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + coef_init : ndarray of shape (n_classes, n_features), default=None + The initial coefficients to warm-start the optimization. + + intercept_init : ndarray of shape (n_classes,), default=None + The initial intercept to warm-start the optimization. + + sample_weight : array-like, shape (n_samples,), default=None + 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 : object + Returns an instance of self. + """ + self._more_validate_params() + + return self._fit( + X, + y, + alpha=self.alpha, + C=1.0, + loss=self.loss, + learning_rate=self.learning_rate, + coef_init=coef_init, + intercept_init=intercept_init, + sample_weight=sample_weight, + ) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class SGDClassifier(BaseSGDClassifier): + """Linear classifiers (SVM, logistic regression, etc.) with SGD training. + + This estimator implements regularized linear models with stochastic + gradient descent (SGD) learning: the gradient of the loss is estimated + each sample at a time and the model is updated along the way with a + decreasing strength schedule (aka learning rate). SGD allows minibatch + (online/out-of-core) learning via the `partial_fit` method. + For best results using the default learning rate schedule, the data should + have zero mean and unit variance. + + This implementation works with data represented as dense or sparse arrays + of floating point values for the features. The model it fits can be + controlled with the loss parameter; by default, it fits a linear support + vector machine (SVM). + + The regularizer is a penalty added to the loss function that shrinks model + parameters towards the zero vector using either the squared euclidean norm + L2 or the absolute norm L1 or a combination of both (Elastic Net). If the + parameter update crosses the 0.0 value because of the regularizer, the + update is truncated to 0.0 to allow for learning sparse models and achieve + online feature selection. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + loss : {'hinge', 'log_loss', 'modified_huber', 'squared_hinge',\ + 'perceptron', 'squared_error', 'huber', 'epsilon_insensitive',\ + 'squared_epsilon_insensitive'}, default='hinge' + The loss function to be used. + + - 'hinge' gives a linear SVM. + - 'log_loss' gives logistic regression, a probabilistic classifier. + - 'modified_huber' is another smooth loss that brings tolerance to + outliers as well as probability estimates. + - 'squared_hinge' is like hinge but is quadratically penalized. + - 'perceptron' is the linear loss used by the perceptron algorithm. + - The other losses, 'squared_error', 'huber', 'epsilon_insensitive' and + 'squared_epsilon_insensitive' are designed for regression but can be useful + in classification as well; see + :class:`~sklearn.linear_model.SGDRegressor` for a description. + + More details about the losses formulas can be found in the :ref:`User Guide + ` and you can find a visualisation of the loss + functions in + :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_loss_functions.py`. + + penalty : {'l2', 'l1', 'elasticnet', None}, default='l2' + The penalty (aka regularization term) to be used. Defaults to 'l2' + which is the standard regularizer for linear SVM models. 'l1' and + 'elasticnet' might bring sparsity to the model (feature selection) + not achievable with 'l2'. No penalty is added when set to `None`. + + You can see a visualisation of the penalties in + :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_penalties.py`. + + alpha : float, default=0.0001 + Constant that multiplies the regularization term. The higher the + value, the stronger the regularization. Also used to compute the + learning rate when `learning_rate` is set to 'optimal'. + Values must be in the range `[0.0, inf)`. + + l1_ratio : float, default=0.15 + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + Only used if `penalty` is 'elasticnet'. + Values must be in the range `[0.0, 1.0]` or can be `None` if + `penalty` is not `elasticnet`. + + .. versionchanged:: 1.7 + `l1_ratio` can be `None` when `penalty` is not "elasticnet". + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`partial_fit` method. + Values must be in the range `[1, inf)`. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, training will stop + when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive + epochs. + Convergence is checked against the training loss or the + validation loss depending on the `early_stopping` parameter. + Values must be in the range `[0.0, inf)`. + + .. versionadded:: 0.19 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + Values must be in the range `[0, inf)`. + + epsilon : float, default=0.1 + Epsilon in the epsilon-insensitive loss functions; only if `loss` is + 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. + For 'huber', determines the threshold at which it becomes less + important to get the prediction exactly right. + For epsilon-insensitive, any differences between the current prediction + and the correct label are ignored if they are less than this threshold. + Values must be in the range `[0.0, inf)`. + + n_jobs : int, default=None + The number of CPUs to use to do the OVA (One Versus All, for + multi-class problems) computation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance, default=None + Used for shuffling the data, when ``shuffle`` is set to ``True``. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + Integer values must be in the range `[0, 2**32 - 1]`. + + learning_rate : str, default='optimal' + The learning rate schedule: + + - 'constant': `eta = eta0` + - 'optimal': `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. + + .. versionadded:: 0.20 + Added 'adaptive' option. + + eta0 : float, default=0.0 + 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'. + Values must be in the range `[0.0, inf)`. + + power_t : float, default=0.5 + The exponent for inverse scaling learning rate. + Values must be in the range `(-inf, inf)`. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to `True`, it will automatically set aside + a stratified fraction of training data as validation and terminate + training when validation score returned by the `score` method is not + improving by at least tol for n_iter_no_change consecutive epochs. + + See :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_early_stopping.py` for an + example of the effects of early stopping. + + .. versionadded:: 0.20 + Added 'early_stopping' option + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if `early_stopping` is True. + Values must be in the range `(0.0, 1.0)`. + + .. versionadded:: 0.20 + Added 'validation_fraction' option + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before stopping + fitting. + Convergence is checked against the training loss or the + validation loss depending on the `early_stopping` parameter. + Integer values must be in the range `[1, max_iter)`. + + .. versionadded:: 0.20 + Added 'n_iter_no_change' option + + class_weight : dict, {class_label: weight} or "balanced", default=None + Preset for the class_weight fit parameter. + + Weights associated with classes. If not given, all classes + are supposed to have weight one. + + The "balanced" mode uses the values of y to automatically adjust + weights inversely proportional to class frequencies in the input data + as ``n_samples / (n_classes * np.bincount(y))``. + + warm_start : bool, default=False + 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 `. + + 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, default=False + When set to `True`, computes the averaged SGD weights across all + updates 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. + Integer values must be in the range `[1, n_samples]`. + + Attributes + ---------- + coef_ : ndarray of shape (1, n_features) if n_classes == 2 else \ + (n_classes, n_features) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) if n_classes == 2 else (n_classes,) + Constants in decision function. + + n_iter_ : int + The actual number of iterations before reaching the stopping criterion. + For multiclass fits, it is the maximum over every binary fit. + + classes_ : array of shape (n_classes,) + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.svm.LinearSVC : Linear support vector classification. + LogisticRegression : Logistic regression. + Perceptron : Inherits from SGDClassifier. ``Perceptron()`` is equivalent to + ``SGDClassifier(loss="perceptron", eta0=1, learning_rate="constant", + penalty=None)``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.linear_model import SGDClassifier + >>> from sklearn.preprocessing import StandardScaler + >>> from sklearn.pipeline import make_pipeline + >>> X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) + >>> Y = np.array([1, 1, 2, 2]) + >>> # Always scale the input. The most convenient way is to use a pipeline. + >>> clf = make_pipeline(StandardScaler(), + ... SGDClassifier(max_iter=1000, tol=1e-3)) + >>> clf.fit(X, Y) + Pipeline(steps=[('standardscaler', StandardScaler()), + ('sgdclassifier', SGDClassifier())]) + >>> print(clf.predict([[-0.8, -1]])) + [1] + """ + + _parameter_constraints: dict = { + **BaseSGDClassifier._parameter_constraints, + "penalty": [StrOptions({"l2", "l1", "elasticnet"}), None], + "alpha": [Interval(Real, 0, None, closed="left")], + "l1_ratio": [Interval(Real, 0, 1, closed="both"), None], + "power_t": [Interval(Real, None, None, closed="neither")], + "epsilon": [Interval(Real, 0, None, closed="left")], + "learning_rate": [ + StrOptions({"constant", "optimal", "invscaling", "adaptive"}), + Hidden(StrOptions({"pa1", "pa2"})), + ], + "eta0": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + loss="hinge", + *, + penalty="l2", + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + epsilon=DEFAULT_EPSILON, + n_jobs=None, + random_state=None, + learning_rate="optimal", + eta0=0.0, + power_t=0.5, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + class_weight=None, + warm_start=False, + average=False, + ): + super().__init__( + loss=loss, + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + n_jobs=n_jobs, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, + power_t=power_t, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + class_weight=class_weight, + warm_start=warm_start, + average=average, + ) + + def _check_proba(self): + if self.loss not in ("log_loss", "modified_huber"): + raise AttributeError( + "probability estimates are not available for loss=%r" % self.loss + ) + return True + + @available_if(_check_proba) + def predict_proba(self, X): + """Probability estimates. + + This method is only available for log loss and modified Huber loss. + + Multiclass probability estimates are derived from binary (one-vs.-rest) + estimates by simple normalization, as recommended by Zadrozny and + Elkan. + + Binary probability estimates for loss="modified_huber" are given by + (clip(decision_function(X), -1, 1) + 1) / 2. For other loss functions + it is necessary to perform proper probability calibration by wrapping + the classifier with + :class:`~sklearn.calibration.CalibratedClassifierCV` instead. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data for prediction. + + Returns + ------- + ndarray of shape (n_samples, n_classes) + Returns the probability of the sample for each class in the model, + where classes are ordered as they are in `self.classes_`. + + References + ---------- + Zadrozny and Elkan, "Transforming classifier scores into multiclass + probability estimates", SIGKDD'02, + https://dl.acm.org/doi/pdf/10.1145/775047.775151 + + The justification for the formula in the loss="modified_huber" + case is in the appendix B in: + http://jmlr.csail.mit.edu/papers/volume2/zhang02c/zhang02c.pdf + """ + check_is_fitted(self) + + if self.loss == "log_loss": + return self._predict_proba_lr(X) + + elif self.loss == "modified_huber": + binary = len(self.classes_) == 2 + scores = self.decision_function(X) + + if binary: + prob2 = np.ones((scores.shape[0], 2)) + prob = prob2[:, 1] + else: + prob = scores + + np.clip(scores, -1, 1, prob) + prob += 1.0 + prob /= 2.0 + + if binary: + prob2[:, 0] -= prob + prob = prob2 + else: + # the above might assign zero to all classes, which doesn't + # normalize neatly; work around this to produce uniform + # probabilities + prob_sum = prob.sum(axis=1) + all_zero = prob_sum == 0 + if np.any(all_zero): + prob[all_zero, :] = 1 + prob_sum[all_zero] = len(self.classes_) + + # normalize + prob /= prob_sum.reshape((prob.shape[0], -1)) + + return prob + + else: + raise NotImplementedError( + "predict_(log_)proba only supported when" + " loss='log_loss' or loss='modified_huber' " + "(%r given)" % self.loss + ) + + @available_if(_check_proba) + def predict_log_proba(self, X): + """Log of probability estimates. + + This method is only available for log loss and modified Huber loss. + + When loss="modified_huber", probability estimates may be hard zeros + and ones, so taking the logarithm is not possible. + + See ``predict_proba`` for details. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data for prediction. + + Returns + ------- + T : array-like, shape (n_samples, n_classes) + Returns the log-probability of the sample for each class in the + model, where classes are ordered as they are in + `self.classes_`. + """ + return np.log(self.predict_proba(X)) + + +class BaseSGDRegressor(RegressorMixin, BaseSGD): + loss_functions = { + "squared_error": (CyHalfSquaredError,), + "huber": (CyHuberLoss, DEFAULT_EPSILON), + "epsilon_insensitive": (EpsilonInsensitive, DEFAULT_EPSILON), + "squared_epsilon_insensitive": (SquaredEpsilonInsensitive, DEFAULT_EPSILON), + } + + _parameter_constraints: dict = { + **BaseSGD._parameter_constraints, + "loss": [StrOptions(set(loss_functions))], + "early_stopping": ["boolean"], + "validation_fraction": [Interval(Real, 0, 1, closed="neither")], + "n_iter_no_change": [Interval(Integral, 1, None, closed="left")], + } + + @abstractmethod + def __init__( + self, + loss="squared_error", + *, + penalty="l2", + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + epsilon=DEFAULT_EPSILON, + random_state=None, + learning_rate="invscaling", + eta0=0.01, + power_t=0.25, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + warm_start=False, + average=False, + ): + super().__init__( + loss=loss, + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, + power_t=power_t, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + warm_start=warm_start, + average=average, + ) + + def _partial_fit( + self, + X, + y, + alpha, + C, + loss, + learning_rate, + max_iter, + sample_weight, + coef_init, + intercept_init, + ): + first_call = getattr(self, "coef_", None) is None + X, y = validate_data( + self, + X, + y, + accept_sparse="csr", + copy=False, + order="C", + dtype=[np.float64, np.float32], + accept_large_sparse=False, + reset=first_call, + ) + y = y.astype(X.dtype, copy=False) + + n_samples, n_features = X.shape + + sample_weight = _check_sample_weight(sample_weight, X, dtype=X.dtype) + + # Allocate datastructures from input arguments + if first_call: + self._allocate_parameter_mem( + n_classes=1, + n_features=n_features, + input_dtype=X.dtype, + coef_init=coef_init, + intercept_init=intercept_init, + ) + if self.average > 0 and getattr(self, "_average_coef", None) is None: + self._average_coef = np.zeros(n_features, dtype=X.dtype, order="C") + self._average_intercept = np.zeros(1, dtype=X.dtype, order="C") + + self._fit_regressor( + X, y, alpha, C, loss, learning_rate, sample_weight, max_iter + ) + + return self + + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, sample_weight=None): + """Perform one epoch of stochastic gradient descent on given samples. + + Internally, this method uses ``max_iter = 1``. Therefore, it is not + guaranteed that a minimum of the cost function is reached after calling + it once. Matters such as objective convergence and early stopping + should be handled by the user. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Subset of training data. + + y : numpy array of shape (n_samples,) + Subset of target values. + + sample_weight : array-like, shape (n_samples,), default=None + Weights applied to individual samples. + If not provided, uniform weights are assumed. + + Returns + ------- + self : object + Returns an instance of self. + """ + if not hasattr(self, "coef_"): + self._more_validate_params(for_partial_fit=True) + + return self._partial_fit( + X, + y, + self.alpha, + C=1.0, + loss=self.loss, + learning_rate=self.learning_rate, + max_iter=1, + sample_weight=sample_weight, + coef_init=None, + intercept_init=None, + ) + + def _fit( + self, + X, + y, + alpha, + C, + loss, + learning_rate, + coef_init=None, + intercept_init=None, + sample_weight=None, + ): + if self.warm_start and getattr(self, "coef_", None) is not None: + if coef_init is None: + coef_init = self.coef_ + if intercept_init is None: + intercept_init = self.intercept_ + else: + self.coef_ = None + self.intercept_ = None + + # Clear iteration count for multiple call to fit. + self.t_ = 1.0 + + self._partial_fit( + X, + y, + alpha, + C, + loss, + learning_rate, + self.max_iter, + sample_weight, + coef_init, + intercept_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 + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, coef_init=None, intercept_init=None, sample_weight=None): + """Fit linear model with Stochastic Gradient Descent. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + + y : ndarray of shape (n_samples,) + Target values. + + coef_init : ndarray of shape (n_features,), default=None + The initial coefficients to warm-start the optimization. + + intercept_init : ndarray of shape (1,), default=None + The initial intercept to warm-start the optimization. + + sample_weight : array-like, shape (n_samples,), default=None + Weights applied to individual samples (1. for unweighted). + + Returns + ------- + self : object + Fitted `SGDRegressor` estimator. + """ + self._more_validate_params() + + return self._fit( + X, + y, + alpha=self.alpha, + C=1.0, + loss=self.loss, + learning_rate=self.learning_rate, + coef_init=coef_init, + intercept_init=intercept_init, + sample_weight=sample_weight, + ) + + def _decision_function(self, X): + """Predict using the linear model + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + + Returns + ------- + ndarray of shape (n_samples,) + Predicted target values per element in X. + """ + check_is_fitted(self) + + X = validate_data(self, X, accept_sparse="csr", reset=False) + + scores = safe_sparse_dot(X, self.coef_.T, dense_output=True) + self.intercept_ + return scores.ravel() + + def predict(self, X): + """Predict using the linear model. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Input data. + + Returns + ------- + ndarray of shape (n_samples,) + Predicted target values per element in X. + """ + return self._decision_function(X) + + def _fit_regressor( + self, X, y, alpha, C, loss, learning_rate, sample_weight, max_iter + ): + loss_function = self._get_loss_function(loss) + penalty_type = self._get_penalty_type(self.penalty) + learning_rate_type = self._get_learning_rate_type(learning_rate) + + if not hasattr(self, "t_"): + self.t_ = 1.0 + + validation_mask = self._make_validation_split(y, sample_mask=sample_weight > 0) + 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, MAX_INT) + + dataset, intercept_decay = make_dataset( + X, y, sample_weight, random_state=random_state + ) + + tol = self.tol if self.tol is not None else -np.inf + + 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 = self.intercept_ + average_coef = None # Not used + average_intercept = [0] # Not used + + _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) + coef, intercept, average_coef, average_intercept, self.n_iter_ = _plain_sgd( + coef, + intercept[0], + average_coef, + average_intercept[0], + loss_function, + penalty_type, + alpha, + C, + self._get_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, + 1.0, + 1.0, + learning_rate_type, + self.eta0, + self.power_t, + 0, + self.t_, + intercept_decay, + self.average, + ) + + self.t_ += self.n_iter_ * X.shape[0] + + 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.intercept_ = np.atleast_1d(average_intercept) + else: + self.coef_ = coef + self.intercept_ = np.atleast_1d(intercept) + + else: + self.intercept_ = np.atleast_1d(intercept) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class SGDRegressor(BaseSGDRegressor): + """Linear model fitted by minimizing a regularized empirical loss with SGD. + + SGD stands for Stochastic Gradient Descent: the gradient of the loss is + estimated each sample at a time and the model is updated along the way with + a decreasing strength schedule (aka learning rate). + + The regularizer is a penalty added to the loss function that shrinks model + parameters towards the zero vector using either the squared euclidean norm + L2 or the absolute norm L1 or a combination of both (Elastic Net). If the + parameter update crosses the 0.0 value because of the regularizer, the + update is truncated to 0.0 to allow for learning sparse models and achieve + online feature selection. + + This implementation works with data represented as dense numpy arrays of + floating point values for the features. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + loss : str, default='squared_error' + The loss function to be used. The possible values are 'squared_error', + 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive' + + The 'squared_error' refers to the ordinary least squares fit. + 'huber' modifies 'squared_error' to focus less on getting outliers + correct by switching from squared to linear loss past a distance of + epsilon. 'epsilon_insensitive' ignores errors less than epsilon and is + linear past that; this is the loss function used in SVR. + 'squared_epsilon_insensitive' is the same but becomes squared loss past + a tolerance of epsilon. + + More details about the losses formulas can be found in the + :ref:`User Guide `. + + penalty : {'l2', 'l1', 'elasticnet', None}, default='l2' + The penalty (aka regularization term) to be used. Defaults to 'l2' + which is the standard regularizer for linear SVM models. 'l1' and + 'elasticnet' might bring sparsity to the model (feature selection) + not achievable with 'l2'. No penalty is added when set to `None`. + + You can see a visualisation of the penalties in + :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_penalties.py`. + + alpha : float, default=0.0001 + Constant that multiplies the regularization term. The higher the + value, the stronger the regularization. Also used to compute the + learning rate when `learning_rate` is set to 'optimal'. + Values must be in the range `[0.0, inf)`. + + l1_ratio : float, default=0.15 + The Elastic Net mixing parameter, with 0 <= l1_ratio <= 1. + l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1. + Only used if `penalty` is 'elasticnet'. + Values must be in the range `[0.0, 1.0]` or can be `None` if + `penalty` is not `elasticnet`. + + .. versionchanged:: 1.7 + `l1_ratio` can be `None` when `penalty` is not "elasticnet". + + fit_intercept : bool, default=True + Whether the intercept should be estimated or not. If False, the + data is assumed to be already centered. + + max_iter : int, default=1000 + The maximum number of passes over the training data (aka epochs). + It only impacts the behavior in the ``fit`` method, and not the + :meth:`partial_fit` method. + Values must be in the range `[1, inf)`. + + .. versionadded:: 0.19 + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, training will stop + when (loss > best_loss - tol) for ``n_iter_no_change`` consecutive + epochs. + Convergence is checked against the training loss or the + validation loss depending on the `early_stopping` parameter. + Values must be in the range `[0.0, inf)`. + + .. versionadded:: 0.19 + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + + verbose : int, default=0 + The verbosity level. + Values must be in the range `[0, inf)`. + + epsilon : float, default=0.1 + Epsilon in the epsilon-insensitive loss functions; only if `loss` is + 'huber', 'epsilon_insensitive', or 'squared_epsilon_insensitive'. + For 'huber', determines the threshold at which it becomes less + important to get the prediction exactly right. + For epsilon-insensitive, any differences between the current prediction + and the correct label are ignored if they are less than this threshold. + Values must be in the range `[0.0, inf)`. + + random_state : int, RandomState instance, default=None + Used for shuffling the data, when ``shuffle`` is set to ``True``. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + learning_rate : str, default='invscaling' + The learning rate schedule: + + - 'constant': `eta = eta0` + - 'optimal': `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. + + .. versionadded:: 0.20 + Added 'adaptive' option. + + eta0 : float, default=0.01 + The initial learning rate for the 'constant', 'invscaling' or + 'adaptive' schedules. The default value is 0.01. + Values must be in the range `[0.0, inf)`. + + power_t : float, default=0.25 + The exponent for inverse scaling learning rate. + Values must be in the range `(-inf, inf)`. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set aside + a fraction of training data as validation and terminate + training when validation score returned by the `score` method is not + improving by at least `tol` for `n_iter_no_change` consecutive + epochs. + + See :ref:`sphx_glr_auto_examples_linear_model_plot_sgd_early_stopping.py` for an + example of the effects of early stopping. + + .. versionadded:: 0.20 + Added 'early_stopping' option + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if `early_stopping` is True. + Values must be in the range `(0.0, 1.0)`. + + .. versionadded:: 0.20 + Added 'validation_fraction' option + + n_iter_no_change : int, default=5 + Number of iterations with no improvement to wait before stopping + fitting. + Convergence is checked against the training loss or the + validation loss depending on the `early_stopping` parameter. + Integer values must be in the range `[1, max_iter)`. + + .. versionadded:: 0.20 + Added 'n_iter_no_change' option + + warm_start : bool, default=False + 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 `. + + 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, default=False + When set to True, computes the averaged SGD weights across all + updates 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_ : ndarray of shape (n_features,) + Weights assigned to the features. + + intercept_ : ndarray of shape (1,) + The intercept term. + + n_iter_ : int + The actual number of iterations before reaching the stopping criterion. + + t_ : int + Number of weight updates performed during training. + Same as ``(n_iter_ * n_samples + 1)``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + HuberRegressor : Linear regression model that is robust to outliers. + Lars : Least Angle Regression model. + Lasso : Linear Model trained with L1 prior as regularizer. + RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm. + Ridge : Linear least squares with l2 regularization. + sklearn.svm.SVR : Epsilon-Support Vector Regression. + TheilSenRegressor : Theil-Sen Estimator robust multivariate regression model. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.linear_model import SGDRegressor + >>> from sklearn.pipeline import make_pipeline + >>> from sklearn.preprocessing import StandardScaler + >>> n_samples, n_features = 10, 5 + >>> rng = np.random.RandomState(0) + >>> y = rng.randn(n_samples) + >>> X = rng.randn(n_samples, n_features) + >>> # Always scale the input. The most convenient way is to use a pipeline. + >>> reg = make_pipeline(StandardScaler(), + ... SGDRegressor(max_iter=1000, tol=1e-3)) + >>> reg.fit(X, y) + Pipeline(steps=[('standardscaler', StandardScaler()), + ('sgdregressor', SGDRegressor())]) + """ + + _parameter_constraints: dict = { + **BaseSGDRegressor._parameter_constraints, + "penalty": [StrOptions({"l2", "l1", "elasticnet"}), None], + "alpha": [Interval(Real, 0, None, closed="left")], + "l1_ratio": [Interval(Real, 0, 1, closed="both"), None], + "power_t": [Interval(Real, None, None, closed="neither")], + "learning_rate": [ + StrOptions({"constant", "optimal", "invscaling", "adaptive"}), + Hidden(StrOptions({"pa1", "pa2"})), + ], + "epsilon": [Interval(Real, 0, None, closed="left")], + "eta0": [Interval(Real, 0, None, closed="left")], + } + + def __init__( + self, + loss="squared_error", + *, + penalty="l2", + alpha=0.0001, + l1_ratio=0.15, + fit_intercept=True, + max_iter=1000, + tol=1e-3, + shuffle=True, + verbose=0, + epsilon=DEFAULT_EPSILON, + random_state=None, + learning_rate="invscaling", + eta0=0.01, + power_t=0.25, + early_stopping=False, + validation_fraction=0.1, + n_iter_no_change=5, + warm_start=False, + average=False, + ): + super().__init__( + loss=loss, + penalty=penalty, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=tol, + shuffle=shuffle, + verbose=verbose, + epsilon=epsilon, + random_state=random_state, + learning_rate=learning_rate, + eta0=eta0, + power_t=power_t, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + n_iter_no_change=n_iter_no_change, + warm_start=warm_start, + average=average, + ) + + +class SGDOneClassSVM(OutlierMixin, BaseSGD): + """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 `. + + .. versionadded:: 1.0 + + Parameters + ---------- + nu : float, default=0.5 + 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, default=True + Whether the intercept should be estimated or not. Defaults to True. + + max_iter : int, default=1000 + 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. + Values must be in the range `[1, inf)`. + + tol : float or None, default=1e-3 + The stopping criterion. If it is not None, the iterations will stop + when (loss > previous_loss - tol). Defaults to 1e-3. + Values must be in the range `[0.0, inf)`. + + shuffle : bool, default=True + Whether or not the training data should be shuffled after each epoch. + Defaults to True. + + verbose : int, default=0 + The verbosity level. + + random_state : int, RandomState instance or None, 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 : {'constant', 'optimal', 'invscaling', 'adaptive'}, default='optimal' + The learning rate schedule to use with `fit`. (If using `partial_fit`, + learning rate must be controlled directly). + + - 'constant': `eta = eta0` + - 'optimal': `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 : float, default=0.0 + 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'. + Values must be in the range `[0.0, inf)`. + + power_t : float, default=0.5 + The exponent for inverse scaling learning rate. + Values must be in the range `(-inf, inf)`. + + warm_start : bool, default=False + 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 `. + + 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, default=False + 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_ : ndarray of shape (1, n_features) + Weights assigned to the features. + + offset_ : ndarray of 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 + 1)``. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.svm.OneClassSVM : Unsupervised Outlier Detection. + + 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). + + 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] + """ + + loss_functions = {"hinge": (Hinge, 1.0)} + + _parameter_constraints: dict = { + **BaseSGD._parameter_constraints, + "nu": [Interval(Real, 0.0, 1.0, closed="right")], + "learning_rate": [ + StrOptions({"constant", "optimal", "invscaling", "adaptive"}), + Hidden(StrOptions({"pa1", "pa2"})), + ], + "eta0": [Interval(Real, 0, None, closed="left")], + "power_t": [Interval(Real, None, None, closed="neither")], + } + + 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, + ): + self.nu = nu + super().__init__( + loss="hinge", + penalty="l2", + 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 _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=X.dtype, 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, sample_mask=sample_weight > 0) + 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 + + _plain_sgd = _get_plain_sgd_function(input_dtype=coef.dtype) + 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 = validate_data( + self, + X, + None, + accept_sparse="csr", + dtype=[np.float64, np.float32], + 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, dtype=X.dtype) + + # 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( + n_classes=1, + n_features=n_features, + input_dtype=X.dtype, + coef_init=coef_init, + intercept_init=offset_init, + one_class=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=X.dtype, order="C") + self._average_intercept = np.zeros(1, dtype=X.dtype, 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 + + @_fit_context(prefer_skip_nested_validation=True) + 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. + y : Ignored + Not used, present for API consistency by convention. + + sample_weight : array-like, shape (n_samples,), optional + Weights applied to individual samples. + If not provided, uniform weights are assumed. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + if not hasattr(self, "coef_"): + self._more_validate_params(for_partial_fit=True) + + alpha = self.nu / 2 + 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, + ): + 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 + + @_fit_context(prefer_skip_nested_validation=True) + 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 + - rho. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_samples, n_features) + Training data. + y : Ignored + Not used, present for API consistency by convention. + + 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 : object + Returns a fitted instance of self. + """ + self._more_validate_params() + + 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 = validate_data(self, 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 __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_theil_sen.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_theil_sen.py new file mode 100644 index 0000000000000000000000000000000000000000..4b25145a8ca55efe3f99e80f24a8da6e4b1a9f50 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/_theil_sen.py @@ -0,0 +1,467 @@ +""" +A Theil-Sen Estimator for Multiple Linear Regression Model +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from itertools import combinations +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs +from scipy import linalg +from scipy.linalg.lapack import get_lapack_funcs +from scipy.special import binom + +from ..base import RegressorMixin, _fit_context +from ..exceptions import ConvergenceWarning +from ..utils import check_random_state +from ..utils._param_validation import Hidden, Interval, StrOptions +from ..utils.parallel import Parallel, delayed +from ..utils.validation import validate_data +from ._base import LinearModel + +_EPSILON = np.finfo(np.double).eps + + +def _modified_weiszfeld_step(X, x_old): + """Modified Weiszfeld step. + + This function defines one iteration step in order to approximate the + spatial median (L1 median). It is a form of an iteratively re-weighted + least squares method. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + x_old : ndarray of shape = (n_features,) + Current start vector. + + Returns + ------- + x_new : ndarray of shape (n_features,) + New iteration step. + + References + ---------- + - On Computation of Spatial Median for Robust Data Mining, 2005 + T. Kärkkäinen and S. Äyrämö + http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf + """ + diff = X - x_old + diff_norm = np.sqrt(np.sum(diff**2, axis=1)) + mask = diff_norm >= _EPSILON + # x_old equals one of our samples + is_x_old_in_X = int(mask.sum() < X.shape[0]) + + diff = diff[mask] + diff_norm = diff_norm[mask][:, np.newaxis] + quotient_norm = linalg.norm(np.sum(diff / diff_norm, axis=0)) + + if quotient_norm > _EPSILON: # to avoid division by zero + new_direction = np.sum(X[mask, :] / diff_norm, axis=0) / np.sum( + 1 / diff_norm, axis=0 + ) + else: + new_direction = 1.0 + quotient_norm = 1.0 + + return ( + max(0.0, 1.0 - is_x_old_in_X / quotient_norm) * new_direction + + min(1.0, is_x_old_in_X / quotient_norm) * x_old + ) + + +def _spatial_median(X, max_iter=300, tol=1.0e-3): + """Spatial median (L1 median). + + The spatial median is member of a class of so-called M-estimators which + are defined by an optimization problem. Given a number of p points in an + n-dimensional space, the point x minimizing the sum of all distances to the + p other points is called spatial median. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + max_iter : int, default=300 + Maximum number of iterations. + + tol : float, default=1.e-3 + Stop the algorithm if spatial_median has converged. + + Returns + ------- + spatial_median : ndarray of shape = (n_features,) + Spatial median. + + n_iter : int + Number of iterations needed. + + References + ---------- + - On Computation of Spatial Median for Robust Data Mining, 2005 + T. Kärkkäinen and S. Äyrämö + http://users.jyu.fi/~samiayr/pdf/ayramo_eurogen05.pdf + """ + if X.shape[1] == 1: + return 1, np.median(X.ravel(), keepdims=True) + + tol **= 2 # We are computing the tol on the squared norm + spatial_median_old = np.mean(X, axis=0) + + for n_iter in range(max_iter): + spatial_median = _modified_weiszfeld_step(X, spatial_median_old) + if np.sum((spatial_median_old - spatial_median) ** 2) < tol: + break + else: + spatial_median_old = spatial_median + else: + warnings.warn( + "Maximum number of iterations {max_iter} reached in " + "spatial median for TheilSen regressor." + "".format(max_iter=max_iter), + ConvergenceWarning, + ) + return n_iter, spatial_median + + +def _breakdown_point(n_samples, n_subsamples): + """Approximation of the breakdown point. + + Parameters + ---------- + n_samples : int + Number of samples. + + n_subsamples : int + Number of subsamples to consider. + + Returns + ------- + breakdown_point : float + Approximation of breakdown point. + """ + return ( + 1 + - ( + 0.5 ** (1 / n_subsamples) * (n_samples - n_subsamples + 1) + + n_subsamples + - 1 + ) + / n_samples + ) + + +def _lstsq(X, y, indices, fit_intercept): + """Least Squares Estimator for TheilSenRegressor class. + + This function calculates the least squares method on a subset of rows of X + and y defined by the indices array. Optionally, an intercept column is + added if intercept is set to true. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Design matrix, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : ndarray of shape (n_samples,) + Target vector, where `n_samples` is the number of samples. + + indices : ndarray of shape (n_subpopulation, n_subsamples) + Indices of all subsamples with respect to the chosen subpopulation. + + fit_intercept : bool + Fit intercept or not. + + Returns + ------- + weights : ndarray of shape (n_subpopulation, n_features + intercept) + Solution matrix of n_subpopulation solved least square problems. + """ + fit_intercept = int(fit_intercept) + n_features = X.shape[1] + fit_intercept + n_subsamples = indices.shape[1] + weights = np.empty((indices.shape[0], n_features)) + X_subpopulation = np.ones((n_subsamples, n_features)) + # gelss need to pad y_subpopulation to be of the max dim of X_subpopulation + y_subpopulation = np.zeros((max(n_subsamples, n_features))) + (lstsq,) = get_lapack_funcs(("gelss",), (X_subpopulation, y_subpopulation)) + + for index, subset in enumerate(indices): + X_subpopulation[:, fit_intercept:] = X[subset, :] + y_subpopulation[:n_subsamples] = y[subset] + weights[index] = lstsq(X_subpopulation, y_subpopulation)[1][:n_features] + + return weights + + +class TheilSenRegressor(RegressorMixin, LinearModel): + """Theil-Sen Estimator: robust multivariate regression model. + + The algorithm calculates least square solutions on subsets with size + n_subsamples of the samples in X. Any value of n_subsamples between the + number of features and samples leads to an estimator with a compromise + between robustness and efficiency. Since the number of least square + solutions is "n_samples choose n_subsamples", it can be extremely large + and can therefore be limited with max_subpopulation. If this limit is + reached, the subsets are chosen randomly. In a final step, the spatial + median (or L1 median) is calculated of all least square solutions. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + fit_intercept : bool, default=True + Whether to calculate the intercept for this model. If set + to false, no intercept will be used in calculations. + + copy_X : bool, default=True + If True, X will be copied; else, it may be overwritten. + + .. deprecated:: 1.6 + `copy_X` was deprecated in 1.6 and will be removed in 1.8. + It has no effect as a copy is always made. + + max_subpopulation : int, default=1e4 + Instead of computing with a set of cardinality 'n choose k', where n is + the number of samples and k is the number of subsamples (at least + number of features), consider only a stochastic subpopulation of a + given maximal size if 'n choose k' is larger than max_subpopulation. + For other than small problem sizes this parameter will determine + memory usage and runtime if n_subsamples is not changed. Note that the + data type should be int but floats such as 1e4 can be accepted too. + + n_subsamples : int, default=None + Number of samples to calculate the parameters. This is at least the + number of features (plus 1 if fit_intercept=True) and the number of + samples as a maximum. A lower number leads to a higher breakdown + point and a low efficiency while a high number leads to a low + breakdown point and a high efficiency. If None, take the + minimum number of subsamples leading to maximal robustness. + If n_subsamples is set to n_samples, Theil-Sen is identical to least + squares. + + max_iter : int, default=300 + Maximum number of iterations for the calculation of spatial median. + + tol : float, default=1e-3 + Tolerance when calculating spatial median. + + random_state : int, RandomState instance or None, default=None + A random number generator instance to define the state of the random + permutations generator. Pass an int for reproducible output across + multiple function calls. + See :term:`Glossary `. + + n_jobs : int, default=None + Number of CPUs to use during the cross validation. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : bool, default=False + Verbose mode when fitting the model. + + Attributes + ---------- + coef_ : ndarray of shape (n_features,) + Coefficients of the regression model (median of distribution). + + intercept_ : float + Estimated intercept of regression model. + + breakdown_ : float + Approximated breakdown point. + + n_iter_ : int + Number of iterations needed for the spatial median. + + n_subpopulation_ : int + Number of combinations taken into account from 'n choose k', where n is + the number of samples and k is the number of subsamples. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + HuberRegressor : Linear regression model that is robust to outliers. + RANSACRegressor : RANSAC (RANdom SAmple Consensus) algorithm. + SGDRegressor : Fitted by minimizing a regularized empirical loss with SGD. + + References + ---------- + - Theil-Sen Estimators in a Multiple Linear Regression Model, 2009 + Xin Dang, Hanxiang Peng, Xueqin Wang and Heping Zhang + http://home.olemiss.edu/~xdang/papers/MTSE.pdf + + Examples + -------- + >>> from sklearn.linear_model import TheilSenRegressor + >>> from sklearn.datasets import make_regression + >>> X, y = make_regression( + ... n_samples=200, n_features=2, noise=4.0, random_state=0) + >>> reg = TheilSenRegressor(random_state=0).fit(X, y) + >>> reg.score(X, y) + 0.9884 + >>> reg.predict(X[:1,]) + array([-31.5871]) + """ + + _parameter_constraints: dict = { + "fit_intercept": ["boolean"], + "copy_X": ["boolean", Hidden(StrOptions({"deprecated"}))], + # target_type should be Integral but can accept Real for backward compatibility + "max_subpopulation": [Interval(Real, 1, None, closed="left")], + "n_subsamples": [None, Integral], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "tol": [Interval(Real, 0.0, None, closed="left")], + "random_state": ["random_state"], + "n_jobs": [None, Integral], + "verbose": ["verbose"], + } + + def __init__( + self, + *, + fit_intercept=True, + copy_X="deprecated", + max_subpopulation=1e4, + n_subsamples=None, + max_iter=300, + tol=1.0e-3, + random_state=None, + n_jobs=None, + verbose=False, + ): + self.fit_intercept = fit_intercept + self.copy_X = copy_X + self.max_subpopulation = max_subpopulation + self.n_subsamples = n_subsamples + self.max_iter = max_iter + self.tol = tol + self.random_state = random_state + self.n_jobs = n_jobs + self.verbose = verbose + + def _check_subparams(self, n_samples, n_features): + n_subsamples = self.n_subsamples + + if self.fit_intercept: + n_dim = n_features + 1 + else: + n_dim = n_features + + if n_subsamples is not None: + if n_subsamples > n_samples: + raise ValueError( + "Invalid parameter since n_subsamples > " + "n_samples ({0} > {1}).".format(n_subsamples, n_samples) + ) + if n_samples >= n_features: + if n_dim > n_subsamples: + plus_1 = "+1" if self.fit_intercept else "" + raise ValueError( + "Invalid parameter since n_features{0} " + "> n_subsamples ({1} > {2})." + "".format(plus_1, n_dim, n_subsamples) + ) + else: # if n_samples < n_features + if n_subsamples != n_samples: + raise ValueError( + "Invalid parameter since n_subsamples != " + "n_samples ({0} != {1}) while n_samples " + "< n_features.".format(n_subsamples, n_samples) + ) + else: + n_subsamples = min(n_dim, n_samples) + + all_combinations = max(1, np.rint(binom(n_samples, n_subsamples))) + n_subpopulation = int(min(self.max_subpopulation, all_combinations)) + + return n_subsamples, n_subpopulation + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit linear model. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Training data. + y : ndarray of shape (n_samples,) + Target values. + + Returns + ------- + self : returns an instance of self. + Fitted `TheilSenRegressor` estimator. + """ + if self.copy_X != "deprecated": + warnings.warn( + "`copy_X` was deprecated in 1.6 and will be removed in 1.8 since it " + "has no effect internally. Simply leave this parameter to its default " + "value to avoid this warning.", + FutureWarning, + ) + + random_state = check_random_state(self.random_state) + X, y = validate_data(self, X, y, y_numeric=True) + n_samples, n_features = X.shape + n_subsamples, self.n_subpopulation_ = self._check_subparams( + n_samples, n_features + ) + self.breakdown_ = _breakdown_point(n_samples, n_subsamples) + + if self.verbose: + print("Breakdown point: {0}".format(self.breakdown_)) + print("Number of samples: {0}".format(n_samples)) + tol_outliers = int(self.breakdown_ * n_samples) + print("Tolerable outliers: {0}".format(tol_outliers)) + print("Number of subpopulations: {0}".format(self.n_subpopulation_)) + + # Determine indices of subpopulation + if np.rint(binom(n_samples, n_subsamples)) <= self.max_subpopulation: + indices = list(combinations(range(n_samples), n_subsamples)) + else: + indices = [ + random_state.choice(n_samples, size=n_subsamples, replace=False) + for _ in range(self.n_subpopulation_) + ] + + n_jobs = effective_n_jobs(self.n_jobs) + index_list = np.array_split(indices, n_jobs) + weights = Parallel(n_jobs=n_jobs, verbose=self.verbose)( + delayed(_lstsq)(X, y, index_list[job], self.fit_intercept) + for job in range(n_jobs) + ) + weights = np.vstack(weights) + self.n_iter_, coefs = _spatial_median( + weights, max_iter=self.max_iter, tol=self.tol + ) + + if self.fit_intercept: + self.intercept_ = coefs[0] + self.coef_ = coefs[1:] + else: + self.intercept_ = 0.0 + self.coef_ = coefs + + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..6d8405c7933891dcdbbc340d47108cde68089d1c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/meson.build @@ -0,0 +1,32 @@ +# .pyx is generated, so this is needed to make Cython compilation work +linear_model_cython_tree = [ + fs.copyfile('__init__.py'), +] + +py.extension_module( + '_cd_fast', + [cython_gen.process('_cd_fast.pyx'), utils_cython_tree], + subdir: 'sklearn/linear_model', + install: true +) + +name_list = ['_sgd_fast', '_sag_fast'] + +foreach name: name_list + pyx = custom_target( + name + '_pyx', + output: name + '.pyx', + input: name + '.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [linear_model_cython_tree, utils_cython_tree, _loss_cython_tree], + ) + py.extension_module( + name, + cython_gen.process(pyx), + subdir: 'sklearn/linear_model', + install: true +) +endforeach diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8dfdf4e47122d5ed54a4a85bef880697338ed2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_base.py @@ -0,0 +1,791 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings + +import numpy as np +import pytest +from scipy import linalg, sparse + +from sklearn.datasets import load_iris, make_regression, make_sparse_uncorrelated +from sklearn.linear_model import LinearRegression +from sklearn.linear_model._base import ( + _preprocess_data, + _rescale_data, + make_dataset, +) +from sklearn.preprocessing import add_dummy_feature +from sklearn.utils._testing import ( + assert_allclose, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + LIL_CONTAINERS, +) + +rtol = 1e-6 + + +def test_linear_regression(): + # Test LinearRegression on a simple dataset. + # a simple dataset + X = [[1], [2]] + Y = [1, 2] + + reg = LinearRegression() + 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() + reg.fit(X, Y) + assert_array_almost_equal(reg.coef_, [0]) + assert_array_almost_equal(reg.intercept_, [0]) + assert_array_almost_equal(reg.predict(X), [0]) + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_linear_regression_sample_weights( + sparse_container, fit_intercept, global_random_seed +): + rng = np.random.RandomState(global_random_seed) + + # It would not work with under-determined systems + n_samples, n_features = 6, 5 + + X = rng.normal(size=(n_samples, n_features)) + if sparse_container is not None: + X = sparse_container(X) + y = rng.normal(size=n_samples) + + sample_weight = 1.0 + rng.uniform(size=n_samples) + + # LinearRegression with explicit sample_weight + reg = LinearRegression(fit_intercept=fit_intercept, tol=1e-16) + reg.fit(X, y, sample_weight=sample_weight) + coefs1 = reg.coef_ + inter1 = reg.intercept_ + + assert reg.coef_.shape == (X.shape[1],) # sanity checks + + # Closed form of the weighted least square + # theta = (X^T W X)^(-1) @ X^T W y + W = np.diag(sample_weight) + X_aug = X if not fit_intercept else add_dummy_feature(X) + + Xw = X_aug.T @ W @ X_aug + yw = X_aug.T @ W @ y + coefs2 = linalg.solve(Xw, yw) + + if not fit_intercept: + assert_allclose(coefs1, coefs2) + else: + assert_allclose(coefs1, coefs2[1:]) + assert_allclose(inter1, coefs2[0]) + + +def test_raises_value_error_if_positive_and_sparse(): + error_msg = "Sparse data was passed for X, 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) + + +@pytest.mark.parametrize("n_samples, n_features", [(2, 3), (3, 2)]) +def test_raises_value_error_if_sample_weights_greater_than_1d(n_samples, n_features): + # Sample weights must be either scalar or 1D + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + sample_weights_OK = rng.randn(n_samples) ** 2 + 1 + sample_weights_OK_1 = 1.0 + sample_weights_OK_2 = 2.0 + + reg = LinearRegression() + + # make sure the "OK" sample weights actually work + reg.fit(X, y, sample_weights_OK) + reg.fit(X, y, sample_weights_OK_1) + reg.fit(X, y, sample_weights_OK_2) + + +def test_fit_intercept(): + # Test assertions on betas shape. + X2 = np.array([[0.38349978, 0.61650022], [0.58853682, 0.41146318]]) + X3 = np.array( + [[0.27677969, 0.70693172, 0.01628859], [0.08385139, 0.20692515, 0.70922346]] + ) + y = np.array([1, 1]) + + lr2_without_intercept = LinearRegression(fit_intercept=False).fit(X2, y) + lr2_with_intercept = LinearRegression().fit(X2, y) + + lr3_without_intercept = LinearRegression(fit_intercept=False).fit(X3, y) + lr3_with_intercept = LinearRegression().fit(X3, y) + + assert lr2_with_intercept.coef_.shape == lr2_without_intercept.coef_.shape + assert lr3_with_intercept.coef_.shape == lr3_without_intercept.coef_.shape + assert lr2_without_intercept.coef_.ndim == lr3_without_intercept.coef_.ndim + + +def test_linear_regression_sparse(global_random_seed): + # Test that linear regression also works with sparse data + rng = np.random.RandomState(global_random_seed) + n = 100 + X = sparse.eye(n, n) + beta = rng.rand(n) + y = X @ beta + + ols = LinearRegression() + ols.fit(X, y.ravel()) + assert_array_almost_equal(beta, ols.coef_ + ols.intercept_) + + assert_array_almost_equal(ols.predict(X) - y.ravel(), 0) + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_linear_regression_sparse_equal_dense(fit_intercept, csr_container): + # Test that linear regression agrees between sparse and dense + rng = np.random.RandomState(0) + n_samples = 200 + n_features = 2 + X = rng.randn(n_samples, n_features) + X[X < 0.1] = 0.0 + Xcsr = csr_container(X) + y = rng.rand(n_samples) + params = dict(fit_intercept=fit_intercept) + clf_dense = LinearRegression(**params) + clf_sparse = LinearRegression(**params) + clf_dense.fit(X, y) + clf_sparse.fit(Xcsr, y) + assert clf_dense.intercept_ == pytest.approx(clf_sparse.intercept_) + assert_allclose(clf_dense.coef_, clf_sparse.coef_) + + +def test_linear_regression_multiple_outcome(): + # Test multiple-outcome linear regressions + rng = np.random.RandomState(0) + X, y = make_regression(random_state=rng) + + Y = np.vstack((y, y)).T + n_features = X.shape[1] + + reg = LinearRegression() + reg.fit((X), Y) + assert reg.coef_.shape == (2, n_features) + Y_pred = reg.predict(X) + reg.fit(X, y) + y_pred = reg.predict(X) + assert_array_almost_equal(np.vstack((y_pred, y_pred)).T, Y_pred, decimal=3) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_linear_regression_sparse_multiple_outcome(global_random_seed, coo_container): + # Test multiple-outcome linear regressions with sparse data + rng = np.random.RandomState(global_random_seed) + X, y = make_sparse_uncorrelated(random_state=rng) + X = coo_container(X) + Y = np.vstack((y, y)).T + n_features = X.shape[1] + + ols = LinearRegression() + ols.fit(X, Y) + assert ols.coef_.shape == (2, n_features) + Y_pred = ols.predict(X) + ols.fit(X, y.ravel()) + y_pred = ols.predict(X) + 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(global_random_seed): + # Test multiple-outcome nonnegative linear regressions + rng = np.random.RandomState(global_random_seed) + X, y = make_sparse_uncorrelated(random_state=rng) + 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.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(global_random_seed): + # Test differences with LinearRegression when positive=False. + rng = np.random.RandomState(global_random_seed) + X, y = make_sparse_uncorrelated(random_state=rng) + + 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(global_random_seed): + # Test LinearRegression fitted coefficients + # when the problem is positive. + rng = np.random.RandomState(global_random_seed) + 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 + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize("use_sw", [True, False]) +def test_inplace_data_preprocessing(sparse_container, use_sw, global_random_seed): + # Check that the data is not modified inplace by the linear regression + # estimator. + rng = np.random.RandomState(global_random_seed) + original_X_data = rng.randn(10, 12) + original_y_data = rng.randn(10, 2) + orginal_sw_data = rng.rand(10) + + if sparse_container is not None: + X = sparse_container(original_X_data) + else: + X = original_X_data.copy() + y = original_y_data.copy() + # XXX: Note hat y_sparse is not supported (broken?) in the current + # implementation of LinearRegression. + + if use_sw: + sample_weight = orginal_sw_data.copy() + else: + sample_weight = None + + # Do not allow inplace preprocessing of X and y: + reg = LinearRegression() + reg.fit(X, y, sample_weight=sample_weight) + if sparse_container is not None: + assert_allclose(X.toarray(), original_X_data) + else: + assert_allclose(X, original_X_data) + assert_allclose(y, original_y_data) + + if use_sw: + assert_allclose(sample_weight, orginal_sw_data) + + # Allow inplace preprocessing of X and y + reg = LinearRegression(copy_X=False) + reg.fit(X, y, sample_weight=sample_weight) + if sparse_container is not None: + # No optimization relying on the inplace modification of sparse input + # data has been implemented at this time. + assert_allclose(X.toarray(), original_X_data) + else: + # X has been offset (and optionally rescaled by sample weights) + # inplace. The 0.42 threshold is arbitrary and has been found to be + # robust to any random seed in the admissible range. + assert np.linalg.norm(X - original_X_data) > 0.42 + + # y should not have been modified inplace by LinearRegression.fit. + assert_allclose(y, original_y_data) + + if use_sw: + # Sample weights have no reason to ever be modified inplace. + assert_allclose(sample_weight, orginal_sw_data) + + +def test_linear_regression_pd_sparse_dataframe_warning(): + pd = pytest.importorskip("pandas") + + # Warning is raised only when some of the columns is sparse + df = pd.DataFrame({"0": np.random.randn(10)}) + for col in range(1, 4): + arr = np.random.randn(10) + arr[:8] = 0 + # all columns but the first column is sparse + if col != 0: + arr = pd.arrays.SparseArray(arr, fill_value=0) + df[str(col)] = arr + + msg = "pandas.DataFrame with sparse columns found." + + reg = LinearRegression() + with pytest.warns(UserWarning, match=msg): + reg.fit(df.iloc[:, 0:2], df.iloc[:, 3]) + + # does not warn when the whole dataframe is sparse + df["0"] = pd.arrays.SparseArray(df["0"], fill_value=0) + assert hasattr(df, "sparse") + + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + reg.fit(df.iloc[:, 0:2], df.iloc[:, 3]) + + +def test_preprocess_data(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 2 + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + expected_X_mean = np.mean(X, axis=0) + expected_y_mean = np.mean(y, axis=0) + + Xt, yt, X_mean, y_mean, X_scale = _preprocess_data(X, y, fit_intercept=False) + assert_array_almost_equal(X_mean, np.zeros(n_features)) + assert_array_almost_equal(y_mean, 0) + assert_array_almost_equal(X_scale, np.ones(n_features)) + assert_array_almost_equal(Xt, X) + assert_array_almost_equal(yt, y) + + Xt, yt, X_mean, y_mean, X_scale = _preprocess_data(X, y, fit_intercept=True) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_scale, np.ones(n_features)) + assert_array_almost_equal(Xt, X - expected_X_mean) + assert_array_almost_equal(yt, y - expected_y_mean) + + +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS) +def test_preprocess_data_multioutput(global_random_seed, sparse_container): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 3 + n_outputs = 2 + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples, n_outputs) + expected_y_mean = np.mean(y, axis=0) + + if sparse_container is not None: + X = sparse_container(X) + + _, yt, _, y_mean, _ = _preprocess_data(X, y, fit_intercept=False) + assert_array_almost_equal(y_mean, np.zeros(n_outputs)) + assert_array_almost_equal(yt, y) + + _, yt, _, y_mean, _ = _preprocess_data(X, y, fit_intercept=True) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(yt, y - y_mean) + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_preprocess_data_weighted(sparse_container, global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 4 + # Generate random data with 50% of zero values to make sure + # that the sparse variant of this test is actually sparse. This also + # shifts the mean value for each columns in X further away from + # zero. + X = rng.rand(n_samples, n_features) + X[X < 0.5] = 0.0 + + # Scale the first feature of X to be 10 larger than the other to + # better check the impact of feature scaling. + X[:, 0] *= 10 + + # Constant non-zero feature. + X[:, 2] = 1.0 + + # Constant zero feature (non-materialized in the sparse case) + X[:, 3] = 0.0 + y = rng.rand(n_samples) + + sample_weight = rng.rand(n_samples) + expected_X_mean = np.average(X, axis=0, weights=sample_weight) + expected_y_mean = np.average(y, axis=0, weights=sample_weight) + + X_sample_weight_avg = np.average(X, weights=sample_weight, axis=0) + X_sample_weight_var = np.average( + (X - X_sample_weight_avg) ** 2, weights=sample_weight, axis=0 + ) + constant_mask = X_sample_weight_var < 10 * np.finfo(X.dtype).eps + assert_array_equal(constant_mask, [0, 0, 1, 1]) + expected_X_scale = np.sqrt(X_sample_weight_var) * np.sqrt(sample_weight.sum()) + + # near constant features should not be scaled + expected_X_scale[constant_mask] = 1 + + if sparse_container is not None: + X = sparse_container(X) + + # normalize is False + Xt, yt, X_mean, y_mean, X_scale = _preprocess_data( + X, + y, + fit_intercept=True, + sample_weight=sample_weight, + ) + assert_array_almost_equal(X_mean, expected_X_mean) + assert_array_almost_equal(y_mean, expected_y_mean) + assert_array_almost_equal(X_scale, np.ones(n_features)) + if sparse_container is not None: + assert_array_almost_equal(Xt.toarray(), X.toarray()) + else: + assert_array_almost_equal(Xt, X - expected_X_mean) + assert_array_almost_equal(yt, y - expected_y_mean) + + +@pytest.mark.parametrize("lil_container", LIL_CONTAINERS) +def test_sparse_preprocess_data_offsets(global_random_seed, lil_container): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 2 + X = sparse.rand(n_samples, n_features, density=0.5, random_state=rng) + X = lil_container(X) + y = rng.rand(n_samples) + XA = X.toarray() + + Xt, yt, X_mean, y_mean, X_scale = _preprocess_data(X, y, fit_intercept=False) + assert_array_almost_equal(X_mean, np.zeros(n_features)) + assert_array_almost_equal(y_mean, 0) + assert_array_almost_equal(X_scale, np.ones(n_features)) + assert_array_almost_equal(Xt.toarray(), XA) + assert_array_almost_equal(yt, y) + + Xt, yt, X_mean, y_mean, X_scale = _preprocess_data(X, y, fit_intercept=True) + assert_array_almost_equal(X_mean, np.mean(XA, axis=0)) + assert_array_almost_equal(y_mean, np.mean(y, axis=0)) + assert_array_almost_equal(X_scale, np.ones(n_features)) + assert_array_almost_equal(Xt.toarray(), XA) + assert_array_almost_equal(yt, y - np.mean(y, axis=0)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_csr_preprocess_data(csr_container): + # Test output format of _preprocess_data, when input is csr + X, y = make_regression() + X[X < 2.5] = 0.0 + csr = csr_container(X) + csr_, y, _, _, _ = _preprocess_data(csr, y, fit_intercept=True) + assert csr_.format == "csr" + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize("to_copy", (True, False)) +def test_preprocess_copy_data_no_checks(sparse_container, to_copy): + X, y = make_regression() + X[X < 2.5] = 0.0 + + if sparse_container is not None: + X = sparse_container(X) + + X_, y_, _, _, _ = _preprocess_data( + X, y, fit_intercept=True, copy=to_copy, check_input=False + ) + + if to_copy and sparse_container is not None: + assert not np.may_share_memory(X_.data, X.data) + elif to_copy: + assert not np.may_share_memory(X_, X) + elif sparse_container is not None: + assert np.may_share_memory(X_.data, X.data) + else: + assert np.may_share_memory(X_, X) + + +def test_dtype_preprocess_data(global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 2 + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + + X_32 = np.asarray(X, dtype=np.float32) + y_32 = np.asarray(y, dtype=np.float32) + X_64 = np.asarray(X, dtype=np.float64) + y_64 = np.asarray(y, dtype=np.float64) + + for fit_intercept in [True, False]: + Xt_32, yt_32, X_mean_32, y_mean_32, X_scale_32 = _preprocess_data( + X_32, + y_32, + fit_intercept=fit_intercept, + ) + + Xt_64, yt_64, X_mean_64, y_mean_64, X_scale_64 = _preprocess_data( + X_64, + y_64, + fit_intercept=fit_intercept, + ) + + Xt_3264, yt_3264, X_mean_3264, y_mean_3264, X_scale_3264 = _preprocess_data( + X_32, + y_64, + fit_intercept=fit_intercept, + ) + + Xt_6432, yt_6432, X_mean_6432, y_mean_6432, X_scale_6432 = _preprocess_data( + X_64, + y_32, + fit_intercept=fit_intercept, + ) + + assert Xt_32.dtype == np.float32 + assert yt_32.dtype == np.float32 + assert X_mean_32.dtype == np.float32 + assert y_mean_32.dtype == np.float32 + assert X_scale_32.dtype == np.float32 + + assert Xt_64.dtype == np.float64 + assert yt_64.dtype == np.float64 + assert X_mean_64.dtype == np.float64 + assert y_mean_64.dtype == np.float64 + assert X_scale_64.dtype == np.float64 + + assert Xt_3264.dtype == np.float32 + assert yt_3264.dtype == np.float32 + assert X_mean_3264.dtype == np.float32 + assert y_mean_3264.dtype == np.float32 + assert X_scale_3264.dtype == np.float32 + + assert Xt_6432.dtype == np.float64 + assert yt_6432.dtype == np.float64 + assert X_mean_6432.dtype == np.float64 + assert y_mean_6432.dtype == np.float64 + assert X_scale_6432.dtype == np.float64 + + assert X_32.dtype == np.float32 + assert y_32.dtype == np.float32 + assert X_64.dtype == np.float64 + assert y_64.dtype == np.float64 + + assert_array_almost_equal(Xt_32, Xt_64) + assert_array_almost_equal(yt_32, yt_64) + assert_array_almost_equal(X_mean_32, X_mean_64) + assert_array_almost_equal(y_mean_32, y_mean_64) + assert_array_almost_equal(X_scale_32, X_scale_64) + + +@pytest.mark.parametrize("n_targets", [None, 2]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_rescale_data(n_targets, sparse_container, global_random_seed): + rng = np.random.RandomState(global_random_seed) + n_samples = 200 + n_features = 2 + + sample_weight = 1.0 + rng.rand(n_samples) + X = rng.rand(n_samples, n_features) + if n_targets is None: + y = rng.rand(n_samples) + else: + y = rng.rand(n_samples, n_targets) + + expected_sqrt_sw = np.sqrt(sample_weight) + expected_rescaled_X = X * expected_sqrt_sw[:, np.newaxis] + + if n_targets is None: + expected_rescaled_y = y * expected_sqrt_sw + else: + expected_rescaled_y = y * expected_sqrt_sw[:, np.newaxis] + + if sparse_container is not None: + X = sparse_container(X) + if n_targets is None: + y = sparse_container(y.reshape(-1, 1)) + else: + y = sparse_container(y) + + rescaled_X, rescaled_y, sqrt_sw = _rescale_data(X, y, sample_weight) + + assert_allclose(sqrt_sw, expected_sqrt_sw) + + if sparse_container is not None: + rescaled_X = rescaled_X.toarray() + rescaled_y = rescaled_y.toarray() + if n_targets is None: + rescaled_y = rescaled_y.ravel() + + assert_allclose(rescaled_X, expected_rescaled_X) + assert_allclose(rescaled_y, expected_rescaled_y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_fused_types_make_dataset(csr_container): + iris = load_iris() + + X_32 = iris.data.astype(np.float32) + y_32 = iris.target.astype(np.float32) + X_csr_32 = csr_container(X_32) + sample_weight_32 = np.arange(y_32.size, dtype=np.float32) + + X_64 = iris.data.astype(np.float64) + y_64 = iris.target.astype(np.float64) + X_csr_64 = csr_container(X_64) + sample_weight_64 = np.arange(y_64.size, dtype=np.float64) + + # array + dataset_32, _ = make_dataset(X_32, y_32, sample_weight_32) + dataset_64, _ = make_dataset(X_64, y_64, sample_weight_64) + xi_32, yi_32, _, _ = dataset_32._next_py() + xi_64, yi_64, _, _ = dataset_64._next_py() + xi_data_32, _, _ = xi_32 + xi_data_64, _, _ = xi_64 + + assert xi_data_32.dtype == np.float32 + assert xi_data_64.dtype == np.float64 + assert_allclose(yi_64, yi_32, rtol=rtol) + + # csr + datasetcsr_32, _ = make_dataset(X_csr_32, y_32, sample_weight_32) + datasetcsr_64, _ = make_dataset(X_csr_64, y_64, sample_weight_64) + xicsr_32, yicsr_32, _, _ = datasetcsr_32._next_py() + xicsr_64, yicsr_64, _, _ = datasetcsr_64._next_py() + xicsr_data_32, _, _ = xicsr_32 + xicsr_data_64, _, _ = xicsr_64 + + assert xicsr_data_32.dtype == np.float32 + assert xicsr_data_64.dtype == np.float64 + + assert_allclose(xicsr_data_64, xicsr_data_32, rtol=rtol) + assert_allclose(yicsr_64, yicsr_32, rtol=rtol) + + assert_array_equal(xi_data_32, xicsr_data_32) + assert_array_equal(xi_data_64, xicsr_data_64) + assert_array_equal(yi_32, yicsr_32) + assert_array_equal(yi_64, yicsr_64) + + +@pytest.mark.parametrize("X_shape", [(10, 5), (10, 20), (100, 100)]) +@pytest.mark.parametrize( + "sparse_container", + [None] + + [ + pytest.param( + container, + marks=pytest.mark.xfail( + reason="Known to fail for CSR arrays, see issue #30131." + ), + ) + for container in CSR_CONTAINERS + ], +) +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_linear_regression_sample_weight_consistency( + X_shape, sparse_container, fit_intercept, global_random_seed +): + """Test that the impact of sample_weight is consistent. + + Note that this test is stricter than the common test + check_sample_weight_equivalence alone and also tests sparse X. + It is very similar to test_enet_sample_weight_consistency. + """ + rng = np.random.RandomState(global_random_seed) + n_samples, n_features = X_shape + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + if sparse_container is not None: + X = sparse_container(X) + params = dict(fit_intercept=fit_intercept) + + reg = LinearRegression(**params).fit(X, y, sample_weight=None) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + + # 1) sample_weight=np.ones(..) must be equivalent to sample_weight=None, + # a special case of check_sample_weight_equivalence(name, reg), but we also + # test with sparse input. + sample_weight = np.ones_like(y) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 2) sample_weight=None should be equivalent to sample_weight = number + sample_weight = 123.0 + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 3) scaling of sample_weight should have no effect, cf. np.average() + sample_weight = rng.uniform(low=0.01, high=2, size=X.shape[0]) + reg = reg.fit(X, y, sample_weight=sample_weight) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + + reg.fit(X, y, sample_weight=np.pi * sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6 if sparse_container is None else 1e-5) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 4) setting elements of sample_weight to 0 is equivalent to removing these samples + sample_weight_0 = sample_weight.copy() + sample_weight_0[-5:] = 0 + y[-5:] *= 1000 # to make excluding those samples important + reg.fit(X, y, sample_weight=sample_weight_0) + coef_0 = reg.coef_.copy() + if fit_intercept: + intercept_0 = reg.intercept_ + reg.fit(X[:-5], y[:-5], sample_weight=sample_weight[:-5]) + assert_allclose(reg.coef_, coef_0, rtol=1e-5) + if fit_intercept: + assert_allclose(reg.intercept_, intercept_0) + + # 5) check that multiplying sample_weight by 2 is equivalent to repeating + # corresponding samples twice + if sparse_container is not None: + 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 = sample_weight.copy() + sample_weight_1[: n_samples // 2] *= 2 + sample_weight_2 = np.concatenate( + [sample_weight, sample_weight[: n_samples // 2]], axis=0 + ) + + reg1 = LinearRegression(**params).fit(X, y, sample_weight=sample_weight_1) + reg2 = LinearRegression(**params).fit(X2, y2, sample_weight=sample_weight_2) + assert_allclose(reg1.coef_, reg2.coef_, rtol=1e-6) + if fit_intercept: + assert_allclose(reg1.intercept_, reg2.intercept_) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_bayes.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_bayes.py new file mode 100644 index 0000000000000000000000000000000000000000..9f7fabb749f529ea21b90d5496c8b9514f93f892 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_bayes.py @@ -0,0 +1,314 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from math import log + +import numpy as np +import pytest + +from sklearn import datasets +from sklearn.linear_model import ARDRegression, BayesianRidge, Ridge +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_less, +) +from sklearn.utils.extmath import fast_logdet + +diabetes = datasets.load_diabetes() + + +def test_bayesian_ridge_scores(): + """Check scores attribute shape""" + X, y = diabetes.data, diabetes.target + + clf = BayesianRidge(compute_score=True) + clf.fit(X, y) + + assert clf.scores_.shape == (clf.n_iter_ + 1,) + + +def test_bayesian_ridge_score_values(): + """Check value of score on toy example. + + Compute log marginal likelihood with equation (36) in Sparse Bayesian + Learning and the Relevance Vector Machine (Tipping, 2001): + + - 0.5 * (log |Id/alpha + X.X^T/lambda| + + y^T.(Id/alpha + X.X^T/lambda).y + n * log(2 * pi)) + + lambda_1 * log(lambda) - lambda_2 * lambda + + alpha_1 * log(alpha) - alpha_2 * alpha + + and check equality with the score computed during training. + """ + + X, y = diabetes.data, diabetes.target + n_samples = X.shape[0] + # check with initial values of alpha and lambda (see code for the values) + eps = np.finfo(np.float64).eps + alpha_ = 1.0 / (np.var(y) + eps) + lambda_ = 1.0 + + # value of the parameters of the Gamma hyperpriors + alpha_1 = 0.1 + alpha_2 = 0.1 + lambda_1 = 0.1 + lambda_2 = 0.1 + + # compute score using formula of docstring + score = lambda_1 * log(lambda_) - lambda_2 * lambda_ + score += alpha_1 * log(alpha_) - alpha_2 * alpha_ + M = 1.0 / alpha_ * np.eye(n_samples) + 1.0 / lambda_ * np.dot(X, X.T) + M_inv_dot_y = np.linalg.solve(M, y) + score += -0.5 * ( + fast_logdet(M) + np.dot(y.T, M_inv_dot_y) + n_samples * log(2 * np.pi) + ) + + # compute score with BayesianRidge + clf = BayesianRidge( + alpha_1=alpha_1, + alpha_2=alpha_2, + lambda_1=lambda_1, + lambda_2=lambda_2, + max_iter=1, + fit_intercept=False, + compute_score=True, + ) + clf.fit(X, y) + + assert_almost_equal(clf.scores_[0], score, decimal=9) + + +def test_bayesian_ridge_parameter(): + # Test correctness of lambda_ and alpha_ parameters (GitHub issue #8224) + X = np.array([[1, 1], [3, 4], [5, 7], [4, 1], [2, 6], [3, 10], [3, 2]]) + y = np.array([1, 2, 3, 2, 0, 4, 5]).T + + # A Ridge regression model using an alpha value equal to the ratio of + # lambda_ and alpha_ from the Bayesian Ridge model must be identical + br_model = BayesianRidge(compute_score=True).fit(X, y) + rr_model = Ridge(alpha=br_model.lambda_ / br_model.alpha_).fit(X, y) + assert_array_almost_equal(rr_model.coef_, br_model.coef_) + assert_almost_equal(rr_model.intercept_, br_model.intercept_) + + +@pytest.mark.parametrize("n_samples, n_features", [(10, 20), (20, 10)]) +def test_bayesian_covariance_matrix(n_samples, n_features, global_random_seed): + """Check the posterior covariance matrix sigma_ + + Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/31093 + """ + X, y = datasets.make_regression( + n_samples, n_features, random_state=global_random_seed + ) + reg = BayesianRidge(fit_intercept=False).fit(X, y) + covariance_matrix = np.linalg.inv( + reg.lambda_ * np.identity(n_features) + reg.alpha_ * np.dot(X.T, X) + ) + assert_allclose(reg.sigma_, covariance_matrix, rtol=1e-6) + + +def test_bayesian_sample_weights(): + # Test correctness of the sample_weights method + X = np.array([[1, 1], [3, 4], [5, 7], [4, 1], [2, 6], [3, 10], [3, 2]]) + y = np.array([1, 2, 3, 2, 0, 4, 5]).T + w = np.array([4, 3, 3, 1, 1, 2, 3]).T + + # A Ridge regression model using an alpha value equal to the ratio of + # lambda_ and alpha_ from the Bayesian Ridge model must be identical + br_model = BayesianRidge(compute_score=True).fit(X, y, sample_weight=w) + rr_model = Ridge(alpha=br_model.lambda_ / br_model.alpha_).fit( + X, y, sample_weight=w + ) + assert_array_almost_equal(rr_model.coef_, br_model.coef_) + assert_almost_equal(rr_model.intercept_, br_model.intercept_) + + +def test_toy_bayesian_ridge_object(): + # Test BayesianRidge on toy + X = np.array([[1], [2], [6], [8], [10]]) + Y = np.array([1, 2, 6, 8, 10]) + clf = BayesianRidge(compute_score=True) + clf.fit(X, Y) + + # Check that the model could approximately learn the identity function + test = [[1], [3], [4]] + assert_array_almost_equal(clf.predict(test), [1, 3, 4], 2) + + +def test_bayesian_initial_params(): + # Test BayesianRidge with initial values (alpha_init, lambda_init) + X = np.vander(np.linspace(0, 4, 5), 4) + y = np.array([0.0, 1.0, 0.0, -1.0, 0.0]) # y = (x^3 - 6x^2 + 8x) / 3 + + # In this case, starting from the default initial values will increase + # the bias of the fitted curve. So, lambda_init should be small. + reg = BayesianRidge(alpha_init=1.0, lambda_init=1e-3) + # Check the R2 score nearly equals to one. + r2 = reg.fit(X, y).score(X, y) + assert_almost_equal(r2, 1.0) + + +def test_prediction_bayesian_ridge_ard_with_constant_input(): + # Test BayesianRidge and ARDRegression predictions for edge case of + # constant target vectors + n_samples = 4 + n_features = 5 + random_state = check_random_state(42) + constant_value = random_state.rand() + X = random_state.random_sample((n_samples, n_features)) + y = np.full(n_samples, constant_value, dtype=np.array(constant_value).dtype) + expected = np.full(n_samples, constant_value, dtype=np.array(constant_value).dtype) + + for clf in [BayesianRidge(), ARDRegression()]: + y_pred = clf.fit(X, y).predict(X) + assert_array_almost_equal(y_pred, expected) + + +def test_std_bayesian_ridge_ard_with_constant_input(): + # Test BayesianRidge and ARDRegression standard dev. for edge case of + # constant target vector + # The standard dev. should be relatively small (< 0.01 is tested here) + n_samples = 10 + n_features = 5 + random_state = check_random_state(42) + constant_value = random_state.rand() + X = random_state.random_sample((n_samples, n_features)) + y = np.full(n_samples, constant_value, dtype=np.array(constant_value).dtype) + expected_upper_boundary = 0.01 + + for clf in [BayesianRidge(), ARDRegression()]: + _, y_std = clf.fit(X, y).predict(X, return_std=True) + assert_array_less(y_std, expected_upper_boundary) + + +def test_update_of_sigma_in_ard(): + # Checks that `sigma_` is updated correctly after the last iteration + # of the ARDRegression algorithm. See issue #10128. + X = np.array([[1, 0], [0, 0]]) + y = np.array([0, 0]) + clf = ARDRegression(max_iter=1) + clf.fit(X, y) + # With the inputs above, ARDRegression prunes both of the two coefficients + # in the first iteration. Hence, the expected shape of `sigma_` is (0, 0). + assert clf.sigma_.shape == (0, 0) + # Ensure that no error is thrown at prediction stage + clf.predict(X, return_std=True) + + +def test_toy_ard_object(): + # Test BayesianRegression ARD classifier + X = np.array([[1], [2], [3]]) + Y = np.array([1, 2, 3]) + clf = ARDRegression(compute_score=True) + clf.fit(X, Y) + + # Check that the model could approximately learn the identity function + test = [[1], [3], [4]] + assert_array_almost_equal(clf.predict(test), [1, 3, 4], 2) + + +@pytest.mark.parametrize("n_samples, n_features", ((10, 100), (100, 10))) +def test_ard_accuracy_on_easy_problem(global_random_seed, n_samples, n_features): + # Check that ARD converges with reasonable accuracy on an easy problem + # (Github issue #14055) + X = np.random.RandomState(global_random_seed).normal(size=(250, 3)) + y = X[:, 1] + + regressor = ARDRegression() + regressor.fit(X, y) + + abs_coef_error = np.abs(1 - regressor.coef_[1]) + assert abs_coef_error < 1e-10 + + +@pytest.mark.parametrize("constructor_name", ["array", "dataframe"]) +def test_return_std(constructor_name): + # Test return_std option for both Bayesian regressors + def f(X): + return np.dot(X, w) + b + + def f_noise(X, noise_mult): + return f(X) + np.random.randn(X.shape[0]) * noise_mult + + d = 5 + n_train = 50 + n_test = 10 + + w = np.array([1.0, 0.0, 1.0, -1.0, 0.0]) + b = 1.0 + + X = np.random.random((n_train, d)) + X = _convert_container(X, constructor_name) + + X_test = np.random.random((n_test, d)) + X_test = _convert_container(X_test, constructor_name) + + for decimal, noise_mult in enumerate([1, 0.1, 0.01]): + y = f_noise(X, noise_mult) + + m1 = BayesianRidge() + m1.fit(X, y) + y_mean1, y_std1 = m1.predict(X_test, return_std=True) + assert_array_almost_equal(y_std1, noise_mult, decimal=decimal) + + m2 = ARDRegression() + m2.fit(X, y) + y_mean2, y_std2 = m2.predict(X_test, return_std=True) + assert_array_almost_equal(y_std2, noise_mult, decimal=decimal) + + +def test_update_sigma(global_random_seed): + # make sure the two update_sigma() helpers are equivalent. The woodbury + # formula is used when n_samples < n_features, and the other one is used + # otherwise. + + rng = np.random.RandomState(global_random_seed) + + # set n_samples == n_features to avoid instability issues when inverting + # the matrices. Using the woodbury formula would be unstable when + # n_samples > n_features + n_samples = n_features = 10 + X = rng.randn(n_samples, n_features) + alpha = 1 + lmbda = np.arange(1, n_features + 1) + keep_lambda = np.array([True] * n_features) + + reg = ARDRegression() + + sigma = reg._update_sigma(X, alpha, lmbda, keep_lambda) + sigma_woodbury = reg._update_sigma_woodbury(X, alpha, lmbda, keep_lambda) + + np.testing.assert_allclose(sigma, sigma_woodbury) + + +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +@pytest.mark.parametrize("Estimator", [BayesianRidge, ARDRegression]) +def test_dtype_match(dtype, Estimator): + # Test that np.float32 input data is not cast to np.float64 when possible + X = np.array([[1, 1], [3, 4], [5, 7], [4, 1], [2, 6], [3, 10], [3, 2]], dtype=dtype) + y = np.array([1, 2, 3, 2, 0, 4, 5]).T + + model = Estimator() + # check type consistency + model.fit(X, y) + attributes = ["coef_", "sigma_"] + for attribute in attributes: + assert getattr(model, attribute).dtype == X.dtype + + y_mean, y_std = model.predict(X, return_std=True) + assert y_mean.dtype == X.dtype + assert y_std.dtype == X.dtype + + +@pytest.mark.parametrize("Estimator", [BayesianRidge, ARDRegression]) +def test_dtype_correctness(Estimator): + X = np.array([[1, 1], [3, 4], [5, 7], [4, 1], [2, 6], [3, 10], [3, 2]]) + y = np.array([1, 2, 3, 2, 0, 4, 5]).T + model = Estimator() + coef_32 = model.fit(X.astype(np.float32), y).coef_ + coef_64 = model.fit(X.astype(np.float64), y).coef_ + np.testing.assert_allclose(coef_32, coef_64, rtol=1e-4) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..2483a26644cbbe30388703efc4f687bb01ba5f62 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_common.py @@ -0,0 +1,234 @@ +# SPDX-License-Identifier: BSD-3-Clause + +import inspect + +import numpy as np +import pytest + +from sklearn.base import is_classifier +from sklearn.datasets import make_classification, make_low_rank_matrix, make_regression +from sklearn.linear_model import ( + ARDRegression, + BayesianRidge, + ElasticNet, + ElasticNetCV, + GammaRegressor, + HuberRegressor, + Lars, + LarsCV, + Lasso, + LassoCV, + LassoLars, + LassoLarsCV, + LassoLarsIC, + LinearRegression, + LogisticRegression, + LogisticRegressionCV, + MultiTaskElasticNet, + MultiTaskElasticNetCV, + MultiTaskLasso, + MultiTaskLassoCV, + OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV, + PassiveAggressiveClassifier, + PassiveAggressiveRegressor, + Perceptron, + PoissonRegressor, + Ridge, + RidgeClassifier, + RidgeClassifierCV, + RidgeCV, + SGDClassifier, + SGDRegressor, + TheilSenRegressor, + TweedieRegressor, +) +from sklearn.preprocessing import MinMaxScaler +from sklearn.svm import LinearSVC, LinearSVR +from sklearn.utils._testing import set_random_state + + +# Note: GammaRegressor() and TweedieRegressor(power != 1) have a non-canonical link. +@pytest.mark.parametrize( + "model", + [ + ARDRegression(), + BayesianRidge(), + ElasticNet(), + ElasticNetCV(), + Lars(), + LarsCV(), + Lasso(), + LassoCV(), + LassoLarsCV(), + LassoLarsIC(), + LinearRegression(), + # TODO: FIx SAGA which fails badly with sample_weights. + # This is a known limitation, see: + # https://github.com/scikit-learn/scikit-learn/issues/21305 + pytest.param( + LogisticRegression( + penalty="elasticnet", solver="saga", l1_ratio=0.5, tol=1e-15 + ), + marks=pytest.mark.xfail(reason="Missing importance sampling scheme"), + ), + LogisticRegressionCV(tol=1e-6), + MultiTaskElasticNet(), + MultiTaskElasticNetCV(), + MultiTaskLasso(), + MultiTaskLassoCV(), + OrthogonalMatchingPursuit(), + OrthogonalMatchingPursuitCV(), + PoissonRegressor(), + Ridge(), + RidgeCV(), + pytest.param( + SGDRegressor(tol=1e-15), + marks=pytest.mark.xfail(reason="Insufficient precision."), + ), + SGDRegressor(penalty="elasticnet", max_iter=10_000), + TweedieRegressor(power=0), # same as Ridge + ], + ids=lambda x: x.__class__.__name__, +) +@pytest.mark.parametrize("with_sample_weight", [False, True]) +def test_balance_property(model, with_sample_weight, global_random_seed): + # Test that sum(y_predicted) == sum(y_observed) on the training set. + # This must hold for all linear models with deviance of an exponential disperson + # family as loss and the corresponding canonical link if fit_intercept=True. + # Examples: + # - squared error and identity link (most linear models) + # - Poisson deviance with log link + # - log loss with logit link + # This is known as balance property or unconditional calibration/unbiasedness. + # For reference, see Corollary 3.18, 3.20 and Chapter 5.1.5 of + # M.V. Wuthrich and M. Merz, "Statistical Foundations of Actuarial Learning and its + # Applications" (June 3, 2022). http://doi.org/10.2139/ssrn.3822407 + + if ( + with_sample_weight + and "sample_weight" not in inspect.signature(model.fit).parameters.keys() + ): + pytest.skip("Estimator does not support sample_weight.") + + rel = 2e-4 # test precision + if isinstance(model, SGDRegressor): + rel = 1e-1 + elif hasattr(model, "solver") and model.solver == "saga": + rel = 1e-2 + + rng = np.random.RandomState(global_random_seed) + n_train, n_features, n_targets = 100, 10, None + if isinstance( + model, + (MultiTaskElasticNet, MultiTaskElasticNetCV, MultiTaskLasso, MultiTaskLassoCV), + ): + n_targets = 3 + X = make_low_rank_matrix(n_samples=n_train, n_features=n_features, random_state=rng) + if n_targets: + coef = ( + rng.uniform(low=-2, high=2, size=(n_features, n_targets)) + / np.max(X, axis=0)[:, None] + ) + else: + coef = rng.uniform(low=-2, high=2, size=n_features) / np.max(X, axis=0) + + expectation = np.exp(X @ coef + 0.5) + y = rng.poisson(lam=expectation) + 1 # strict positive, i.e. y > 0 + if is_classifier(model): + y = (y > expectation + 1).astype(np.float64) + + if with_sample_weight: + sw = rng.uniform(low=1, high=10, size=y.shape[0]) + else: + sw = None + + model.set_params(fit_intercept=True) # to be sure + if with_sample_weight: + model.fit(X, y, sample_weight=sw) + else: + model.fit(X, y) + # Assert balance property. + if is_classifier(model): + assert np.average(model.predict_proba(X)[:, 1], weights=sw) == pytest.approx( + np.average(y, weights=sw), rel=rel + ) + else: + assert np.average(model.predict(X), weights=sw, axis=0) == pytest.approx( + np.average(y, weights=sw, axis=0), rel=rel + ) + + +@pytest.mark.filterwarnings("ignore:The default of 'normalize'") +@pytest.mark.filterwarnings("ignore:lbfgs failed to converge") +@pytest.mark.parametrize( + "Regressor", + [ + ARDRegression, + BayesianRidge, + ElasticNet, + ElasticNetCV, + GammaRegressor, + HuberRegressor, + Lars, + LarsCV, + Lasso, + LassoCV, + LassoLars, + LassoLarsCV, + LassoLarsIC, + LinearSVR, + LinearRegression, + OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV, + PassiveAggressiveRegressor, + PoissonRegressor, + Ridge, + RidgeCV, + SGDRegressor, + TheilSenRegressor, + TweedieRegressor, + ], +) +@pytest.mark.parametrize("ndim", [1, 2]) +def test_linear_model_regressor_coef_shape(Regressor, ndim): + """Check the consistency of linear models `coef` shape.""" + if Regressor is LinearRegression: + pytest.xfail("LinearRegression does not follow `coef_` shape contract!") + + X, y = make_regression(random_state=0, n_samples=200, n_features=20) + y = MinMaxScaler().fit_transform(y.reshape(-1, 1))[:, 0] + 1 + y = y[:, np.newaxis] if ndim == 2 else y + + regressor = Regressor() + set_random_state(regressor) + regressor.fit(X, y) + assert regressor.coef_.shape == (X.shape[1],) + + +@pytest.mark.parametrize( + "Classifier", + [ + LinearSVC, + LogisticRegression, + LogisticRegressionCV, + PassiveAggressiveClassifier, + Perceptron, + RidgeClassifier, + RidgeClassifierCV, + SGDClassifier, + ], +) +@pytest.mark.parametrize("n_classes", [2, 3]) +def test_linear_model_classifier_coef_shape(Classifier, n_classes): + if Classifier in (RidgeClassifier, RidgeClassifierCV): + pytest.xfail(f"{Classifier} does not follow `coef_` shape contract!") + + X, y = make_classification(n_informative=10, n_classes=n_classes, random_state=0) + n_features = X.shape[1] + + classifier = Classifier() + set_random_state(classifier) + classifier.fit(X, y) + expected_shape = (1, n_features) if n_classes == 2 else (n_classes, n_features) + assert classifier.coef_.shape == expected_shape diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_coordinate_descent.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_coordinate_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..70226210c010dc8c3ee350933cea569c6be23faa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_coordinate_descent.py @@ -0,0 +1,1805 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from copy import deepcopy + +import joblib +import numpy as np +import pytest +from scipy import interpolate, sparse + +from sklearn.base import clone, config_context, is_classifier +from sklearn.datasets import load_diabetes, make_regression +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ( + ElasticNet, + ElasticNetCV, + Lasso, + LassoCV, + LassoLars, + LassoLarsCV, + LinearRegression, + MultiTaskElasticNet, + MultiTaskElasticNetCV, + MultiTaskLasso, + MultiTaskLassoCV, + Ridge, + RidgeClassifier, + RidgeClassifierCV, + RidgeCV, + enet_path, + lars_path, + lasso_path, +) +from sklearn.linear_model._coordinate_descent import _set_order +from sklearn.model_selection import ( + BaseCrossValidator, + GridSearchCV, + LeaveOneGroupOut, +) +from sklearn.model_selection._split import GroupsConsumerMixin +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils import check_array +from sklearn.utils._testing import ( + TempMemmap, + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + assert_array_less, + ignore_warnings, +) +from sklearn.utils.fixes import COO_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS + + +@pytest.mark.parametrize("order", ["C", "F"]) +@pytest.mark.parametrize("input_order", ["C", "F"]) +def test_set_order_dense(order, input_order): + """Check that _set_order returns arrays with promised order.""" + X = np.array([[0], [0], [0]], order=input_order) + y = np.array([0, 0, 0], order=input_order) + X2, y2 = _set_order(X, y, order=order) + if order == "C": + assert X2.flags["C_CONTIGUOUS"] + assert y2.flags["C_CONTIGUOUS"] + elif order == "F": + assert X2.flags["F_CONTIGUOUS"] + assert y2.flags["F_CONTIGUOUS"] + + if order == input_order: + assert X is X2 + assert y is y2 + + +@pytest.mark.parametrize("order", ["C", "F"]) +@pytest.mark.parametrize("input_order", ["C", "F"]) +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_set_order_sparse(order, input_order, coo_container): + """Check that _set_order returns sparse matrices in promised format.""" + X = coo_container(np.array([[0], [0], [0]])) + y = coo_container(np.array([0, 0, 0])) + sparse_format = "csc" if input_order == "F" else "csr" + X = X.asformat(sparse_format) + y = X.asformat(sparse_format) + X2, y2 = _set_order(X, y, order=order) + + format = "csc" if order == "F" else "csr" + assert sparse.issparse(X2) and X2.format == format + assert sparse.issparse(y2) and y2.format == format + + +def test_lasso_zero(): + # Check that the lasso can handle zero data without crashing + X = [[0], [0], [0]] + y = [0, 0, 0] + # _cd_fast.pyx tests for gap < tol, but here we get 0.0 < 0.0 + # should probably be changed to gap <= tol ? + with ignore_warnings(category=ConvergenceWarning): + clf = Lasso(alpha=0.1).fit(X, y) + pred = clf.predict([[1], [2], [3]]) + assert_array_almost_equal(clf.coef_, [0]) + assert_array_almost_equal(pred, [0, 0, 0]) + assert_almost_equal(clf.dual_gap_, 0) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +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 + # against nobs. + + X = [[-1], [0], [1]] + Y = [-1, 0, 1] # just a straight line + T = [[2], [3], [4]] # test sample + + clf = Lasso(alpha=1e-8) + clf.fit(X, Y) + 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 = Lasso(alpha=0.1) + clf.fit(X, Y) + pred = clf.predict(T) + assert_array_almost_equal(clf.coef_, [0.85]) + assert_array_almost_equal(pred, [1.7, 2.55, 3.4]) + assert_almost_equal(clf.dual_gap_, 0) + + clf = Lasso(alpha=0.5) + clf.fit(X, Y) + pred = clf.predict(T) + assert_array_almost_equal(clf.coef_, [0.25]) + assert_array_almost_equal(pred, [0.5, 0.75, 1.0]) + assert_almost_equal(clf.dual_gap_, 0) + + clf = Lasso(alpha=1) + clf.fit(X, Y) + pred = clf.predict(T) + assert_array_almost_equal(clf.coef_, [0.0]) + assert_array_almost_equal(pred, [0, 0, 0]) + assert_almost_equal(clf.dual_gap_, 0) + + +def test_enet_toy(): + # Test ElasticNet for various parameters of alpha and l1_ratio. + # Actually, the parameters alpha = 0 should not be allowed. However, + # we test it as a border case. + # ElasticNet is tested with and without precomputed Gram matrix + + X = np.array([[-1.0], [0.0], [1.0]]) + Y = [-1, 0, 1] # just a straight line + T = [[2.0], [3.0], [4.0]] # test sample + + # this should be the same as lasso + clf = ElasticNet(alpha=1e-8, l1_ratio=1.0) + clf.fit(X, Y) + 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, max_iter=100, precompute=False) + clf.fit(X, Y) + 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.set_params(max_iter=100, precompute=True) + clf.fit(X, Y) # with Gram + 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.set_params(max_iter=100, precompute=np.dot(X.T, X)) + clf.fit(X, Y) # with Gram + 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) + 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) + assert_almost_equal(clf.dual_gap_, 0) + + +def test_lasso_dual_gap(): + """ + Check that Lasso.dual_gap_ matches its objective formulation, with the + datafit normalized by n_samples + """ + X, y, _, _ = build_dataset(n_samples=10, n_features=30) + n_samples = len(y) + alpha = 0.01 * np.max(np.abs(X.T @ y)) / n_samples + clf = Lasso(alpha=alpha, fit_intercept=False).fit(X, y) + w = clf.coef_ + R = y - X @ w + primal = 0.5 * np.mean(R**2) + clf.alpha * np.sum(np.abs(w)) + # dual pt: R / n_samples, dual constraint: norm(X.T @ theta, inf) <= alpha + R /= np.max(np.abs(X.T @ R) / (n_samples * alpha)) + dual = 0.5 * (np.mean(y**2) - np.mean((y - R) ** 2)) + assert_allclose(clf.dual_gap_, primal - dual) + + +def build_dataset(n_samples=50, n_features=200, n_informative_features=10, n_targets=1): + """ + build an ill-posed linear regression problem with many noisy features and + comparatively few samples + """ + random_state = np.random.RandomState(0) + if n_targets > 1: + w = random_state.randn(n_features, n_targets) + else: + w = random_state.randn(n_features) + w[n_informative_features:] = 0.0 + X = random_state.randn(n_samples, n_features) + y = np.dot(X, w) + X_test = random_state.randn(n_samples, n_features) + y_test = np.dot(X_test, w) + return X, y, X_test, y_test + + +def test_lasso_cv(): + X, y, X_test, y_test = build_dataset() + max_iter = 150 + clf = LassoCV(alphas=10, eps=1e-3, max_iter=max_iter, cv=3).fit(X, y) + assert_almost_equal(clf.alpha_, 0.056, 2) + + clf = LassoCV(alphas=10, eps=1e-3, max_iter=max_iter, precompute=True, cv=3) + clf.fit(X, y) + assert_almost_equal(clf.alpha_, 0.056, 2) + + # Check that the lars and the coordinate descent implementation + # select a similar alpha + lars = LassoLarsCV(max_iter=30, cv=3).fit(X, y) + # for this we check that they don't fall in the grid of + # clf.alphas further than 1 + assert ( + np.abs( + np.searchsorted(clf.alphas_[::-1], lars.alpha_) + - np.searchsorted(clf.alphas_[::-1], clf.alpha_) + ) + <= 1 + ) + # check that they also give a similar MSE + mse_lars = interpolate.interp1d(lars.cv_alphas_, lars.mse_path_.T) + assert_allclose(mse_lars(clf.alphas_[5]).mean(), clf.mse_path_[5].mean(), rtol=1e-2) + + # test set + assert clf.score(X_test, y_test) > 0.99 + + +def test_lasso_cv_with_some_model_selection(): + from sklearn import datasets + from sklearn.model_selection import ShuffleSplit + + diabetes = datasets.load_diabetes() + X = diabetes.data + y = diabetes.target + + pipe = make_pipeline(StandardScaler(), LassoCV(cv=ShuffleSplit(random_state=0))) + pipe.fit(X, y) + + +def test_lasso_cv_positive_constraint(): + X, y, X_test, y_test = build_dataset() + max_iter = 500 + + # Ensure the unconstrained fit has a negative coefficient + clf_unconstrained = LassoCV(alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1) + clf_unconstrained.fit(X, y) + assert min(clf_unconstrained.coef_) < 0 + + # On same data, constrained fit has non-negative coefficients + clf_constrained = LassoCV( + alphas=3, eps=1e-1, max_iter=max_iter, positive=True, cv=2, n_jobs=1 + ) + clf_constrained.fit(X, y) + assert min(clf_constrained.coef_) >= 0 + + +@pytest.mark.parametrize( + "alphas, err_type, err_msg", + [ + ((1, -1, -100), ValueError, r"alphas\[1\] == -1, must be >= 0.0."), + ( + (-0.1, -1.0, -10.0), + ValueError, + r"alphas\[0\] == -0.1, must be >= 0.0.", + ), + ( + (1, 1.0, "1"), + TypeError, + r"alphas\[2\] must be an instance of float, not str", + ), + ], +) +def test_lassocv_alphas_validation(alphas, err_type, err_msg): + """Check the `alphas` validation in LassoCV.""" + + n_samples, n_features = 5, 5 + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) + y = rng.randint(0, 2, n_samples) + lassocv = LassoCV(alphas=alphas) + with pytest.raises(err_type, match=err_msg): + lassocv.fit(X, y) + + +def _scale_alpha_inplace(estimator, n_samples): + """Rescale the parameter alpha from when the estimator is evoked with + normalize set to True as if it were evoked in a Pipeline with normalize set + to False and with a StandardScaler. + """ + if ("alpha" not in estimator.get_params()) and ( + "alphas" not in estimator.get_params() + ): + return + + if isinstance(estimator, (RidgeCV, RidgeClassifierCV)): + # alphas is not validated at this point and can be a list. + # We convert it to a np.ndarray to make sure broadcasting + # is used. + alphas = np.asarray(estimator.alphas) * n_samples + return estimator.set_params(alphas=alphas) + if isinstance(estimator, (Lasso, LassoLars, MultiTaskLasso)): + alpha = estimator.alpha * np.sqrt(n_samples) + if isinstance(estimator, (Ridge, RidgeClassifier)): + alpha = estimator.alpha * n_samples + if isinstance(estimator, (ElasticNet, MultiTaskElasticNet)): + if estimator.l1_ratio == 1: + alpha = estimator.alpha * np.sqrt(n_samples) + elif estimator.l1_ratio == 0: + alpha = estimator.alpha * n_samples + else: + # To avoid silent errors in case of refactoring + raise NotImplementedError + + estimator.set_params(alpha=alpha) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize( + "LinearModel, params", + [ + (Lasso, {"tol": 1e-16, "alpha": 0.1}), + (LassoCV, {"tol": 1e-16}), + (ElasticNetCV, {}), + (RidgeClassifier, {"solver": "sparse_cg", "alpha": 0.1}), + (ElasticNet, {"tol": 1e-16, "l1_ratio": 1, "alpha": 0.01}), + (ElasticNet, {"tol": 1e-16, "l1_ratio": 0, "alpha": 0.01}), + (Ridge, {"solver": "sparse_cg", "tol": 1e-12, "alpha": 0.1}), + (LinearRegression, {}), + (RidgeCV, {}), + (RidgeClassifierCV, {}), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_model_pipeline_same_dense_and_sparse(LinearModel, params, csr_container): + # Test that linear model preceded by StandardScaler in the pipeline and + # with normalize set to False gives the same y_pred and the same .coef_ + # given X sparse or dense + + model_dense = make_pipeline(StandardScaler(with_mean=False), LinearModel(**params)) + + model_sparse = make_pipeline(StandardScaler(with_mean=False), LinearModel(**params)) + + # prepare the data + rng = np.random.RandomState(0) + n_samples = 200 + n_features = 2 + X = rng.randn(n_samples, n_features) + X[X < 0.1] = 0.0 + + X_sparse = csr_container(X) + y = rng.rand(n_samples) + + if is_classifier(model_dense): + y = np.sign(y) + + model_dense.fit(X, y) + model_sparse.fit(X_sparse, y) + + assert_allclose(model_sparse[1].coef_, model_dense[1].coef_) + y_pred_dense = model_dense.predict(X) + y_pred_sparse = model_sparse.predict(X_sparse) + assert_allclose(y_pred_dense, y_pred_sparse) + + assert_allclose(model_dense[1].intercept_, model_sparse[1].intercept_) + + +def test_lasso_path_return_models_vs_new_return_gives_same_coefficients(): + # Test that lasso_path with lars_path style output gives the + # same result + + # Some toy data + X = np.array([[1, 2, 3.1], [2.3, 5.4, 4.3]]).T + y = np.array([1, 2, 3.1]) + alphas = [5.0, 1.0, 0.5] + + # Use lars_path and lasso_path(new output) with 1D linear interpolation + # to compute the same path + alphas_lars, _, coef_path_lars = lars_path(X, y, method="lasso") + coef_path_cont_lars = interpolate.interp1d( + alphas_lars[::-1], coef_path_lars[:, ::-1] + ) + alphas_lasso2, coef_path_lasso2, _ = lasso_path(X, y, alphas=alphas) + coef_path_cont_lasso = interpolate.interp1d( + alphas_lasso2[::-1], coef_path_lasso2[:, ::-1] + ) + + assert_array_almost_equal( + coef_path_cont_lasso(alphas), coef_path_cont_lars(alphas), decimal=1 + ) + + +def test_enet_path(): + # We use a large number of samples and of informative features so that + # the l1_ratio selected is more toward ridge than lasso + X, y, X_test, y_test = build_dataset( + n_samples=200, n_features=100, n_informative_features=100 + ) + max_iter = 150 + + # Here we have a small number of iterations, and thus the + # ElasticNet might not converge. This is to speed up tests + clf = ElasticNetCV( + alphas=[0.01, 0.05, 0.1], eps=2e-3, l1_ratio=[0.5, 0.7], cv=3, max_iter=max_iter + ) + ignore_warnings(clf.fit)(X, y) + # Well-conditioned settings, we should have selected our + # smallest penalty + assert_almost_equal(clf.alpha_, min(clf.alphas_)) + # Non-sparse ground truth: we should have selected an elastic-net + # that is closer to ridge than to lasso + assert clf.l1_ratio_ == min(clf.l1_ratio) + + clf = ElasticNetCV( + alphas=[0.01, 0.05, 0.1], + eps=2e-3, + l1_ratio=[0.5, 0.7], + cv=3, + max_iter=max_iter, + precompute=True, + ) + ignore_warnings(clf.fit)(X, y) + + # Well-conditioned settings, we should have selected our + # smallest penalty + assert_almost_equal(clf.alpha_, min(clf.alphas_)) + # Non-sparse ground truth: we should have selected an elastic-net + # that is closer to ridge than to lasso + assert clf.l1_ratio_ == min(clf.l1_ratio) + + # We are in well-conditioned settings with low noise: we should + # have a good test-set performance + assert clf.score(X_test, y_test) > 0.99 + + # Multi-output/target case + X, y, X_test, y_test = build_dataset(n_features=10, n_targets=3) + clf = MultiTaskElasticNetCV( + alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7], cv=3, max_iter=max_iter + ) + ignore_warnings(clf.fit)(X, y) + # We are in well-conditioned settings with low noise: we should + # have a good test-set performance + assert clf.score(X_test, y_test) > 0.99 + assert clf.coef_.shape == (3, 10) + + # Mono-output should have same cross-validated alpha_ and l1_ratio_ + # in both cases. + X, y, _, _ = build_dataset(n_features=10) + clf1 = ElasticNetCV(alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf1.fit(X, y) + clf2 = MultiTaskElasticNetCV(alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf2.fit(X, y[:, np.newaxis]) + assert_almost_equal(clf1.l1_ratio_, clf2.l1_ratio_) + assert_almost_equal(clf1.alpha_, clf2.alpha_) + + +def test_path_parameters(): + X, y, _, _ = build_dataset() + max_iter = 100 + + clf = ElasticNetCV(alphas=50, eps=1e-3, max_iter=max_iter, l1_ratio=0.5, tol=1e-3) + clf.fit(X, y) # new params + assert_almost_equal(0.5, clf.l1_ratio) + assert 50 == clf._alphas + assert 50 == len(clf.alphas_) + + +def test_warm_start(): + X, y, _, _ = build_dataset() + clf = ElasticNet(alpha=0.1, max_iter=5, warm_start=True) + ignore_warnings(clf.fit)(X, y) + ignore_warnings(clf.fit)(X, y) # do a second round with 5 iterations + + clf2 = ElasticNet(alpha=0.1, max_iter=10) + ignore_warnings(clf2.fit)(X, y) + assert_array_almost_equal(clf2.coef_, clf.coef_) + + +def test_lasso_alpha_warning(): + X = [[-1], [0], [1]] + Y = [-1, 0, 1] # just a straight line + + clf = Lasso(alpha=0) + warning_message = ( + "With alpha=0, this algorithm does not " + "converge well. You are advised to use the " + "LinearRegression estimator" + ) + with pytest.warns(UserWarning, match=warning_message): + clf.fit(X, Y) + + +def test_lasso_positive_constraint(): + X = [[-1], [0], [1]] + y = [1, 0, -1] # just a straight line with negative slope + + lasso = Lasso(alpha=0.1, positive=True) + lasso.fit(X, y) + assert min(lasso.coef_) >= 0 + + lasso = Lasso(alpha=0.1, precompute=True, positive=True) + lasso.fit(X, y) + assert min(lasso.coef_) >= 0 + + +def test_enet_positive_constraint(): + X = [[-1], [0], [1]] + y = [1, 0, -1] # just a straight line with negative slope + + enet = ElasticNet(alpha=0.1, positive=True) + enet.fit(X, y) + assert min(enet.coef_) >= 0 + + +def test_enet_cv_positive_constraint(): + X, y, X_test, y_test = build_dataset() + max_iter = 500 + + # Ensure the unconstrained fit has a negative coefficient + enetcv_unconstrained = ElasticNetCV( + alphas=3, eps=1e-1, max_iter=max_iter, cv=2, n_jobs=1 + ) + enetcv_unconstrained.fit(X, y) + assert min(enetcv_unconstrained.coef_) < 0 + + # On same data, constrained fit has non-negative coefficients + enetcv_constrained = ElasticNetCV( + alphas=3, eps=1e-1, max_iter=max_iter, cv=2, positive=True, n_jobs=1 + ) + enetcv_constrained.fit(X, y) + assert min(enetcv_constrained.coef_) >= 0 + + +def test_uniform_targets(): + enet = ElasticNetCV(alphas=3) + m_enet = MultiTaskElasticNetCV(alphas=3) + lasso = LassoCV(alphas=3) + m_lasso = MultiTaskLassoCV(alphas=3) + + models_single_task = (enet, lasso) + models_multi_task = (m_enet, m_lasso) + + rng = np.random.RandomState(0) + + X_train = rng.random_sample(size=(10, 3)) + X_test = rng.random_sample(size=(10, 3)) + + y1 = np.empty(10) + y2 = np.empty((10, 2)) + + for model in models_single_task: + for y_values in (0, 5): + y1.fill(y_values) + with ignore_warnings(category=ConvergenceWarning): + assert_array_equal(model.fit(X_train, y1).predict(X_test), y1) + assert_array_equal(model.alphas_, [np.finfo(float).resolution] * 3) + + for model in models_multi_task: + for y_values in (0, 5): + y2[:, 0].fill(y_values) + y2[:, 1].fill(2 * y_values) + with ignore_warnings(category=ConvergenceWarning): + assert_array_equal(model.fit(X_train, y2).predict(X_test), y2) + assert_array_equal(model.alphas_, [np.finfo(float).resolution] * 3) + + +def test_multi_task_lasso_and_enet(): + X, y, X_test, y_test = build_dataset() + Y = np.c_[y, y] + # Y_test = np.c_[y_test, y_test] + clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y) + assert 0 < clf.dual_gap_ < 1e-5 + assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) + + clf = MultiTaskElasticNet(alpha=1, tol=1e-8).fit(X, Y) + assert 0 < clf.dual_gap_ < 1e-5 + assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) + + clf = MultiTaskElasticNet(alpha=1.0, tol=1e-8, max_iter=1) + warning_message = ( + "Objective did not converge. You might want to " + "increase the number of iterations." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + clf.fit(X, Y) + + +def test_lasso_readonly_data(): + X = np.array([[-1], [0], [1]]) + Y = np.array([-1, 0, 1]) # just a straight line + T = np.array([[2], [3], [4]]) # test sample + with TempMemmap((X, Y)) as (X, Y): + clf = Lasso(alpha=0.5) + clf.fit(X, Y) + pred = clf.predict(T) + assert_array_almost_equal(clf.coef_, [0.25]) + assert_array_almost_equal(pred, [0.5, 0.75, 1.0]) + assert_almost_equal(clf.dual_gap_, 0) + + +def test_multi_task_lasso_readonly_data(): + X, y, X_test, y_test = build_dataset() + Y = np.c_[y, y] + with TempMemmap((X, Y)) as (X, Y): + Y = np.c_[y, y] + clf = MultiTaskLasso(alpha=1, tol=1e-8).fit(X, Y) + assert 0 < clf.dual_gap_ < 1e-5 + assert_array_almost_equal(clf.coef_[0], clf.coef_[1]) + + +def test_enet_multitarget(): + n_targets = 3 + X, y, _, _ = build_dataset( + n_samples=10, n_features=8, n_informative_features=10, n_targets=n_targets + ) + estimator = ElasticNet(alpha=0.01) + estimator.fit(X, y) + coef, intercept, dual_gap = ( + estimator.coef_, + estimator.intercept_, + estimator.dual_gap_, + ) + + for k in range(n_targets): + estimator.fit(X, y[:, k]) + assert_array_almost_equal(coef[k, :], estimator.coef_) + assert_array_almost_equal(intercept[k], estimator.intercept_) + assert_array_almost_equal(dual_gap[k], estimator.dual_gap_) + + +def test_multioutput_enetcv_error(): + rng = np.random.RandomState(0) + X = rng.randn(10, 2) + y = rng.randn(10, 2) + clf = ElasticNetCV() + with pytest.raises(ValueError): + clf.fit(X, y) + + +def test_multitask_enet_and_lasso_cv(): + X, y, _, _ = build_dataset(n_features=50, n_targets=3) + clf = MultiTaskElasticNetCV(cv=3).fit(X, y) + assert_almost_equal(clf.alpha_, 0.00556, 3) + clf = MultiTaskLassoCV(cv=3).fit(X, y) + assert_almost_equal(clf.alpha_, 0.00278, 3) + + X, y, _, _ = build_dataset(n_targets=3) + clf = MultiTaskElasticNetCV( + alphas=10, eps=1e-3, max_iter=200, l1_ratio=[0.3, 0.5], tol=1e-3, cv=3 + ) + clf.fit(X, y) + assert 0.5 == clf.l1_ratio_ + assert (3, X.shape[1]) == clf.coef_.shape + assert (3,) == clf.intercept_.shape + assert (2, 10, 3) == clf.mse_path_.shape + assert (2, 10) == clf.alphas_.shape + + X, y, _, _ = build_dataset(n_targets=3) + clf = MultiTaskLassoCV(alphas=10, eps=1e-3, max_iter=500, tol=1e-3, cv=3) + clf.fit(X, y) + assert (3, X.shape[1]) == clf.coef_.shape + assert (3,) == clf.intercept_.shape + assert (10, 3) == clf.mse_path_.shape + assert 10 == len(clf.alphas_) + + +def test_1d_multioutput_enet_and_multitask_enet_cv(): + X, y, _, _ = build_dataset(n_features=10) + y = y[:, np.newaxis] + clf = ElasticNetCV(alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf.fit(X, y[:, 0]) + clf1 = MultiTaskElasticNetCV(alphas=5, eps=2e-3, l1_ratio=[0.5, 0.7]) + clf1.fit(X, y) + assert_almost_equal(clf.l1_ratio_, clf1.l1_ratio_) + assert_almost_equal(clf.alpha_, clf1.alpha_) + assert_almost_equal(clf.coef_, clf1.coef_[0]) + assert_almost_equal(clf.intercept_, clf1.intercept_[0]) + + +def test_1d_multioutput_lasso_and_multitask_lasso_cv(): + X, y, _, _ = build_dataset(n_features=10) + y = y[:, np.newaxis] + clf = LassoCV(alphas=5, eps=2e-3) + clf.fit(X, y[:, 0]) + clf1 = MultiTaskLassoCV(alphas=5, eps=2e-3) + clf1.fit(X, y) + assert_almost_equal(clf.alpha_, clf1.alpha_) + assert_almost_equal(clf.coef_, clf1.coef_[0]) + assert_almost_equal(clf.intercept_, clf1.intercept_[0]) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_input_dtype_enet_and_lassocv(csr_container): + X, y, _, _ = build_dataset(n_features=10) + clf = ElasticNetCV(alphas=5) + clf.fit(csr_container(X), y) + clf1 = ElasticNetCV(alphas=5) + clf1.fit(csr_container(X, dtype=np.float32), y) + assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) + assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) + + clf = LassoCV(alphas=5) + clf.fit(csr_container(X), y) + clf1 = LassoCV(alphas=5) + clf1.fit(csr_container(X, dtype=np.float32), y) + assert_almost_equal(clf.alpha_, clf1.alpha_, decimal=6) + assert_almost_equal(clf.coef_, clf1.coef_, decimal=6) + + +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_elasticnet_precompute_gram(): + # Check the dtype-aware check for a precomputed Gram matrix + # (see https://github.com/scikit-learn/scikit-learn/pull/22059 + # and https://github.com/scikit-learn/scikit-learn/issues/21997). + # Here: (X_c.T, X_c)[2, 3] is not equal to np.dot(X_c[:, 2], X_c[:, 3]) + # but within tolerance for np.float32 + + rng = np.random.RandomState(58) + X = rng.binomial(1, 0.25, (1000, 4)).astype(np.float32) + y = rng.rand(1000).astype(np.float32) + + X_c = X - np.average(X, axis=0) + gram = np.dot(X_c.T, X_c) + + clf1 = ElasticNet(alpha=0.01, precompute=gram) + clf1.fit(X_c, y) + + clf2 = ElasticNet(alpha=0.01, precompute=False) + clf2.fit(X, y) + + 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) + n_iter_reference = model.n_iter_ + + # This dataset is not trivial enough for the model to converge in one pass. + assert n_iter_reference > 2 + + # Check that n_iter_ is invariant to multiple calls to fit + # when warm_start=False, all else being equal. + model.fit(X, y) + n_iter_cold_start = model.n_iter_ + assert n_iter_cold_start == n_iter_reference + + # Fit the same model again, using a warm start: the optimizer just performs + # a single pass before checking that it has already converged + model.set_params(warm_start=True) + model.fit(X, y) + n_iter_warm_start = model.n_iter_ + assert n_iter_warm_start == 1 + + +def test_warm_start_convergence_with_regularizer_decrement(): + X, y = load_diabetes(return_X_y=True) + + # Train a model to converge on a lightly regularized problem + final_alpha = 1e-5 + low_reg_model = ElasticNet(alpha=final_alpha).fit(X, y) + + # Fitting a new model on a more regularized version of the same problem. + # Fitting with high regularization is easier it should converge faster + # in general. + high_reg_model = ElasticNet(alpha=final_alpha * 10).fit(X, y) + assert low_reg_model.n_iter_ > high_reg_model.n_iter_ + + # Fit the solution to the original, less regularized version of the + # problem but from the solution of the highly regularized variant of + # the problem as a better starting point. This should also converge + # faster than the original model that starts from zero. + warm_low_reg_model = deepcopy(high_reg_model) + warm_low_reg_model.set_params(warm_start=True, alpha=final_alpha) + warm_low_reg_model.fit(X, y) + assert low_reg_model.n_iter_ > warm_low_reg_model.n_iter_ + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_random_descent(csr_container): + # Test that both random and cyclic selection give the same results. + # Ensure that the test models fully converge and check a wide + # range of conditions. + + # This uses the coordinate descent algo using the gram trick. + X, y, _, _ = build_dataset(n_samples=50, n_features=20) + clf_cyclic = ElasticNet(selection="cyclic", tol=1e-8) + clf_cyclic.fit(X, y) + clf_random = ElasticNet(selection="random", tol=1e-8, random_state=42) + clf_random.fit(X, y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # This uses the descent algo without the gram trick + clf_cyclic = ElasticNet(selection="cyclic", tol=1e-8) + clf_cyclic.fit(X.T, y[:20]) + clf_random = ElasticNet(selection="random", tol=1e-8, random_state=42) + clf_random.fit(X.T, y[:20]) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # Sparse Case + clf_cyclic = ElasticNet(selection="cyclic", tol=1e-8) + clf_cyclic.fit(csr_container(X), y) + clf_random = ElasticNet(selection="random", tol=1e-8, random_state=42) + clf_random.fit(csr_container(X), y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + # Multioutput case. + new_y = np.hstack((y[:, np.newaxis], y[:, np.newaxis])) + clf_cyclic = MultiTaskElasticNet(selection="cyclic", tol=1e-8) + clf_cyclic.fit(X, new_y) + clf_random = MultiTaskElasticNet(selection="random", tol=1e-8, random_state=42) + clf_random.fit(X, new_y) + assert_array_almost_equal(clf_cyclic.coef_, clf_random.coef_) + assert_almost_equal(clf_cyclic.intercept_, clf_random.intercept_) + + +def test_enet_path_positive(): + # Test positive parameter + + X, Y, _, _ = build_dataset(n_samples=50, n_features=50, n_targets=2) + + # For mono output + # Test that the coefs returned by positive=True in enet_path are positive + for path in [enet_path, lasso_path]: + pos_path_coef = path(X, Y[:, 0], positive=True)[1] + assert np.all(pos_path_coef >= 0) + + # For multi output, positive parameter is not allowed + # Test that an error is raised + for path in [enet_path, lasso_path]: + with pytest.raises(ValueError): + path(X, Y, positive=True) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_dense_descent_paths(csr_container): + # Test that dense and sparse input give the same input for descent paths. + X, y, _, _ = build_dataset(n_samples=50, n_features=20) + csr = csr_container(X) + for path in [enet_path, lasso_path]: + _, coefs, _ = path(X, y) + _, sparse_coefs, _ = path(csr, y) + assert_array_almost_equal(coefs, sparse_coefs) + + +@pytest.mark.parametrize("path_func", [enet_path, lasso_path]) +def test_path_unknown_parameter(path_func): + """Check that passing parameter not used by the coordinate descent solver + will raise an error.""" + X, y, _, _ = build_dataset(n_samples=50, n_features=20) + err_msg = "Unexpected parameters in params" + with pytest.raises(ValueError, match=err_msg): + path_func(X, y, normalize=True, fit_intercept=True) + + +def test_check_input_false(): + X, y, _, _ = build_dataset(n_samples=20, n_features=10) + X = check_array(X, order="F", dtype="float64") + y = check_array(X, order="F", dtype="float64") + clf = ElasticNet(selection="cyclic", tol=1e-8) + # Check that no error is raised if data is provided in the right format + clf.fit(X, y, check_input=False) + # With check_input=False, an exhaustive check is not made on y but its + # dtype is still cast in _preprocess_data to X's dtype. So the test should + # pass anyway + X = check_array(X, order="F", dtype="float32") + with ignore_warnings(category=ConvergenceWarning): + clf.fit(X, y, check_input=False) + # With no input checking, providing X in C order should result in false + # computation + X = check_array(X, order="C", dtype="float64") + with pytest.raises(ValueError): + clf.fit(X, y, check_input=False) + + +@pytest.mark.parametrize("check_input", [True, False]) +def test_enet_copy_X_True(check_input): + X, y, _, _ = build_dataset() + X = X.copy(order="F") + + original_X = X.copy() + enet = ElasticNet(copy_X=True) + enet.fit(X, y, check_input=check_input) + + assert_array_equal(original_X, X) + + +def test_enet_copy_X_False_check_input_False(): + X, y, _, _ = build_dataset() + X = X.copy(order="F") + + original_X = X.copy() + enet = ElasticNet(copy_X=False) + enet.fit(X, y, check_input=False) + + # No copying, X is overwritten + assert np.any(np.not_equal(original_X, X)) + + +def test_overrided_gram_matrix(): + X, y, _, _ = build_dataset(n_samples=20, n_features=10) + Gram = X.T.dot(X) + clf = ElasticNet(selection="cyclic", tol=1e-8, precompute=Gram) + warning_message = ( + "Gram matrix was provided but X was centered" + " to fit intercept: recomputing Gram matrix." + ) + with pytest.warns(UserWarning, match=warning_message): + clf.fit(X, y) + + +@pytest.mark.parametrize("model", [ElasticNet, Lasso]) +def test_lasso_non_float_y(model): + X = [[0, 0], [1, 1], [-1, -1]] + y = [0, 1, 2] + y_float = [0.0, 1.0, 2.0] + + clf = model(fit_intercept=False) + clf.fit(X, y) + clf_float = model(fit_intercept=False) + clf_float.fit(X, y_float) + assert_array_equal(clf.coef_, clf_float.coef_) + + +def test_enet_float_precision(): + # Generate dataset + X, y, X_test, y_test = build_dataset(n_samples=20, n_features=10) + # Here we have a small number of iterations, and thus the + # ElasticNet might not converge. This is to speed up tests + + for fit_intercept in [True, False]: + coef = {} + intercept = {} + for dtype in [np.float64, np.float32]: + clf = ElasticNet( + alpha=0.5, + max_iter=100, + precompute=False, + fit_intercept=fit_intercept, + ) + + X = dtype(X) + y = dtype(y) + ignore_warnings(clf.fit)(X, y) + + coef[("simple", dtype)] = clf.coef_ + intercept[("simple", dtype)] = clf.intercept_ + + assert clf.coef_.dtype == dtype + + # test precompute Gram array + Gram = X.T.dot(X) + clf_precompute = ElasticNet( + alpha=0.5, + max_iter=100, + precompute=Gram, + fit_intercept=fit_intercept, + ) + ignore_warnings(clf_precompute.fit)(X, y) + assert_array_almost_equal(clf.coef_, clf_precompute.coef_) + assert_array_almost_equal(clf.intercept_, clf_precompute.intercept_) + + # test multi task enet + multi_y = np.hstack((y[:, np.newaxis], y[:, np.newaxis])) + clf_multioutput = MultiTaskElasticNet( + alpha=0.5, + max_iter=100, + fit_intercept=fit_intercept, + ) + clf_multioutput.fit(X, multi_y) + coef[("multi", dtype)] = clf_multioutput.coef_ + intercept[("multi", dtype)] = clf_multioutput.intercept_ + assert clf.coef_.dtype == dtype + + for v in ["simple", "multi"]: + assert_array_almost_equal( + coef[(v, np.float32)], coef[(v, np.float64)], decimal=4 + ) + assert_array_almost_equal( + intercept[(v, np.float32)], intercept[(v, np.float64)], decimal=4 + ) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_enet_l1_ratio(): + # Test that an error message is raised if an estimator that + # uses _alpha_grid is called with l1_ratio=0 + msg = ( + "Automatic alpha grid generation is not supported for l1_ratio=0. " + "Please supply a grid by providing your estimator with the " + "appropriate `alphas=` argument." + ) + X = np.array([[1, 2, 4, 5, 8], [3, 5, 7, 7, 8]]).T + y = np.array([12, 10, 11, 21, 5]) + + with pytest.raises(ValueError, match=msg): + ElasticNetCV(l1_ratio=0, random_state=42).fit(X, y) + + with pytest.raises(ValueError, match=msg): + MultiTaskElasticNetCV(l1_ratio=0, random_state=42).fit(X, y[:, None]) + + # Test that l1_ratio=0 with alpha>0 produces user warning + warning_message = ( + "Coordinate descent without L1 regularization may " + "lead to unexpected results and is discouraged. " + "Set l1_ratio > 0 to add L1 regularization." + ) + est = ElasticNetCV(l1_ratio=[0], alphas=[1]) + with pytest.warns(UserWarning, match=warning_message): + est.fit(X, y) + + # Test that l1_ratio=0 is allowed if we supply a grid manually + alphas = [0.1, 10] + estkwds = {"alphas": alphas, "random_state": 42} + est_desired = ElasticNetCV(l1_ratio=0.00001, **estkwds) + est = ElasticNetCV(l1_ratio=0, **estkwds) + with ignore_warnings(): + est_desired.fit(X, y) + est.fit(X, y) + assert_array_almost_equal(est.coef_, est_desired.coef_, decimal=5) + + est_desired = MultiTaskElasticNetCV(l1_ratio=0.00001, **estkwds) + est = MultiTaskElasticNetCV(l1_ratio=0, **estkwds) + with ignore_warnings(): + est.fit(X, y[:, None]) + est_desired.fit(X, y[:, None]) + assert_array_almost_equal(est.coef_, est_desired.coef_, decimal=5) + + +def test_coef_shape_not_zero(): + est_no_intercept = Lasso(fit_intercept=False) + est_no_intercept.fit(np.c_[np.ones(3)], np.ones(3)) + assert est_no_intercept.coef_.shape == (1,) + + +def test_warm_start_multitask_lasso(): + X, y, X_test, y_test = build_dataset() + Y = np.c_[y, y] + clf = MultiTaskLasso(alpha=0.1, max_iter=5, warm_start=True) + ignore_warnings(clf.fit)(X, Y) + ignore_warnings(clf.fit)(X, Y) # do a second round with 5 iterations + + clf2 = MultiTaskLasso(alpha=0.1, max_iter=10) + ignore_warnings(clf2.fit)(X, Y) + assert_array_almost_equal(clf2.coef_, clf.coef_) + + +@pytest.mark.parametrize( + "klass, n_classes, kwargs", + [ + (Lasso, 1, dict(precompute=True)), + (Lasso, 1, dict(precompute=False)), + ], +) +def test_enet_coordinate_descent(klass, n_classes, kwargs): + """Test that a warning is issued if model does not converge""" + clf = klass(max_iter=2, **kwargs) + n_samples = 5 + n_features = 2 + X = np.ones((n_samples, n_features)) * 1e50 + y = np.ones((n_samples, n_classes)) + if klass == Lasso: + y = y.ravel() + warning_message = ( + "Objective did not converge. You might want to" + " increase the number of iterations." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + clf.fit(X, y) + + +def test_convergence_warnings(): + random_state = np.random.RandomState(0) + X = random_state.standard_normal((1000, 500)) + y = random_state.standard_normal((1000, 3)) + + # check that the model converges w/o convergence warnings + with warnings.catch_warnings(): + warnings.simplefilter("error", ConvergenceWarning) + MultiTaskElasticNet().fit(X, y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_input_convergence_warning(csr_container): + X, y, _, _ = build_dataset(n_samples=1000, n_features=500) + + with pytest.warns(ConvergenceWarning): + ElasticNet(max_iter=1, tol=0).fit(csr_container(X, dtype=np.float32), y) + + # check that the model converges w/o convergence warnings + with warnings.catch_warnings(): + warnings.simplefilter("error", ConvergenceWarning) + Lasso().fit(csr_container(X, dtype=np.float32), y) + + +@pytest.mark.parametrize( + "precompute, inner_precompute", + [ + (True, True), + ("auto", False), + (False, False), + ], +) +def test_lassoCV_does_not_set_precompute(monkeypatch, precompute, inner_precompute): + X, y, _, _ = build_dataset() + calls = 0 + + class LassoMock(Lasso): + def fit(self, X, y): + super().fit(X, y) + nonlocal calls + calls += 1 + assert self.precompute == inner_precompute + + monkeypatch.setattr("sklearn.linear_model._coordinate_descent.Lasso", LassoMock) + clf = LassoCV(precompute=precompute) + clf.fit(X, y) + assert calls > 0 + + +def test_multi_task_lasso_cv_dtype(): + n_samples, n_features = 10, 3 + rng = np.random.RandomState(42) + X = rng.binomial(1, 0.5, size=(n_samples, n_features)) + X = X.astype(int) # make it explicit that X is int + y = X[:, [0, 0]].copy() + est = MultiTaskLassoCV(alphas=5, fit_intercept=True).fit(X, y) + assert_array_almost_equal(est.coef_, [[1, 0, 0]] * 2, decimal=3) + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("alpha", [0.01]) +@pytest.mark.parametrize("precompute", [False, True]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_enet_sample_weight_consistency( + fit_intercept, alpha, precompute, sparse_container, global_random_seed +): + """Test that the impact of sample_weight is consistent. + + Note that this test is stricter than the common test + check_sample_weight_equivalence alone and also tests sparse X. + """ + rng = np.random.RandomState(global_random_seed) + n_samples, n_features = 10, 5 + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + if sparse_container is not None: + X = sparse_container(X) + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + precompute=precompute, + tol=1e-6, + l1_ratio=0.5, + ) + + reg = ElasticNet(**params).fit(X, y) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + + # 1) sample_weight=np.ones(..) should be equivalent to sample_weight=None + sample_weight = np.ones_like(y) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 2) sample_weight=None should be equivalent to sample_weight = number + sample_weight = 123.0 + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 3) scaling of sample_weight should have no effect, cf. np.average() + sample_weight = rng.uniform(low=0.01, high=2, size=X.shape[0]) + reg = reg.fit(X, y, sample_weight=sample_weight) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + + reg.fit(X, y, sample_weight=np.pi * sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 4) setting elements of sample_weight to 0 is equivalent to removing these samples + sample_weight_0 = sample_weight.copy() + sample_weight_0[-5:] = 0 + y[-5:] *= 1000 # to make excluding those samples important + reg.fit(X, y, sample_weight=sample_weight_0) + coef_0 = reg.coef_.copy() + if fit_intercept: + intercept_0 = reg.intercept_ + reg.fit(X[:-5], y[:-5], sample_weight=sample_weight[:-5]) + assert_allclose(reg.coef_, coef_0, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept_0) + + # 5) check that multiplying sample_weight by 2 is equivalent to repeating + # corresponding samples twice + if sparse_container is not None: + 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 = sample_weight.copy() + sample_weight_1[: n_samples // 2] *= 2 + sample_weight_2 = np.concatenate( + [sample_weight, sample_weight[: n_samples // 2]], axis=0 + ) + + reg1 = ElasticNet(**params).fit(X, y, sample_weight=sample_weight_1) + reg2 = ElasticNet(**params).fit(X2, y2, sample_weight=sample_weight_2) + assert_allclose(reg1.coef_, reg2.coef_, rtol=1e-6) + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS) +def test_enet_cv_sample_weight_correctness( + fit_intercept, sparse_container, global_random_seed +): + """Test that ElasticNetCV with sample weights gives correct results. + + We fit the same model twice, once with weighted training data, once with repeated + data points in the training data and check that both models converge to the + same solution. + + Since this model uses an internal cross-validation scheme to tune the alpha + regularization parameter, we make sure that the repetitions only occur within + a specific CV group. Data points belonging to other CV groups stay + unit-weighted / "unrepeated". + """ + rng = np.random.RandomState(global_random_seed) + n_splits, n_samples_per_cv, n_features = 3, 10, 5 + X_with_weights = rng.rand(n_splits * n_samples_per_cv, n_features) + beta = rng.rand(n_features) + beta[0:2] = 0 + y_with_weights = X_with_weights @ beta + rng.rand(n_splits * n_samples_per_cv) + + if sparse_container is not None: + X_with_weights = sparse_container(X_with_weights) + params = dict(tol=1e-6) + + # Assign random integer weights only to the first cross-validation group. + # The samples in the other cross-validation groups are left with unit + # weights. + + sw = np.ones_like(y_with_weights) + sw[:n_samples_per_cv] = rng.randint(0, 5, size=n_samples_per_cv) + groups_with_weights = np.concatenate( + [ + np.full(n_samples_per_cv, 0), + np.full(n_samples_per_cv, 1), + np.full(n_samples_per_cv, 2), + ] + ) + splits_with_weights = list( + LeaveOneGroupOut().split(X_with_weights, groups=groups_with_weights) + ) + reg_with_weights = ElasticNetCV( + cv=splits_with_weights, fit_intercept=fit_intercept, **params + ) + + reg_with_weights.fit(X_with_weights, y_with_weights, sample_weight=sw) + + if sparse_container is not None: + X_with_weights = X_with_weights.toarray() + X_with_repetitions = np.repeat(X_with_weights, sw.astype(int), axis=0) + if sparse_container is not None: + X_with_repetitions = sparse_container(X_with_repetitions) + + y_with_repetitions = np.repeat(y_with_weights, sw.astype(int), axis=0) + groups_with_repetitions = np.repeat(groups_with_weights, sw.astype(int), axis=0) + + splits_with_repetitions = list( + LeaveOneGroupOut().split(X_with_repetitions, groups=groups_with_repetitions) + ) + reg_with_repetitions = ElasticNetCV( + cv=splits_with_repetitions, fit_intercept=fit_intercept, **params + ) + reg_with_repetitions.fit(X_with_repetitions, y_with_repetitions) + + # Check that the alpha selection process is the same: + assert_allclose(reg_with_weights.mse_path_, reg_with_repetitions.mse_path_) + assert_allclose(reg_with_weights.alphas_, reg_with_repetitions.alphas_) + assert reg_with_weights.alpha_ == pytest.approx(reg_with_repetitions.alpha_) + + # Check that the final model coefficients are the same: + assert_allclose(reg_with_weights.coef_, reg_with_repetitions.coef_, atol=1e-10) + assert reg_with_weights.intercept_ == pytest.approx(reg_with_repetitions.intercept_) + + +@pytest.mark.parametrize("sample_weight", [False, True]) +def test_enet_cv_grid_search(sample_weight): + """Test that ElasticNetCV gives same result as GridSearchCV.""" + n_samples, n_features = 200, 10 + cv = 5 + X, y = make_regression( + n_samples=n_samples, + n_features=n_features, + effective_rank=10, + n_informative=n_features - 4, + noise=10, + random_state=0, + ) + if sample_weight: + sample_weight = np.linspace(1, 5, num=n_samples) + else: + sample_weight = None + + alphas = np.logspace(np.log10(1e-5), np.log10(1), num=10) + l1_ratios = [0.1, 0.5, 0.9] + reg = ElasticNetCV(cv=cv, alphas=alphas, l1_ratio=l1_ratios) + reg.fit(X, y, sample_weight=sample_weight) + + param = {"alpha": alphas, "l1_ratio": l1_ratios} + gs = GridSearchCV( + estimator=ElasticNet(), + param_grid=param, + cv=cv, + scoring="neg_mean_squared_error", + ).fit(X, y, sample_weight=sample_weight) + + assert reg.l1_ratio_ == pytest.approx(gs.best_params_["l1_ratio"]) + assert reg.alpha_ == pytest.approx(gs.best_params_["alpha"]) + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("l1_ratio", [0, 0.5, 1]) +@pytest.mark.parametrize("precompute", [False, True]) +@pytest.mark.parametrize("sparse_container", [None] + CSC_CONTAINERS) +def test_enet_cv_sample_weight_consistency( + fit_intercept, l1_ratio, precompute, sparse_container +): + """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 = X.sum(axis=1) + rng.rand(n_samples) + params = dict( + l1_ratio=l1_ratio, + fit_intercept=fit_intercept, + precompute=precompute, + tol=1e-6, + cv=3, + ) + if sparse_container is not None: + X = sparse_container(X) + + if l1_ratio == 0: + params.pop("l1_ratio", None) + reg = LassoCV(**params).fit(X, y) + else: + reg = ElasticNetCV(**params).fit(X, y) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + + # sample_weight=np.ones(..) should be equivalent to sample_weight=None + sample_weight = np.ones_like(y) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # sample_weight=None should be equivalent to sample_weight = number + sample_weight = 123.0 + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # scaling of sample_weight should have no effect, cf. np.average() + sample_weight = 2 * np.ones_like(y) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + +@pytest.mark.parametrize("X_is_sparse", [False, True]) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("sample_weight", [np.array([10, 1, 10, 1]), None]) +def test_enet_alpha_max_sample_weight(X_is_sparse, fit_intercept, sample_weight): + X = np.array([[3.0, 1.0], [2.0, 5.0], [5.0, 3.0], [1.0, 4.0]]) + beta = np.array([1, 1]) + y = X @ beta + if X_is_sparse: + X = sparse.csc_matrix(X) + # Test alpha_max makes coefs zero. + reg = ElasticNetCV(alphas=1, cv=2, eps=1, fit_intercept=fit_intercept) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, 0, atol=1e-5) + alpha_max = reg.alpha_ + # Test smaller alpha makes coefs nonzero. + reg = ElasticNet(alpha=0.99 * alpha_max, fit_intercept=fit_intercept) + reg.fit(X, y, sample_weight=sample_weight) + assert_array_less(1e-3, np.max(np.abs(reg.coef_))) + + +@pytest.mark.parametrize("estimator", [ElasticNetCV, LassoCV]) +def test_linear_models_cv_fit_with_loky(estimator): + # LinearModelsCV.fit performs operations on fancy-indexed memmapped + # data when using the loky backend, causing an error due to unexpected + # behavior of fancy indexing of read-only memmaps (cf. numpy#14132). + + # Create a problem sufficiently large to cause memmapping (1MB). + # Unfortunately the scikit-learn and joblib APIs do not make it possible to + # change the max_nbyte of the inner Parallel call. + X, y = make_regression(int(1e6) // 8 + 1, 1) + assert X.nbytes > 1e6 # 1 MB + with joblib.parallel_backend("loky"): + estimator(n_jobs=2, cv=3).fit(X, y) + + +@pytest.mark.parametrize("check_input", [True, False]) +def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input): + """Check that ElasticNet does not overwrite sample_weights.""" + + rng = np.random.RandomState(0) + n_samples, n_features = 10, 5 + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + + sample_weight_1_25 = 1.25 * np.ones_like(y) + sample_weight = sample_weight_1_25.copy() + + reg = ElasticNet() + reg.fit(X, y, sample_weight=sample_weight, check_input=check_input) + + assert_array_equal(sample_weight, sample_weight_1_25) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +@pytest.mark.parametrize("ridge_alpha", [1e-1, 1.0, 1e6]) +def test_enet_ridge_consistency(ridge_alpha): + # Check that ElasticNet(l1_ratio=0) converges to the same solution as Ridge + # provided that the value of alpha is adapted. + # + # XXX: this test does not pass for weaker regularization (lower values of + # ridge_alpha): it could be either a problem of ElasticNet or Ridge (less + # likely) and depends on the dataset statistics: lower values for + # effective_rank are more problematic in particular. + + rng = np.random.RandomState(42) + n_samples = 300 + X, y = make_regression( + n_samples=n_samples, + n_features=100, + effective_rank=10, + n_informative=50, + random_state=rng, + ) + sw = rng.uniform(low=0.01, high=10, size=X.shape[0]) + alpha = 1.0 + common_params = dict( + tol=1e-12, + ) + ridge = Ridge(alpha=alpha, **common_params).fit(X, y, sample_weight=sw) + + alpha_enet = alpha / sw.sum() + enet = ElasticNet(alpha=alpha_enet, l1_ratio=0, **common_params).fit( + X, y, sample_weight=sw + ) + assert_allclose(ridge.coef_, enet.coef_) + assert_allclose(ridge.intercept_, enet.intercept_) + + +@pytest.mark.parametrize( + "estimator", + [ + Lasso(alpha=1.0), + ElasticNet(alpha=1.0, l1_ratio=0.1), + ], +) +def test_sample_weight_invariance(estimator): + rng = np.random.RandomState(42) + X, y = make_regression( + n_samples=100, + n_features=300, + effective_rank=10, + n_informative=50, + random_state=rng, + ) + sw = rng.uniform(low=0.01, high=2, size=X.shape[0]) + params = dict(tol=1e-12) + + # Check that setting some weights to 0 is equivalent to trimming the + # samples: + cutoff = X.shape[0] // 3 + sw_with_null = sw.copy() + sw_with_null[:cutoff] = 0.0 + X_trimmed, y_trimmed = X[cutoff:, :], y[cutoff:] + sw_trimmed = sw[cutoff:] + + reg_trimmed = ( + clone(estimator) + .set_params(**params) + .fit(X_trimmed, y_trimmed, sample_weight=sw_trimmed) + ) + reg_null_weighted = ( + clone(estimator).set_params(**params).fit(X, y, sample_weight=sw_with_null) + ) + assert_allclose(reg_null_weighted.coef_, reg_trimmed.coef_) + assert_allclose(reg_null_weighted.intercept_, reg_trimmed.intercept_) + + # Check that duplicating the training dataset is equivalent to multiplying + # the weights by 2: + X_dup = np.concatenate([X, X], axis=0) + y_dup = np.concatenate([y, y], axis=0) + sw_dup = np.concatenate([sw, sw], axis=0) + + reg_2sw = clone(estimator).set_params(**params).fit(X, y, sample_weight=2 * sw) + reg_dup = ( + clone(estimator).set_params(**params).fit(X_dup, y_dup, sample_weight=sw_dup) + ) + + assert_allclose(reg_2sw.coef_, reg_dup.coef_) + assert_allclose(reg_2sw.intercept_, reg_dup.intercept_) + + +def test_read_only_buffer(): + """Test that sparse coordinate descent works for read-only buffers""" + + rng = np.random.RandomState(0) + clf = ElasticNet(alpha=0.1, copy_X=True, random_state=rng) + X = np.asfortranarray(rng.uniform(size=(100, 10))) + X.setflags(write=False) + + y = rng.rand(100) + clf.fit(X, y) + + +@pytest.mark.parametrize( + "EstimatorCV", + [ElasticNetCV, LassoCV, MultiTaskElasticNetCV, MultiTaskLassoCV], +) +def test_cv_estimators_reject_params_with_no_routing_enabled(EstimatorCV): + """Check that the models inheriting from class:`LinearModelCV` raise an + error when any `params` are passed when routing is not enabled. + """ + X, y = make_regression(random_state=42) + groups = np.array([0, 1] * (len(y) // 2)) + estimator = EstimatorCV() + msg = "is only supported if enable_metadata_routing=True" + with pytest.raises(ValueError, match=msg): + estimator.fit(X, y, groups=groups) + + +@pytest.mark.parametrize( + "MultiTaskEstimatorCV", + [MultiTaskElasticNetCV, MultiTaskLassoCV], +) +@config_context(enable_metadata_routing=True) +def test_multitask_cv_estimators_with_sample_weight(MultiTaskEstimatorCV): + """Check that for :class:`MultiTaskElasticNetCV` and + class:`MultiTaskLassoCV` if `sample_weight` is passed and the + CV splitter does not support `sample_weight` an error is raised. + On the other hand if the splitter does support `sample_weight` + while `sample_weight` is passed there is no error and process + completes smoothly as before. + """ + + class CVSplitter(GroupsConsumerMixin, BaseCrossValidator): + def get_n_splits(self, X=None, y=None, groups=None, metadata=None): + pass # pragma: nocover + + class CVSplitterSampleWeight(CVSplitter): + def split(self, X, y=None, groups=None, sample_weight=None): + split_index = len(X) // 2 + train_indices = list(range(0, split_index)) + test_indices = list(range(split_index, len(X))) + yield test_indices, train_indices + yield train_indices, test_indices + + X, y = make_regression(random_state=42, n_targets=2) + sample_weight = np.ones(X.shape[0]) + + # If CV splitter does not support sample_weight an error is raised + splitter = CVSplitter().set_split_request(groups=True) + estimator = MultiTaskEstimatorCV(cv=splitter) + msg = "do not support sample weights" + with pytest.raises(ValueError, match=msg): + estimator.fit(X, y, sample_weight=sample_weight) + + # If CV splitter does support sample_weight no error is raised + splitter = CVSplitterSampleWeight().set_split_request( + groups=True, sample_weight=True + ) + estimator = MultiTaskEstimatorCV(cv=splitter) + estimator.fit(X, y, sample_weight=sample_weight) + + +# TODO(1.9): remove +@pytest.mark.parametrize( + "Estimator", [LassoCV, ElasticNetCV, MultiTaskLassoCV, MultiTaskElasticNetCV] +) +def test_linear_model_cv_deprecated_n_alphas(Estimator): + """Check the deprecation of n_alphas in favor of alphas.""" + X, y = make_regression(n_targets=2, random_state=42) + + # Asses warning message raised by LinearModelCV when n_alphas is used + with pytest.warns( + FutureWarning, + match="'n_alphas' was deprecated in 1.7 and will be removed in 1.9", + ): + clf = Estimator(n_alphas=5) + if clf._is_multitask(): + clf = clf.fit(X, y) + else: + clf = clf.fit(X, y[:, 0]) + + # Asses no warning message raised when n_alphas is not used + with warnings.catch_warnings(): + warnings.simplefilter("error") + clf = Estimator(alphas=5) + if clf._is_multitask(): + clf = clf.fit(X, y) + else: + clf = clf.fit(X, y[:, 0]) + + +# TODO(1.9): remove +@pytest.mark.parametrize( + "Estimator", [ElasticNetCV, LassoCV, MultiTaskLassoCV, MultiTaskElasticNetCV] +) +def test_linear_model_cv_deprecated_alphas_none(Estimator): + """Check the deprecation of alphas=None.""" + X, y = make_regression(n_targets=2, random_state=42) + + with pytest.warns( + FutureWarning, match="'alphas=None' is deprecated and will be removed in 1.9" + ): + clf = Estimator(alphas=None) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + + +# TODO(1.9): remove +@pytest.mark.parametrize( + "Estimator", [ElasticNetCV, LassoCV, MultiTaskLassoCV, MultiTaskElasticNetCV] +) +def test_linear_model_cv_alphas_n_alphas_unset(Estimator): + """Check that no warning is raised when both n_alphas and alphas are unset.""" + X, y = make_regression(n_targets=2, random_state=42) + + # Asses no warning message raised when n_alphas is not used + with warnings.catch_warnings(): + warnings.simplefilter("error") + clf = Estimator() + if clf._is_multitask(): + clf = clf.fit(X, y) + else: + clf = clf.fit(X, y[:, 0]) + + +# TODO(1.9): remove +@pytest.mark.filterwarnings("ignore:'n_alphas' was deprecated in 1.7") +@pytest.mark.parametrize( + "Estimator", [ElasticNetCV, LassoCV, MultiTaskLassoCV, MultiTaskElasticNetCV] +) +def test_linear_model_cv_alphas(Estimator): + """Check that the behavior of alphas is consistent with n_alphas.""" + X, y = make_regression(n_targets=2, random_state=42) + + # n_alphas is set, alphas is not => n_alphas is used + clf = Estimator(n_alphas=5) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 5 + + # n_alphas is set, alphas is set => alphas has priority + clf = Estimator(n_alphas=5, alphas=10) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 10 + + # same with alphas array-like + clf = Estimator(n_alphas=5, alphas=np.arange(10)) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 10 + + # n_alphas is not set, alphas is set => alphas is used + clf = Estimator(alphas=10) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 10 + + # same with alphas array-like + clf = Estimator(alphas=np.arange(10)) + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 10 + + # both are not set => default = 100 + clf = Estimator() + if clf._is_multitask(): + clf.fit(X, y) + else: + clf.fit(X, y[:, 0]) + assert len(clf.alphas_) == 100 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_huber.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_huber.py new file mode 100644 index 0000000000000000000000000000000000000000..9c0c7d213ee27a9d3d2ee8030f638dfe7a1325c7 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_huber.py @@ -0,0 +1,216 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +import pytest +from scipy import optimize + +from sklearn.datasets import make_regression +from sklearn.linear_model import HuberRegressor, LinearRegression, Ridge, SGDRegressor +from sklearn.linear_model._huber import _huber_loss_and_gradient +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +def make_regression_with_outliers(n_samples=50, n_features=20): + rng = np.random.RandomState(0) + # Generate data with outliers by replacing 10% of the samples with noise. + X, y = make_regression( + n_samples=n_samples, n_features=n_features, random_state=0, noise=0.05 + ) + + # Replace 10% of the sample with noise. + num_noise = int(0.1 * n_samples) + random_samples = rng.randint(0, n_samples, num_noise) + X[random_samples, :] = 2.0 * rng.normal(0, 1, (num_noise, X.shape[1])) + return X, y + + +def test_huber_equals_lr_for_high_epsilon(): + # Test that Ridge matches LinearRegression for large epsilon + X, y = make_regression_with_outliers() + lr = LinearRegression() + lr.fit(X, y) + huber = HuberRegressor(epsilon=1e3, alpha=0.0) + huber.fit(X, y) + assert_almost_equal(huber.coef_, lr.coef_, 3) + assert_almost_equal(huber.intercept_, lr.intercept_, 2) + + +def test_huber_max_iter(): + X, y = make_regression_with_outliers() + huber = HuberRegressor(max_iter=1) + huber.fit(X, y) + assert huber.n_iter_ == huber.max_iter + + +def test_huber_gradient(): + # Test that the gradient calculated by _huber_loss_and_gradient is correct + rng = np.random.RandomState(1) + X, y = make_regression_with_outliers() + sample_weight = rng.randint(1, 3, (y.shape[0])) + + def loss_func(x, *args): + return _huber_loss_and_gradient(x, *args)[0] + + def grad_func(x, *args): + return _huber_loss_and_gradient(x, *args)[1] + + # Check using optimize.check_grad that the gradients are equal. + for _ in range(5): + # Check for both fit_intercept and otherwise. + for n_features in [X.shape[1] + 1, X.shape[1] + 2]: + w = rng.randn(n_features) + w[-1] = np.abs(w[-1]) + grad_same = optimize.check_grad( + loss_func, grad_func, w, X, y, 0.01, 0.1, sample_weight + ) + assert_almost_equal(grad_same, 1e-6, 4) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_huber_sample_weights(csr_container): + # Test sample_weights implementation in HuberRegressor""" + + X, y = make_regression_with_outliers() + huber = HuberRegressor() + huber.fit(X, y) + huber_coef = huber.coef_ + huber_intercept = huber.intercept_ + + # Rescale coefs before comparing with assert_array_almost_equal to make + # sure that the number of decimal places used is somewhat insensitive to + # the amplitude of the coefficients and therefore to the scale of the + # data and the regularization parameter + scale = max(np.mean(np.abs(huber.coef_)), np.mean(np.abs(huber.intercept_))) + + huber.fit(X, y, sample_weight=np.ones(y.shape[0])) + assert_array_almost_equal(huber.coef_ / scale, huber_coef / scale) + assert_array_almost_equal(huber.intercept_ / scale, huber_intercept / scale) + + X, y = make_regression_with_outliers(n_samples=5, n_features=20) + X_new = np.vstack((X, np.vstack((X[1], X[1], X[3])))) + y_new = np.concatenate((y, [y[1]], [y[1]], [y[3]])) + huber.fit(X_new, y_new) + huber_coef = huber.coef_ + huber_intercept = huber.intercept_ + sample_weight = np.ones(X.shape[0]) + sample_weight[1] = 3 + sample_weight[3] = 2 + huber.fit(X, y, sample_weight=sample_weight) + + assert_array_almost_equal(huber.coef_ / scale, huber_coef / scale) + assert_array_almost_equal(huber.intercept_ / scale, huber_intercept / scale) + + # Test sparse implementation with sample weights. + X_csr = csr_container(X) + huber_sparse = HuberRegressor() + huber_sparse.fit(X_csr, y, sample_weight=sample_weight) + assert_array_almost_equal(huber_sparse.coef_ / scale, huber_coef / scale) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_huber_sparse(csr_container): + X, y = make_regression_with_outliers() + huber = HuberRegressor(alpha=0.1) + huber.fit(X, y) + + X_csr = csr_container(X) + huber_sparse = HuberRegressor(alpha=0.1) + huber_sparse.fit(X_csr, y) + assert_array_almost_equal(huber_sparse.coef_, huber.coef_) + assert_array_equal(huber.outliers_, huber_sparse.outliers_) + + +def test_huber_scaling_invariant(): + # Test that outliers filtering is scaling independent. + X, y = make_regression_with_outliers() + huber = HuberRegressor(fit_intercept=False, alpha=0.0) + huber.fit(X, y) + n_outliers_mask_1 = huber.outliers_ + assert not np.all(n_outliers_mask_1) + + huber.fit(X, 2.0 * y) + n_outliers_mask_2 = huber.outliers_ + assert_array_equal(n_outliers_mask_2, n_outliers_mask_1) + + huber.fit(2.0 * X, 2.0 * y) + n_outliers_mask_3 = huber.outliers_ + assert_array_equal(n_outliers_mask_3, n_outliers_mask_1) + + +def test_huber_and_sgd_same_results(): + # Test they should converge to same coefficients for same parameters + + X, y = make_regression_with_outliers(n_samples=10, n_features=2) + + # Fit once to find out the scale parameter. Scale down X and y by scale + # so that the scale parameter is optimized to 1.0 + huber = HuberRegressor(fit_intercept=False, alpha=0.0, epsilon=1.35) + huber.fit(X, y) + X_scale = X / huber.scale_ + y_scale = y / huber.scale_ + huber.fit(X_scale, y_scale) + assert_almost_equal(huber.scale_, 1.0, 3) + + sgdreg = SGDRegressor( + alpha=0.0, + loss="huber", + shuffle=True, + random_state=0, + max_iter=10000, + fit_intercept=False, + epsilon=1.35, + tol=None, + ) + sgdreg.fit(X_scale, y_scale) + assert_array_almost_equal(huber.coef_, sgdreg.coef_, 1) + + +def test_huber_warm_start(): + X, y = make_regression_with_outliers() + huber_warm = HuberRegressor(alpha=1.0, max_iter=10000, warm_start=True, tol=1e-1) + + huber_warm.fit(X, y) + huber_warm_coef = huber_warm.coef_.copy() + huber_warm.fit(X, y) + + # SciPy performs the tol check after doing the coef updates, so + # these would be almost same but not equal. + assert_array_almost_equal(huber_warm.coef_, huber_warm_coef, 1) + + assert huber_warm.n_iter_ == 0 + + +def test_huber_better_r2_score(): + # Test that huber returns a better r2 score than non-outliers""" + X, y = make_regression_with_outliers() + huber = HuberRegressor(alpha=0.01) + huber.fit(X, y) + linear_loss = np.dot(X, huber.coef_) + huber.intercept_ - y + mask = np.abs(linear_loss) < huber.epsilon * huber.scale_ + huber_score = huber.score(X[mask], y[mask]) + huber_outlier_score = huber.score(X[~mask], y[~mask]) + + # The Ridge regressor should be influenced by the outliers and hence + # give a worse score on the non-outliers as compared to the huber + # regressor. + ridge = Ridge(alpha=0.01) + ridge.fit(X, y) + ridge_score = ridge.score(X[mask], y[mask]) + ridge_outlier_score = ridge.score(X[~mask], y[~mask]) + assert huber_score > ridge_score + + # The huber model should also fit poorly on the outliers. + assert ridge_outlier_score > huber_outlier_score + + +def test_huber_bool(): + # Test that it does not crash with bool data + X, y = make_regression(n_samples=200, n_features=2, noise=4.0, random_state=0) + X_bool = X > 0 + HuberRegressor().fit(X_bool, y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_least_angle.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_least_angle.py new file mode 100644 index 0000000000000000000000000000000000000000..9b4a39750e03a495afd512a219b036433e31070c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_least_angle.py @@ -0,0 +1,869 @@ +import warnings + +import numpy as np +import pytest +from scipy import linalg + +from sklearn import datasets, linear_model +from sklearn.base import clone +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ( + Lars, + LarsCV, + LassoLars, + LassoLarsCV, + LassoLarsIC, + lars_path, +) +from sklearn.linear_model._least_angle import _lars_path_residues +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils._testing import ( + TempMemmap, + assert_allclose, + assert_array_almost_equal, + ignore_warnings, +) + +# TODO: use another dataset that has multiple drops +diabetes = datasets.load_diabetes() +X, y = diabetes.data, diabetes.target +G = np.dot(X.T, X) +Xy = np.dot(X.T, y) +n_samples = y.size + + +def test_simple(): + # Principle of Lars is to keep covariances tied and decreasing + + # also test verbose output + import sys + from io import StringIO + + old_stdout = sys.stdout + try: + sys.stdout = StringIO() + + _, _, coef_path_ = linear_model.lars_path(X, y, method="lar", verbose=10) + + sys.stdout = old_stdout + + for i, coef_ in enumerate(coef_path_.T): + res = y - np.dot(X, coef_) + cov = np.dot(X.T, res) + C = np.max(abs(cov)) + eps = 1e-3 + ocur = len(cov[C - eps < abs(cov)]) + if i < X.shape[1]: + assert ocur == i + 1 + else: + # no more than max_pred variables can go into the active set + assert ocur == X.shape[1] + finally: + sys.stdout = old_stdout + + +def test_simple_precomputed(): + # The same, with precomputed Gram matrix + + _, _, coef_path_ = linear_model.lars_path(X, y, Gram=G, method="lar") + + for i, coef_ in enumerate(coef_path_.T): + res = y - np.dot(X, coef_) + cov = np.dot(X.T, res) + C = np.max(abs(cov)) + eps = 1e-3 + ocur = len(cov[C - eps < abs(cov)]) + if i < X.shape[1]: + assert ocur == i + 1 + else: + # no more than max_pred variables can go into the active set + assert ocur == X.shape[1] + + +def _assert_same_lars_path_result(output1, output2): + assert len(output1) == len(output2) + for o1, o2 in zip(output1, output2): + assert_allclose(o1, o2) + + +@pytest.mark.parametrize("method", ["lar", "lasso"]) +@pytest.mark.parametrize("return_path", [True, False]) +def test_lars_path_gram_equivalent(method, return_path): + _assert_same_lars_path_result( + linear_model.lars_path_gram( + Xy=Xy, Gram=G, n_samples=n_samples, method=method, return_path=return_path + ), + linear_model.lars_path(X, y, Gram=G, method=method, return_path=return_path), + ) + + +def test_x_none_gram_none_raises_value_error(): + # Test that lars_path with no X and Gram raises exception + Xy = np.dot(X.T, y) + with pytest.raises(ValueError, match="X and Gram cannot both be unspecified"): + linear_model.lars_path(None, y, Gram=None, Xy=Xy) + + +def test_all_precomputed(): + # Test that lars_path with precomputed Gram and Xy gives the right answer + G = np.dot(X.T, X) + Xy = np.dot(X.T, y) + for method in "lar", "lasso": + output = linear_model.lars_path(X, y, method=method) + output_pre = linear_model.lars_path(X, y, Gram=G, Xy=Xy, method=method) + for expected, got in zip(output, output_pre): + assert_array_almost_equal(expected, got) + + +# TODO: remove warning filter when numpy min version >= 2.0.0 +@pytest.mark.filterwarnings("ignore: `rcond` parameter will change") +def test_lars_lstsq(): + # Test that Lars gives least square solution at the end + # of the path + X1 = 3 * X # use un-normalized dataset + clf = linear_model.LassoLars(alpha=0.0) + clf.fit(X1, y) + coef_lstsq = np.linalg.lstsq(X1, y)[0] + assert_array_almost_equal(clf.coef_, coef_lstsq) + + +# TODO: remove warning filter when numpy min version >= 2.0.0 +@pytest.mark.filterwarnings("ignore: `rcond` parameter will change") +def test_lasso_gives_lstsq_solution(): + # Test that Lars Lasso gives least square solution at the end + # of the path + _, _, coef_path_ = linear_model.lars_path(X, y, method="lasso") + coef_lstsq = np.linalg.lstsq(X, y)[0] + assert_array_almost_equal(coef_lstsq, coef_path_[:, -1]) + + +def test_collinearity(): + # Check that lars_path is robust to collinearity in input + X = np.array([[3.0, 3.0, 1.0], [2.0, 2.0, 0.0], [1.0, 1.0, 0]]) + y = np.array([1.0, 0.0, 0]) + rng = np.random.RandomState(0) + + f = ignore_warnings + _, _, coef_path_ = f(linear_model.lars_path)(X, y, alpha_min=0.01) + assert not np.isnan(coef_path_).any() + residual = np.dot(X, coef_path_[:, -1]) - y + assert (residual**2).sum() < 1.0 # just make sure it's bounded + + n_samples = 10 + X = rng.rand(n_samples, 5) + y = np.zeros(n_samples) + _, _, coef_path_ = linear_model.lars_path( + X, + y, + Gram="auto", + copy_X=False, + copy_Gram=False, + alpha_min=0.0, + method="lasso", + verbose=0, + max_iter=500, + ) + assert_array_almost_equal(coef_path_, np.zeros_like(coef_path_)) + + +def test_no_path(): + # Test that the ``return_path=False`` option returns the correct output + alphas_, _, coef_path_ = linear_model.lars_path(X, y, method="lar") + alpha_, _, coef = linear_model.lars_path(X, y, method="lar", return_path=False) + + assert_array_almost_equal(coef, coef_path_[:, -1]) + assert alpha_ == alphas_[-1] + + +def test_no_path_precomputed(): + # Test that the ``return_path=False`` option with Gram remains correct + alphas_, _, coef_path_ = linear_model.lars_path(X, y, method="lar", Gram=G) + alpha_, _, coef = linear_model.lars_path( + X, y, method="lar", Gram=G, return_path=False + ) + + assert_array_almost_equal(coef, coef_path_[:, -1]) + assert alpha_ == alphas_[-1] + + +def test_no_path_all_precomputed(): + # Test that the ``return_path=False`` option with Gram and Xy remains + # correct + X, y = 3 * diabetes.data, diabetes.target + G = np.dot(X.T, X) + Xy = np.dot(X.T, y) + alphas_, _, coef_path_ = linear_model.lars_path( + X, y, method="lasso", Xy=Xy, Gram=G, alpha_min=0.9 + ) + alpha_, _, coef = linear_model.lars_path( + X, y, method="lasso", Gram=G, Xy=Xy, alpha_min=0.9, return_path=False + ) + + assert_array_almost_equal(coef, coef_path_[:, -1]) + assert alpha_ == alphas_[-1] + + +@pytest.mark.parametrize( + "classifier", [linear_model.Lars, linear_model.LarsCV, linear_model.LassoLarsIC] +) +def test_lars_precompute(classifier): + # Check for different values of precompute + G = np.dot(X.T, X) + + clf = classifier(precompute=G) + output_1 = ignore_warnings(clf.fit)(X, y).coef_ + for precompute in [True, False, "auto", None]: + clf = classifier(precompute=precompute) + output_2 = clf.fit(X, y).coef_ + assert_array_almost_equal(output_1, output_2, decimal=8) + + +def test_singular_matrix(): + # Test when input is a singular matrix + X1 = np.array([[1, 1.0], [1.0, 1.0]]) + y1 = np.array([1, 1]) + _, _, coef_path = linear_model.lars_path(X1, y1) + assert_array_almost_equal(coef_path.T, [[0, 0], [1, 0]]) + + +def test_rank_deficient_design(): + # consistency test that checks that LARS Lasso is handling rank + # deficient input data (with n_features < rank) in the same way + # as coordinate descent Lasso + y = [5, 0, 5] + for X in ([[5, 0], [0, 5], [10, 10]], [[10, 10, 0], [1e-32, 0, 0], [0, 0, 1]]): + # To be able to use the coefs to compute the objective function, + # we need to turn off normalization + lars = linear_model.LassoLars(0.1) + coef_lars_ = lars.fit(X, y).coef_ + obj_lars = 1.0 / (2.0 * 3.0) * linalg.norm( + y - np.dot(X, coef_lars_) + ) ** 2 + 0.1 * linalg.norm(coef_lars_, 1) + coord_descent = linear_model.Lasso(0.1, tol=1e-6) + coef_cd_ = coord_descent.fit(X, y).coef_ + obj_cd = (1.0 / (2.0 * 3.0)) * linalg.norm( + y - np.dot(X, coef_cd_) + ) ** 2 + 0.1 * linalg.norm(coef_cd_, 1) + assert obj_lars < obj_cd * (1.0 + 1e-8) + + +def test_lasso_lars_vs_lasso_cd(): + # Test that LassoLars and Lasso using coordinate descent give the + # same results. + X = 3 * diabetes.data + + alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso") + lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8) + for c, a in zip(lasso_path.T, alphas): + if a == 0: + continue + lasso_cd.alpha = a + lasso_cd.fit(X, y) + error = linalg.norm(c - lasso_cd.coef_) + assert error < 0.01 + + # similar test, with the classifiers + for alpha in np.linspace(1e-2, 1 - 1e-2, 20): + clf1 = linear_model.LassoLars(alpha=alpha).fit(X, y) + clf2 = linear_model.Lasso(alpha=alpha, tol=1e-8).fit(X, y) + err = linalg.norm(clf1.coef_ - clf2.coef_) + assert err < 1e-3 + + # same test, with normalized data + X = diabetes.data + X = X - X.sum(axis=0) + X /= np.linalg.norm(X, axis=0) + alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso") + lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8) + for c, a in zip(lasso_path.T, alphas): + if a == 0: + continue + lasso_cd.alpha = a + lasso_cd.fit(X, y) + error = linalg.norm(c - lasso_cd.coef_) + assert error < 0.01 + + +def test_lasso_lars_vs_lasso_cd_early_stopping(): + # Test that LassoLars and Lasso using coordinate descent give the + # same results when early stopping is used. + # (test : before, in the middle, and in the last part of the path) + alphas_min = [10, 0.9, 1e-4] + + X = diabetes.data + + for alpha_min in alphas_min: + alphas, _, lasso_path = linear_model.lars_path( + X, y, method="lasso", alpha_min=alpha_min + ) + lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8) + lasso_cd.alpha = alphas[-1] + lasso_cd.fit(X, y) + error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) + assert error < 0.01 + + # same test, with normalization + X = diabetes.data - diabetes.data.sum(axis=0) + X /= np.linalg.norm(X, axis=0) + + for alpha_min in alphas_min: + alphas, _, lasso_path = linear_model.lars_path( + X, y, method="lasso", alpha_min=alpha_min + ) + lasso_cd = linear_model.Lasso(tol=1e-8) + lasso_cd.alpha = alphas[-1] + lasso_cd.fit(X, y) + error = linalg.norm(lasso_path[:, -1] - lasso_cd.coef_) + assert error < 0.01 + + +def test_lasso_lars_path_length(): + # Test that the path length of the LassoLars is right + lasso = linear_model.LassoLars() + lasso.fit(X, y) + lasso2 = linear_model.LassoLars(alpha=lasso.alphas_[2]) + lasso2.fit(X, y) + assert_array_almost_equal(lasso.alphas_[:3], lasso2.alphas_) + # Also check that the sequence of alphas is always decreasing + assert np.all(np.diff(lasso.alphas_) < 0) + + +def test_lasso_lars_vs_lasso_cd_ill_conditioned(): + # Test lasso lars on a very ill-conditioned design, and check that + # it does not blow up, and stays somewhat close to a solution given + # by the coordinate descent solver + # Also test that lasso_path (using lars_path output style) gives + # the same result as lars_path and previous lasso output style + # under these conditions. + rng = np.random.RandomState(42) + + # Generate data + n, m = 70, 100 + k = 5 + X = rng.randn(n, m) + w = np.zeros((m, 1)) + i = np.arange(0, m) + rng.shuffle(i) + supp = i[:k] + w[supp] = np.sign(rng.randn(k, 1)) * (rng.rand(k, 1) + 1) + y = np.dot(X, w) + sigma = 0.2 + y += sigma * rng.rand(*y.shape) + y = y.squeeze() + lars_alphas, _, lars_coef = linear_model.lars_path(X, y, method="lasso") + + _, lasso_coef2, _ = linear_model.lasso_path(X, y, alphas=lars_alphas, tol=1e-6) + + assert_array_almost_equal(lars_coef, lasso_coef2, decimal=1) + + +def test_lasso_lars_vs_lasso_cd_ill_conditioned2(): + # Create an ill-conditioned situation in which the LARS has to go + # far in the path to converge, and check that LARS and coordinate + # descent give the same answers + # Note it used to be the case that Lars had to use the drop for good + # strategy for this but this is no longer the case with the + # equality_tolerance checks + X = [[1e20, 1e20, 0], [-1e-32, 0, 0], [1, 1, 1]] + y = [10, 10, 1] + alpha = 0.0001 + + def objective_function(coef): + return 1.0 / (2.0 * len(X)) * linalg.norm( + y - np.dot(X, coef) + ) ** 2 + alpha * linalg.norm(coef, 1) + + lars = linear_model.LassoLars(alpha=alpha) + warning_message = "Regressors in active set degenerate." + with pytest.warns(ConvergenceWarning, match=warning_message): + lars.fit(X, y) + lars_coef_ = lars.coef_ + lars_obj = objective_function(lars_coef_) + + coord_descent = linear_model.Lasso(alpha=alpha, tol=1e-4) + cd_coef_ = coord_descent.fit(X, y).coef_ + cd_obj = objective_function(cd_coef_) + + assert lars_obj < cd_obj * (1.0 + 1e-8) + + +def test_lars_add_features(): + # assure that at least some features get added if necessary + # test for 6d2b4c + # Hilbert matrix + n = 5 + H = 1.0 / (np.arange(1, n + 1) + np.arange(n)[:, np.newaxis]) + clf = linear_model.Lars(fit_intercept=False).fit(H, np.arange(n)) + assert np.all(np.isfinite(clf.coef_)) + + +def test_lars_n_nonzero_coefs(verbose=False): + lars = linear_model.Lars(n_nonzero_coefs=6, verbose=verbose) + lars.fit(X, y) + assert len(lars.coef_.nonzero()[0]) == 6 + # The path should be of length 6 + 1 in a Lars going down to 6 + # non-zero coefs + assert len(lars.alphas_) == 7 + + +def test_multitarget(): + # Assure that estimators receiving multidimensional y do the right thing + Y = np.vstack([y, y**2]).T + n_targets = Y.shape[1] + estimators = [ + linear_model.LassoLars(), + linear_model.Lars(), + # regression test for gh-1615 + linear_model.LassoLars(fit_intercept=False), + linear_model.Lars(fit_intercept=False), + ] + + for estimator in estimators: + estimator.fit(X, Y) + Y_pred = estimator.predict(X) + alphas, active, coef, path = ( + estimator.alphas_, + estimator.active_, + estimator.coef_, + estimator.coef_path_, + ) + for k in range(n_targets): + estimator.fit(X, Y[:, k]) + y_pred = estimator.predict(X) + assert_array_almost_equal(alphas[k], estimator.alphas_) + assert_array_almost_equal(active[k], estimator.active_) + assert_array_almost_equal(coef[k], estimator.coef_) + assert_array_almost_equal(path[k], estimator.coef_path_) + assert_array_almost_equal(Y_pred[:, k], y_pred) + + +def test_lars_cv(): + # Test the LassoLarsCV object by checking that the optimal alpha + # increases as the number of samples increases. + # This property is not actually guaranteed in general and is just a + # property of the given dataset, with the given steps chosen. + old_alpha = 0 + lars_cv = linear_model.LassoLarsCV() + for length in (400, 200, 100): + X = diabetes.data[:length] + y = diabetes.target[:length] + lars_cv.fit(X, y) + np.testing.assert_array_less(old_alpha, lars_cv.alpha_) + old_alpha = lars_cv.alpha_ + assert not hasattr(lars_cv, "n_nonzero_coefs") + + +def test_lars_cv_max_iter(recwarn): + warnings.simplefilter("always") + with np.errstate(divide="raise", invalid="raise"): + X = diabetes.data + y = diabetes.target + rng = np.random.RandomState(42) + x = rng.randn(len(y)) + X = diabetes.data + X = np.c_[X, x, x] # add correlated features + X = StandardScaler().fit_transform(X) + lars_cv = linear_model.LassoLarsCV(max_iter=5, cv=5) + lars_cv.fit(X, y) + + # Check that there is no warning in general and no ConvergenceWarning + # in particular. + # Materialize the string representation of the warning to get a more + # informative error message in case of AssertionError. + recorded_warnings = [str(w) for w in recwarn] + assert len(recorded_warnings) == 0 + + +def test_lasso_lars_ic(): + # Test the LassoLarsIC object by checking that + # - some good features are selected. + # - alpha_bic > alpha_aic + # - n_nonzero_bic < n_nonzero_aic + lars_bic = linear_model.LassoLarsIC("bic") + lars_aic = linear_model.LassoLarsIC("aic") + rng = np.random.RandomState(42) + X = diabetes.data + X = np.c_[X, rng.randn(X.shape[0], 5)] # add 5 bad features + X = StandardScaler().fit_transform(X) + lars_bic.fit(X, y) + lars_aic.fit(X, y) + nonzero_bic = np.where(lars_bic.coef_)[0] + nonzero_aic = np.where(lars_aic.coef_)[0] + assert lars_bic.alpha_ > lars_aic.alpha_ + assert len(nonzero_bic) < len(nonzero_aic) + assert np.max(nonzero_bic) < diabetes.data.shape[1] + + +def test_lars_path_readonly_data(): + # When using automated memory mapping on large input, the + # fold data is in read-only mode + # This is a non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/4597 + splitted_data = train_test_split(X, y, random_state=42) + with TempMemmap(splitted_data) as (X_train, X_test, y_train, y_test): + # The following should not fail despite copy=False + _lars_path_residues(X_train, y_train, X_test, y_test, copy=False) + + +def test_lars_path_positive_constraint(): + # this is the main test for the positive parameter on the lars_path method + # the estimator classes just make use of this function + + # we do the test on the diabetes dataset + + # ensure that we get negative coefficients when positive=False + # and all positive when positive=True + # for method 'lar' (default) and lasso + + err_msg = "Positive constraint not supported for 'lar' coding method." + with pytest.raises(ValueError, match=err_msg): + linear_model.lars_path( + diabetes["data"], diabetes["target"], method="lar", positive=True + ) + + method = "lasso" + _, _, coefs = linear_model.lars_path( + X, y, return_path=True, method=method, positive=False + ) + assert coefs.min() < 0 + + _, _, coefs = linear_model.lars_path( + X, y, return_path=True, method=method, positive=True + ) + assert coefs.min() >= 0 + + +# now we gonna test the positive option for all estimator classes + +default_parameter = {"fit_intercept": False} + +estimator_parameter_map = { + "LassoLars": {"alpha": 0.1}, + "LassoLarsCV": {}, + "LassoLarsIC": {}, +} + + +def test_estimatorclasses_positive_constraint(): + # testing the transmissibility for the positive option of all estimator + # classes in this same function here + default_parameter = {"fit_intercept": False} + + estimator_parameter_map = { + "LassoLars": {"alpha": 0.1}, + "LassoLarsCV": {}, + "LassoLarsIC": {}, + } + for estname in estimator_parameter_map: + params = default_parameter.copy() + params.update(estimator_parameter_map[estname]) + estimator = getattr(linear_model, estname)(positive=False, **params) + estimator.fit(X, y) + assert estimator.coef_.min() < 0 + estimator = getattr(linear_model, estname)(positive=True, **params) + estimator.fit(X, y) + assert min(estimator.coef_) >= 0 + + +def test_lasso_lars_vs_lasso_cd_positive(): + # Test that LassoLars and Lasso using coordinate descent give the + # same results when using the positive option + + # This test is basically a copy of the above with additional positive + # option. However for the middle part, the comparison of coefficient values + # for a range of alphas, we had to make an adaptations. See below. + + # not normalized data + X = 3 * diabetes.data + + alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso", positive=True) + lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8, positive=True) + for c, a in zip(lasso_path.T, alphas): + if a == 0: + continue + lasso_cd.alpha = a + lasso_cd.fit(X, y) + error = linalg.norm(c - lasso_cd.coef_) + assert error < 0.01 + + # The range of alphas chosen for coefficient comparison here is restricted + # as compared with the above test without the positive option. This is due + # to the circumstance that the Lars-Lasso algorithm does not converge to + # the least-squares-solution for small alphas, see 'Least Angle Regression' + # by Efron et al 2004. The coefficients are typically in congruence up to + # the smallest alpha reached by the Lars-Lasso algorithm and start to + # diverge thereafter. See + # https://gist.github.com/michigraber/7e7d7c75eca694c7a6ff + + for alpha in np.linspace(6e-1, 1 - 1e-2, 20): + clf1 = linear_model.LassoLars( + fit_intercept=False, alpha=alpha, positive=True + ).fit(X, y) + clf2 = linear_model.Lasso( + fit_intercept=False, alpha=alpha, tol=1e-8, positive=True + ).fit(X, y) + err = linalg.norm(clf1.coef_ - clf2.coef_) + assert err < 1e-3 + + # normalized data + X = diabetes.data - diabetes.data.sum(axis=0) + X /= np.linalg.norm(X, axis=0) + alphas, _, lasso_path = linear_model.lars_path(X, y, method="lasso", positive=True) + lasso_cd = linear_model.Lasso(fit_intercept=False, tol=1e-8, positive=True) + for c, a in zip(lasso_path.T[:-1], alphas[:-1]): # don't include alpha=0 + lasso_cd.alpha = a + lasso_cd.fit(X, y) + error = linalg.norm(c - lasso_cd.coef_) + assert error < 0.01 + + +def test_lasso_lars_vs_R_implementation(): + # Test that sklearn LassoLars implementation agrees with the LassoLars + # implementation available in R (lars library) when fit_intercept=False. + + # Let's generate the data used in the bug report 7778 + y = np.array([-6.45006793, -3.51251449, -8.52445396, 6.12277822, -19.42109366]) + x = np.array( + [ + [0.47299829, 0, 0, 0, 0], + [0.08239882, 0.85784863, 0, 0, 0], + [0.30114139, -0.07501577, 0.80895216, 0, 0], + [-0.01460346, -0.1015233, 0.0407278, 0.80338378, 0], + [-0.69363927, 0.06754067, 0.18064514, -0.0803561, 0.40427291], + ] + ) + + X = x.T + + # The R result was obtained using the following code: + # + # library(lars) + # model_lasso_lars = lars(X, t(y), type="lasso", intercept=FALSE, + # trace=TRUE, normalize=FALSE) + # r = t(model_lasso_lars$beta) + # + + r = np.array( + [ + [ + 0, + 0, + 0, + 0, + 0, + -79.810362809499026, + -83.528788732782829, + -83.777653739190711, + -83.784156932888934, + -84.033390591756657, + ], + [0, 0, 0, 0, -0.476624256777266, 0, 0, 0, 0, 0.025219751009936], + [ + 0, + -3.577397088285891, + -4.702795355871871, + -7.016748621359461, + -7.614898471899412, + -0.336938391359179, + 0, + 0, + 0.001213370600853, + 0.048162321585148, + ], + [ + 0, + 0, + 0, + 2.231558436628169, + 2.723267514525966, + 2.811549786389614, + 2.813766976061531, + 2.817462468949557, + 2.817368178703816, + 2.816221090636795, + ], + [ + 0, + 0, + -1.218422599914637, + -3.457726183014808, + -4.021304522060710, + -45.827461592423745, + -47.776608869312305, + -47.911561610746404, + -47.914845922736234, + -48.039562334265717, + ], + ] + ) + + model_lasso_lars = linear_model.LassoLars(alpha=0, fit_intercept=False) + model_lasso_lars.fit(X, y) + skl_betas = model_lasso_lars.coef_path_ + + assert_array_almost_equal(r, skl_betas, decimal=12) + + +@pytest.mark.parametrize("copy_X", [True, False]) +def test_lasso_lars_copyX_behaviour(copy_X): + """ + Test that user input regarding copy_X is not being overridden (it was until + at least version 0.21) + + """ + lasso_lars = LassoLarsIC(copy_X=copy_X, precompute=False) + rng = np.random.RandomState(0) + X = rng.normal(0, 1, (100, 5)) + X_copy = X.copy() + y = X[:, 2] + lasso_lars.fit(X, y) + assert copy_X == np.array_equal(X, X_copy) + + +@pytest.mark.parametrize("copy_X", [True, False]) +def test_lasso_lars_fit_copyX_behaviour(copy_X): + """ + Test that user input to .fit for copy_X overrides default __init__ value + + """ + lasso_lars = LassoLarsIC(precompute=False) + rng = np.random.RandomState(0) + X = rng.normal(0, 1, (100, 5)) + X_copy = X.copy() + y = X[:, 2] + lasso_lars.fit(X, y, copy_X=copy_X) + assert copy_X == np.array_equal(X, X_copy) + + +@pytest.mark.parametrize("est", (LassoLars(alpha=1e-3), Lars())) +def test_lars_with_jitter(est): + # Test that a small amount of jitter helps stability, + # using example provided in issue #2746 + + X = np.array([[0.0, 0.0, 0.0, -1.0, 0.0], [0.0, -1.0, 0.0, 0.0, 0.0]]) + y = [-2.5, -2.5] + expected_coef = [0, 2.5, 0, 2.5, 0] + + # set to fit_intercept to False since target is constant and we want check + # the value of coef. coef would be all zeros otherwise. + est.set_params(fit_intercept=False) + est_jitter = clone(est).set_params(jitter=10e-8, random_state=0) + + est.fit(X, y) + est_jitter.fit(X, y) + + assert np.mean((est.coef_ - est_jitter.coef_) ** 2) > 0.1 + np.testing.assert_allclose(est_jitter.coef_, expected_coef, rtol=1e-3) + + +def test_X_none_gram_not_none(): + with pytest.raises(ValueError, match="X cannot be None if Gram is not None"): + lars_path(X=None, y=np.array([1]), Gram=True) + + +def test_copy_X_with_auto_gram(): + # Non-regression test for #17789, `copy_X=True` and Gram='auto' does not + # overwrite X + rng = np.random.RandomState(42) + X = rng.rand(6, 6) + y = rng.rand(6) + + X_before = X.copy() + linear_model.lars_path(X, y, Gram="auto", copy_X=True, method="lasso") + # X did not change + assert_allclose(X, X_before) + + +@pytest.mark.parametrize( + "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}), + ), +) +@pytest.mark.parametrize("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(20, 6).astype(dtype) + y = rng.rand(20).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 + + +@pytest.mark.parametrize( + "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(10, 6) + y_64 = rng.rand(10) + + 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) + + +@pytest.mark.parametrize("criterion", ["aic", "bic"]) +def test_lassolarsic_alpha_selection(criterion): + """Check that we properly compute the AIC and BIC score. + + In this test, we reproduce the example of the Fig. 2 of Zou et al. + (reference [1] in LassoLarsIC) In this example, only 7 features should be + selected. + """ + model = make_pipeline(StandardScaler(), LassoLarsIC(criterion=criterion)) + model.fit(X, y) + + best_alpha_selected = np.argmin(model[-1].criterion_) + assert best_alpha_selected == 7 + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_lassolarsic_noise_variance(fit_intercept): + """Check the behaviour when `n_samples` < `n_features` and that one needs + to provide the noise variance.""" + rng = np.random.RandomState(0) + X, y = datasets.make_regression( + n_samples=10, n_features=11 - fit_intercept, random_state=rng + ) + + model = make_pipeline(StandardScaler(), LassoLarsIC(fit_intercept=fit_intercept)) + + err_msg = ( + "You are using LassoLarsIC in the case where the number of samples is smaller" + " than the number of features" + ) + with pytest.raises(ValueError, match=err_msg): + model.fit(X, y) + + model.set_params(lassolarsic__noise_variance=1.0) + model.fit(X, y).predict(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_linear_loss.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_linear_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..a273656b3dbb8508bb468d6f5ac906b16dbc03f5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_linear_loss.py @@ -0,0 +1,510 @@ +""" +Tests for LinearModelLoss + +Note that correctness of losses (which compose LinearModelLoss) is already well +covered in the _loss module. +""" + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy import linalg, optimize + +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 +from sklearn.utils.fixes import CSR_CONTAINERS + +# 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, + ) + coef = linear_model_loss.init_zero_coef(X) + + if linear_model_loss.base_loss.is_multiclass: + n_classes = linear_model_loss.base_loss.n_classes + 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.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 + + +@pytest.mark.parametrize("base_loss", LOSSES) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("n_features", [0, 1, 10]) +@pytest.mark.parametrize("dtype", [None, np.float32, np.float64, np.int64]) +def test_init_zero_coef( + base_loss, fit_intercept, n_features, dtype, global_random_seed +): + """Test that init_zero_coef initializes coef correctly.""" + loss = LinearModelLoss(base_loss=base_loss(), fit_intercept=fit_intercept) + rng = np.random.RandomState(global_random_seed) + X = rng.normal(size=(5, n_features)) + coef = loss.init_zero_coef(X, dtype=dtype) + if loss.base_loss.is_multiclass: + n_classes = loss.base_loss.n_classes + assert coef.shape == (n_classes, n_features + fit_intercept) + assert coef.flags["F_CONTIGUOUS"] + else: + assert coef.shape == (n_features + fit_intercept,) + + if dtype is None: + assert coef.dtype == X.dtype + else: + assert coef.dtype == dtype + + assert np.count_nonzero(coef) == 0 + + +@pytest.mark.parametrize("base_loss", LOSSES) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("sample_weight", [None, "range"]) +@pytest.mark.parametrize("l2_reg_strength", [0, 1]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_loss_grad_hess_are_the_same( + base_loss, + fit_intercept, + sample_weight, + l2_reg_strength, + csr_container, + global_random_seed, +): + """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=global_random_seed + ) + X_old, y_old, coef_old = X.copy(), y.copy(), coef.copy() + + 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 + ) + g4, h4, _ = loss.gradient_hessian( + 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) + assert_allclose(g1, g4) + # The ravelling only takes effect for multiclass. + assert_allclose(h4 @ g4.ravel(order="F"), h3(g3).ravel(order="F")) + # Test that gradient_out and hessian_out are considered properly. + g_out = np.empty_like(coef) + h_out = np.empty_like(coef, shape=(coef.size, coef.size)) + g5, h5, _ = loss.gradient_hessian( + coef, + X, + y, + sample_weight=sample_weight, + l2_reg_strength=l2_reg_strength, + gradient_out=g_out, + hessian_out=h_out, + ) + assert np.shares_memory(g5, g_out) + assert np.shares_memory(h5, h_out) + assert_allclose(g5, g_out) + assert_allclose(h5, h_out) + assert_allclose(g1, g5) + assert_allclose(h5, h4) + + # same for sparse X + Xs = csr_container(X) + l1_sp = loss.loss( + coef, Xs, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g1_sp = loss.gradient( + coef, Xs, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + l2_sp, g2_sp = loss.loss_gradient( + coef, Xs, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g3_sp, h3_sp = loss.gradient_hessian_product( + coef, Xs, y, sample_weight=sample_weight, l2_reg_strength=l2_reg_strength + ) + g4_sp, h4_sp, _ = loss.gradient_hessian( + coef, Xs, 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)) + assert_allclose(g1, g4_sp) + assert_allclose(h4, h4_sp) + + # X, y and coef should not have changed + assert_allclose(X, X_old) + assert_allclose(Xs.toarray(), X_old) + assert_allclose(y, y_old) + assert_allclose(coef, coef_old) + + +@pytest.mark.parametrize("base_loss", LOSSES) +@pytest.mark.parametrize("sample_weight", [None, "range"]) +@pytest.mark.parametrize("l2_reg_strength", [0, 1]) +@pytest.mark.parametrize("X_container", CSR_CONTAINERS + [None]) +def test_loss_gradients_hessp_intercept( + base_loss, sample_weight, l2_reg_strength, X_container, global_random_seed +): + """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=global_random_seed, + ) + + 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_container is not None: + X = X_container(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(global_random_seed).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) + + +@pytest.mark.parametrize("base_loss", LOSSES) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("sample_weight", [None, "range"]) +@pytest.mark.parametrize("l2_reg_strength", [0, 1]) +def test_gradients_hessians_numerically( + base_loss, fit_intercept, sample_weight, l2_reg_strength, global_random_seed +): + """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=global_random_seed, + ) + 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) + + +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_multinomial_coef_shape(fit_intercept, global_random_seed): + """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=global_random_seed, + ) + s = np.random.RandomState(global_random_seed).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) + g3, hess, _ = loss.gradient_hessian(coef, X, y) + assert g3.shape == coef.shape + # But full hessian is always 2d. + assert hess.shape == (coef.size, coef.size) + + 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")) + + +@pytest.mark.parametrize("sample_weight", [None, "range"]) +def test_multinomial_hessian_3_classes(sample_weight, global_random_seed): + """Test multinomial hessian for 3 classes and 2 points. + + For n_classes = 3 and n_samples = 2, we have + p0 = [p0_0, p0_1] + p1 = [p1_0, p1_1] + p2 = [p2_0, p2_1] + and with 2 x 2 diagonal subblocks + H = [p0 * (1-p0), -p0 * p1, -p0 * p2] + [ -p0 * p1, p1 * (1-p1), -p1 * p2] + [ -p0 * p2, -p1 * p2, p2 * (1-p2)] + hess = X' H X + """ + n_samples, n_features, n_classes = 2, 5, 3 + loss = LinearModelLoss( + base_loss=HalfMultinomialLoss(n_classes=n_classes), fit_intercept=False + ) + X, y, coef = random_X_y_coef( + linear_model_loss=loss, + n_samples=n_samples, + n_features=n_features, + seed=global_random_seed, + ) + 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]) + + grad, hess, _ = loss.gradient_hessian( + coef, + X, + y, + sample_weight=sample_weight, + l2_reg_strength=0, + ) + # Hessian must be a symmetrix matrix. + assert_allclose(hess, hess.T) + + weights, intercept, raw_prediction = loss.weight_intercept_raw(coef, X) + grad_pointwise, proba = loss.base_loss.gradient_proba( + y_true=y, + raw_prediction=raw_prediction, + sample_weight=sample_weight, + ) + p0d, p1d, p2d, oned = ( + np.diag(proba[:, 0]), + np.diag(proba[:, 1]), + np.diag(proba[:, 2]), + np.diag(np.ones(2)), + ) + h = np.block( + [ + [p0d * (oned - p0d), -p0d * p1d, -p0d * p2d], + [-p0d * p1d, p1d * (oned - p1d), -p1d * p2d], + [-p0d * p2d, -p1d * p2d, p2d * (oned - p2d)], + ] + ) + h = h.reshape((n_classes, n_samples, n_classes, n_samples)) + if sample_weight is None: + h /= n_samples + else: + h *= sample_weight / np.sum(sample_weight) + # hess_expected.shape = (n_features, n_classes, n_classes, n_features) + hess_expected = np.einsum("ij, mini, ik->jmnk", X, h, X) + hess_expected = np.moveaxis(hess_expected, 2, 3) + hess_expected = hess_expected.reshape( + n_classes * n_features, n_classes * n_features, order="C" + ) + assert_allclose(hess_expected, hess_expected.T) + assert_allclose(hess, hess_expected) + + +def test_linear_loss_gradient_hessian_raises_wrong_out_parameters(): + """Test that wrong gradient_out and hessian_out raises errors.""" + n_samples, n_features, n_classes = 5, 2, 3 + loss = LinearModelLoss(base_loss=HalfBinomialLoss(), fit_intercept=False) + X = np.ones((n_samples, n_features)) + y = np.ones(n_samples) + coef = loss.init_zero_coef(X) + gradient_out = np.zeros(1) + with pytest.raises( + ValueError, match="gradient_out is required to have shape coef.shape" + ): + loss.gradient_hessian( + coef=coef, + X=X, + y=y, + gradient_out=gradient_out, + hessian_out=None, + ) + hessian_out = np.zeros(1) + with pytest.raises(ValueError, match="hessian_out is required to have shape"): + loss.gradient_hessian( + coef=coef, + X=X, + y=y, + gradient_out=None, + hessian_out=hessian_out, + ) + + loss = LinearModelLoss(base_loss=HalfMultinomialLoss(), fit_intercept=False) + coef = loss.init_zero_coef(X) + gradient_out = np.zeros((2 * n_classes, n_features))[::2] + with pytest.raises(ValueError, match="gradient_out must be F-contiguous"): + loss.gradient_hessian( + coef=coef, + X=X, + y=y, + gradient_out=gradient_out, + ) + hessian_out = np.zeros((2 * n_classes * n_features, n_classes * n_features))[::2] + with pytest.raises(ValueError, match="hessian_out must be contiguous"): + loss.gradient_hessian( + coef=coef, + X=X, + y=y, + gradient_out=None, + hessian_out=hessian_out, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_logistic.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_logistic.py new file mode 100644 index 0000000000000000000000000000000000000000..007c900dd36776ba4bd3d5731f5f40cf882028b3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_logistic.py @@ -0,0 +1,2471 @@ +import itertools +import os +import warnings +from functools import partial + +import numpy as np +import pytest +from numpy.testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from scipy import sparse +from scipy.linalg import LinAlgWarning, svd + +from sklearn import config_context +from sklearn._loss import HalfMultinomialLoss +from sklearn.base import clone +from sklearn.datasets import load_iris, make_classification, make_low_rank_matrix +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import SGDClassifier +from sklearn.linear_model._logistic import ( + LogisticRegression as LogisticRegressionDefault, +) +from sklearn.linear_model._logistic import ( + LogisticRegressionCV as LogisticRegressionCVDefault, +) +from sklearn.linear_model._logistic import ( + _log_reg_scoring_path, + _logistic_regression_path, +) +from sklearn.metrics import get_scorer, log_loss +from sklearn.model_selection import ( + GridSearchCV, + LeaveOneGroupOut, + StratifiedKFold, + cross_val_score, + train_test_split, +) +from sklearn.multiclass import OneVsRestClassifier +from sklearn.preprocessing import LabelEncoder, StandardScaler, scale +from sklearn.svm import l1_min_c +from sklearn.utils import compute_class_weight, shuffle +from sklearn.utils._testing import ignore_warnings, skip_if_no_parallel +from sklearn.utils.fixes import _IS_32BIT, COO_CONTAINERS, CSR_CONTAINERS + +pytestmark = pytest.mark.filterwarnings( + "error::sklearn.exceptions.ConvergenceWarning:sklearn.*" +) +# Fixing random_state helps prevent ConvergenceWarnings +LogisticRegression = partial(LogisticRegressionDefault, random_state=0) +LogisticRegressionCV = partial(LogisticRegressionCVDefault, random_state=0) + + +SOLVERS = ("lbfgs", "liblinear", "newton-cg", "newton-cholesky", "sag", "saga") +X = [[-1, 0], [0, 1], [1, 1]] +Y1 = [0, 1, 1] +Y2 = [2, 1, 0] +iris = load_iris() + + +def check_predictions(clf, X, y): + """Check that the model is able to fit the classification data""" + n_samples = len(y) + classes = np.unique(y) + n_classes = classes.shape[0] + + predicted = clf.fit(X, y).predict(X) + assert_array_equal(clf.classes_, classes) + + assert predicted.shape == (n_samples,) + assert_array_equal(predicted, y) + + probabilities = clf.predict_proba(X) + assert probabilities.shape == (n_samples, n_classes) + assert_array_almost_equal(probabilities.sum(axis=1), np.ones(n_samples)) + assert_array_equal(probabilities.argmax(axis=1), y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_predict_2_classes(csr_container): + # Simple sanity check on a 2 classes dataset + # Make sure it predicts the correct result on simple datasets. + check_predictions(LogisticRegression(random_state=0), X, Y1) + check_predictions(LogisticRegression(random_state=0), csr_container(X), Y1) + + check_predictions(LogisticRegression(C=100, random_state=0), X, Y1) + check_predictions(LogisticRegression(C=100, random_state=0), csr_container(X), Y1) + + check_predictions(LogisticRegression(fit_intercept=False, random_state=0), X, Y1) + check_predictions( + LogisticRegression(fit_intercept=False, random_state=0), csr_container(X), Y1 + ) + + +def test_logistic_cv_mock_scorer(): + class MockScorer: + def __init__(self): + self.calls = 0 + self.scores = [0.1, 0.4, 0.8, 0.5] + + def __call__(self, model, X, y, sample_weight=None): + score = self.scores[self.calls % len(self.scores)] + self.calls += 1 + return score + + mock_scorer = MockScorer() + Cs = [1, 2, 3, 4] + cv = 2 + + lr = LogisticRegressionCV(Cs=Cs, scoring=mock_scorer, cv=cv) + X, y = make_classification(random_state=0) + lr.fit(X, y) + + # Cs[2] has the highest score (0.8) from MockScorer + assert lr.C_[0] == Cs[2] + + # scorer called 8 times (cv*len(Cs)) + assert mock_scorer.calls == cv * len(Cs) + + # reset mock_scorer + mock_scorer.calls = 0 + custom_score = lr.score(X, lr.predict(X)) + + assert custom_score == mock_scorer.scores[0] + assert mock_scorer.calls == 1 + + +@skip_if_no_parallel +def test_lr_liblinear_warning(): + X, y = make_classification(random_state=0) + + lr = LogisticRegression(solver="liblinear", n_jobs=2) + warning_message = ( + "'n_jobs' > 1 does not have any effect when" + " 'solver' is set to 'liblinear'. Got 'n_jobs'" + " = 2." + ) + with pytest.warns(UserWarning, match=warning_message): + lr.fit(X, y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_predict_3_classes(csr_container): + check_predictions(LogisticRegression(C=10), X, Y2) + check_predictions(LogisticRegression(C=10), csr_container(X), Y2) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.filterwarnings( + "ignore:.*'liblinear' solver for multiclass classification is deprecated.*" +) +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(C=len(iris.data), solver="liblinear", multi_class="ovr"), + LogisticRegression(C=len(iris.data), solver="lbfgs"), + LogisticRegression(C=len(iris.data), solver="newton-cg"), + LogisticRegression( + C=len(iris.data), solver="sag", tol=1e-2, multi_class="ovr", random_state=42 + ), + LogisticRegression( + C=len(iris.data), + solver="saga", + tol=1e-2, + multi_class="ovr", + random_state=42, + ), + LogisticRegression(C=len(iris.data), solver="newton-cholesky"), + ], +) +def test_predict_iris(clf): + """Test logistic regression with the iris dataset. + + Test that both multinomial and OvR solvers handle multiclass data correctly and + give good accuracy score (>0.95) for the training data. + """ + n_samples, n_features = iris.data.shape + target = iris.target_names[iris.target] + + if clf.solver == "lbfgs": + # lbfgs has convergence issues on the iris data with its default max_iter=100 + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + clf.fit(iris.data, target) + else: + clf.fit(iris.data, target) + assert_array_equal(np.unique(target), clf.classes_) + + pred = clf.predict(iris.data) + assert np.mean(pred == target) > 0.95 + + probabilities = clf.predict_proba(iris.data) + assert_allclose(probabilities.sum(axis=1), np.ones(n_samples)) + + pred = iris.target_names[probabilities.argmax(axis=1)] + assert np.mean(pred == target) > 0.95 + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("LR", [LogisticRegression, LogisticRegressionCV]) +def test_check_solver_option(LR): + X, y = iris.data, iris.target + + # only 'liblinear' solver + for solver in ["liblinear"]: + msg = f"Solver {solver} does not support a multinomial backend." + lr = LR(solver=solver, multi_class="multinomial") + with pytest.raises(ValueError, match=msg): + lr.fit(X, y) + + # all solvers except 'liblinear' and 'saga' + for solver in ["lbfgs", "newton-cg", "newton-cholesky", "sag"]: + msg = "Solver %s supports only 'l2' or None penalties," % solver + lr = LR(solver=solver, penalty="l1", multi_class="ovr") + with pytest.raises(ValueError, match=msg): + lr.fit(X, y) + for solver in ["lbfgs", "newton-cg", "newton-cholesky", "sag", "saga"]: + msg = "Solver %s supports only dual=False, got dual=True" % solver + lr = LR(solver=solver, dual=True, multi_class="ovr") + with pytest.raises(ValueError, match=msg): + lr.fit(X, y) + + # only saga supports elasticnet. We only test for liblinear because the + # error is raised before for the other solvers (solver %s supports only l2 + # penalties) + for solver in ["liblinear"]: + msg = f"Only 'saga' solver supports elasticnet penalty, got solver={solver}." + lr = LR(solver=solver, penalty="elasticnet") + with pytest.raises(ValueError, match=msg): + lr.fit(X, y) + + # liblinear does not support penalty='none' + # (LogisticRegressionCV does not supports penalty='none' at all) + if LR is LogisticRegression: + msg = "penalty=None is not supported for the liblinear solver" + lr = LR(penalty=None, solver="liblinear") + with pytest.raises(ValueError, match=msg): + lr.fit(X, y) + + +@pytest.mark.parametrize("LR", [LogisticRegression, LogisticRegressionCV]) +def test_elasticnet_l1_ratio_err_helpful(LR): + # Check that an informative error message is raised when penalty="elasticnet" + # but l1_ratio is not specified. + model = LR(penalty="elasticnet", solver="saga") + with pytest.raises(ValueError, match=r".*l1_ratio.*"): + model.fit(np.array([[1, 2], [3, 4]]), np.array([0, 1])) + + +# TODO(1.8): remove whole test with deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("solver", ["lbfgs", "newton-cg", "sag", "saga"]) +def test_multinomial_binary(solver): + # Test multinomial LR on a binary problem. + target = (iris.target > 0).astype(np.intp) + target = np.array(["setosa", "not-setosa"])[target] + + clf = LogisticRegression( + solver=solver, multi_class="multinomial", random_state=42, max_iter=2000 + ) + clf.fit(iris.data, target) + + assert clf.coef_.shape == (1, iris.data.shape[1]) + assert clf.intercept_.shape == (1,) + assert_array_equal(clf.predict(iris.data), target) + + mlr = LogisticRegression( + solver=solver, multi_class="multinomial", random_state=42, fit_intercept=False + ) + mlr.fit(iris.data, target) + pred = clf.classes_[np.argmax(clf.predict_log_proba(iris.data), axis=1)] + assert np.mean(pred == target) > 0.9 + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +# Maybe even remove this whole test as correctness of multinomial loss is tested +# elsewhere. +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +def test_multinomial_binary_probabilities(global_random_seed): + # Test multinomial LR gives expected probabilities based on the + # decision function, for a binary problem. + X, y = make_classification(random_state=global_random_seed) + clf = LogisticRegression( + multi_class="multinomial", + solver="saga", + tol=1e-3, + random_state=global_random_seed, + ) + clf.fit(X, y) + + decision = clf.decision_function(X) + proba = clf.predict_proba(X) + + expected_proba_class_1 = np.exp(decision) / (np.exp(decision) + np.exp(-decision)) + expected_proba = np.c_[1 - expected_proba_class_1, expected_proba_class_1] + + assert_almost_equal(proba, expected_proba) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_sparsify(coo_container): + # Test sparsify and densify members. + n_samples, n_features = iris.data.shape + target = iris.target_names[iris.target] + X = scale(iris.data) + clf = LogisticRegression(random_state=0).fit(X, target) + + pred_d_d = clf.decision_function(X) + + clf.sparsify() + assert sparse.issparse(clf.coef_) + pred_s_d = clf.decision_function(X) + + sp_data = coo_container(X) + pred_s_s = clf.decision_function(sp_data) + + clf.densify() + pred_d_s = clf.decision_function(sp_data) + + assert_array_almost_equal(pred_d_d, pred_s_d) + assert_array_almost_equal(pred_d_d, pred_s_s) + assert_array_almost_equal(pred_d_d, pred_d_s) + + +def test_inconsistent_input(): + # Test that an exception is raised on inconsistent input + rng = np.random.RandomState(0) + X_ = rng.random_sample((5, 10)) + y_ = np.ones(X_.shape[0]) + y_[0] = 0 + + clf = LogisticRegression(random_state=0) + + # Wrong dimensions for training data + y_wrong = y_[:-1] + + with pytest.raises(ValueError): + clf.fit(X, y_wrong) + + # Wrong dimensions for test data + with pytest.raises(ValueError): + clf.fit(X_, y_).predict(rng.random_sample((3, 12))) + + +def test_write_parameters(): + # Test that we can write to coef_ and intercept_ + clf = LogisticRegression(random_state=0) + clf.fit(X, Y1) + clf.coef_[:] = 0 + clf.intercept_[:] = 0 + assert_array_almost_equal(clf.decision_function(X), 0) + + +def test_nan(): + # Test proper NaN handling. + # Regression test for Issue #252: fit used to go into an infinite loop. + Xnan = np.array(X, dtype=np.float64) + Xnan[0, 1] = np.nan + logistic = LogisticRegression(random_state=0) + + with pytest.raises(ValueError): + logistic.fit(Xnan, Y1) + + +def test_consistency_path(): + # Test that the path algorithm is consistent + rng = np.random.RandomState(0) + X = np.concatenate((rng.randn(100, 2) + [1, 1], rng.randn(100, 2))) + y = [1] * 100 + [-1] * 100 + Cs = np.logspace(0, 4, 10) + + f = ignore_warnings + # can't test with fit_intercept=True since LIBLINEAR + # penalizes the intercept + for solver in ["sag", "saga"]: + coefs, Cs, _ = f(_logistic_regression_path)( + X, + y, + Cs=Cs, + fit_intercept=False, + tol=1e-5, + solver=solver, + max_iter=1000, + random_state=0, + ) + for i, C in enumerate(Cs): + lr = LogisticRegression( + C=C, + fit_intercept=False, + tol=1e-5, + solver=solver, + random_state=0, + max_iter=1000, + ) + lr.fit(X, y) + lr_coef = lr.coef_.ravel() + assert_array_almost_equal( + lr_coef, coefs[i], decimal=4, err_msg="with solver = %s" % solver + ) + + # test for fit_intercept=True + for solver in ("lbfgs", "newton-cg", "newton-cholesky", "liblinear", "sag", "saga"): + Cs = [1e3] + coefs, Cs, _ = f(_logistic_regression_path)( + X, + y, + Cs=Cs, + tol=1e-6, + solver=solver, + intercept_scaling=10000.0, + random_state=0, + ) + lr = LogisticRegression( + C=Cs[0], + tol=1e-6, + intercept_scaling=10000.0, + random_state=0, + solver=solver, + ) + lr.fit(X, y) + lr_coef = np.concatenate([lr.coef_.ravel(), lr.intercept_]) + assert_array_almost_equal( + lr_coef, coefs[0], decimal=4, err_msg="with solver = %s" % solver + ) + + +def test_logistic_regression_path_convergence_fail(): + rng = np.random.RandomState(0) + X = np.concatenate((rng.randn(100, 2) + [1, 1], rng.randn(100, 2))) + y = [1] * 100 + [-1] * 100 + Cs = [1e3] + + # Check that the convergence message points to both a model agnostic + # advice (scaling the data) and to the logistic regression specific + # documentation that includes hints on the solver configuration. + with pytest.warns(ConvergenceWarning) as record: + _logistic_regression_path( + X, y, Cs=Cs, tol=0.0, max_iter=1, random_state=0, verbose=0 + ) + + assert len(record) == 1 + warn_msg = record[0].message.args[0] + assert "lbfgs failed to converge after 1 iteration(s)" in warn_msg + assert "Increase the number of iterations" in warn_msg + assert "scale the data" in warn_msg + assert "linear_model.html#logistic-regression" in warn_msg + + +def test_liblinear_dual_random_state(): + # random_state is relevant for liblinear solver only if dual=True + X, y = make_classification(n_samples=20, random_state=0) + lr1 = LogisticRegression( + random_state=0, + dual=True, + tol=1e-3, + solver="liblinear", + ) + lr1.fit(X, y) + lr2 = LogisticRegression( + random_state=0, + dual=True, + tol=1e-3, + solver="liblinear", + ) + lr2.fit(X, y) + lr3 = LogisticRegression( + random_state=8, + dual=True, + tol=1e-3, + solver="liblinear", + ) + lr3.fit(X, y) + + # same result for same random state + assert_array_almost_equal(lr1.coef_, lr2.coef_) + # different results for different random states + msg = "Arrays are not almost equal to 6 decimals" + with pytest.raises(AssertionError, match=msg): + assert_array_almost_equal(lr1.coef_, lr3.coef_) + + +def test_logistic_cv(): + # test for LogisticRegressionCV object + n_samples, n_features = 50, 5 + rng = np.random.RandomState(0) + 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() + lr_cv = LogisticRegressionCV( + Cs=[1.0], fit_intercept=False, solver="liblinear", cv=3 + ) + lr_cv.fit(X_ref, y) + lr = LogisticRegression(C=1.0, fit_intercept=False, solver="liblinear") + lr.fit(X_ref, y) + assert_array_almost_equal(lr.coef_, lr_cv.coef_) + + assert_array_equal(lr_cv.coef_.shape, (1, n_features)) + assert_array_equal(lr_cv.classes_, [-1, 1]) + assert len(lr_cv.classes_) == 2 + + coefs_paths = np.asarray(list(lr_cv.coefs_paths_.values())) + assert_array_equal(coefs_paths.shape, (1, 3, 1, n_features)) + assert_array_equal(lr_cv.Cs_.shape, (1,)) + scores = np.asarray(list(lr_cv.scores_.values())) + assert_array_equal(scores.shape, (1, 3, 1)) + + +@pytest.mark.parametrize( + "scoring, multiclass_agg_list", + [ + ("accuracy", [""]), + ("precision", ["_macro", "_weighted"]), + # no need to test for micro averaging because it + # is the same as accuracy for f1, precision, + # and recall (see https://github.com/ + # scikit-learn/scikit-learn/pull/ + # 11578#discussion_r203250062) + ("f1", ["_macro", "_weighted"]), + ("neg_log_loss", [""]), + ("recall", ["_macro", "_weighted"]), + ], +) +def test_logistic_cv_multinomial_score(scoring, multiclass_agg_list): + # test that LogisticRegressionCV uses the right score to compute its + # cross-validation scores when using a multinomial scoring + # see https://github.com/scikit-learn/scikit-learn/issues/8720 + X, y = make_classification( + n_samples=100, random_state=0, n_classes=3, n_informative=6 + ) + train, test = np.arange(80), np.arange(80, 100) + lr = LogisticRegression(C=1.0) + # we use lbfgs to support multinomial + params = lr.get_params() + # we store the params to set them further in _log_reg_scoring_path + for key in ["C", "n_jobs", "warm_start"]: + del params[key] + lr.fit(X[train], y[train]) + for averaging in multiclass_agg_list: + scorer = get_scorer(scoring + averaging) + assert_array_almost_equal( + _log_reg_scoring_path( + X, + y, + train, + test, + Cs=[1.0], + scoring=scorer, + pos_class=None, + max_squared_sum=None, + sample_weight=None, + score_params=None, + **(params | {"multi_class": "multinomial"}), + )[2][0], + scorer(lr, X[test], y[test]), + ) + + +def test_multinomial_logistic_regression_string_inputs(): + # Test with string labels for LogisticRegression(CV) + n_samples, n_features, n_classes = 50, 5, 3 + X_ref, y = make_classification( + n_samples=n_samples, + n_features=n_features, + n_classes=n_classes, + n_informative=3, + random_state=0, + ) + y_str = LabelEncoder().fit(["bar", "baz", "foo"]).inverse_transform(y) + # For numerical labels, let y values be taken from set (-1, 0, 1) + y = np.array(y) - 1 + # Test for string labels + lr = LogisticRegression() + lr_cv = LogisticRegressionCV(Cs=3) + lr_str = LogisticRegression() + lr_cv_str = LogisticRegressionCV(Cs=3) + + lr.fit(X_ref, y) + lr_cv.fit(X_ref, y) + lr_str.fit(X_ref, y_str) + lr_cv_str.fit(X_ref, y_str) + + assert_array_almost_equal(lr.coef_, lr_str.coef_) + assert sorted(lr_str.classes_) == ["bar", "baz", "foo"] + assert_array_almost_equal(lr_cv.coef_, lr_cv_str.coef_) + assert sorted(lr_str.classes_) == ["bar", "baz", "foo"] + assert sorted(lr_cv_str.classes_) == ["bar", "baz", "foo"] + + # The predictions should be in original labels + assert sorted(np.unique(lr_str.predict(X_ref))) == ["bar", "baz", "foo"] + assert sorted(np.unique(lr_cv_str.predict(X_ref))) == ["bar", "baz", "foo"] + + # Make sure class weights can be given with string labels + lr_cv_str = LogisticRegression(class_weight={"bar": 1, "baz": 2, "foo": 0}).fit( + X_ref, y_str + ) + assert sorted(np.unique(lr_cv_str.predict(X_ref))) == ["bar", "baz"] + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_logistic_cv_sparse(csr_container): + X, y = make_classification(n_samples=50, n_features=5, random_state=0) + X[X < 1.0] = 0.0 + csr = csr_container(X) + + clf = LogisticRegressionCV() + clf.fit(X, y) + clfs = LogisticRegressionCV() + clfs.fit(csr, y) + assert_array_almost_equal(clfs.coef_, clf.coef_) + assert_array_almost_equal(clfs.intercept_, clf.intercept_) + assert clfs.C_ == clf.C_ + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +# Best remove this whole test. +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +def test_ovr_multinomial_iris(): + # Test that OvR and multinomial are correct using the iris dataset. + train, target = iris.data, iris.target + n_samples, n_features = train.shape + + # The cv indices from stratified kfold (where stratification is done based + # on the fine-grained iris classes, i.e, before the classes 0 and 1 are + # conflated) is used for both clf and clf1 + n_cv = 2 + cv = StratifiedKFold(n_cv) + precomputed_folds = list(cv.split(train, target)) + + # Train clf on the original dataset where classes 0 and 1 are separated + clf = LogisticRegressionCV(cv=precomputed_folds, multi_class="ovr") + clf.fit(train, target) + + # Conflate classes 0 and 1 and train clf1 on this modified dataset + clf1 = LogisticRegressionCV(cv=precomputed_folds, multi_class="ovr") + target_copy = target.copy() + target_copy[target_copy == 0] = 1 + clf1.fit(train, target_copy) + + # Ensure that what OvR learns for class2 is same regardless of whether + # classes 0 and 1 are separated or not + assert_allclose(clf.scores_[2], clf1.scores_[2]) + assert_allclose(clf.intercept_[2:], clf1.intercept_) + assert_allclose(clf.coef_[2][np.newaxis, :], clf1.coef_) + + # Test the shape of various attributes. + assert clf.coef_.shape == (3, n_features) + assert_array_equal(clf.classes_, [0, 1, 2]) + coefs_paths = np.asarray(list(clf.coefs_paths_.values())) + assert coefs_paths.shape == (3, n_cv, 10, n_features + 1) + assert clf.Cs_.shape == (10,) + scores = np.asarray(list(clf.scores_.values())) + assert scores.shape == (3, n_cv, 10) + + # Test that for the iris data multinomial gives a better accuracy than OvR + for solver in ["lbfgs", "newton-cg", "sag", "saga"]: + max_iter = 500 if solver in ["sag", "saga"] else 30 + clf_multi = LogisticRegressionCV( + solver=solver, + max_iter=max_iter, + random_state=42, + tol=1e-3 if solver in ["sag", "saga"] else 1e-2, + cv=2, + ) + if solver == "lbfgs": + # lbfgs requires scaling to avoid convergence warnings + train = scale(train) + + clf_multi.fit(train, target) + multi_score = clf_multi.score(train, target) + ovr_score = clf.score(train, target) + assert multi_score > ovr_score + + # Test attributes of LogisticRegressionCV + assert clf.coef_.shape == clf_multi.coef_.shape + assert_array_equal(clf_multi.classes_, [0, 1, 2]) + coefs_paths = np.asarray(list(clf_multi.coefs_paths_.values())) + assert coefs_paths.shape == (3, n_cv, 10, n_features + 1) + assert clf_multi.Cs_.shape == (10,) + scores = np.asarray(list(clf_multi.scores_.values())) + assert scores.shape == (3, n_cv, 10) + + +def test_logistic_regression_solvers(): + """Test solvers converge to the same result.""" + X, y = make_classification(n_features=10, n_informative=5, random_state=0) + + params = dict(fit_intercept=False, random_state=42) + + regressors = { + solver: LogisticRegression(solver=solver, **params).fit(X, y) + for solver in SOLVERS + } + + for solver_1, solver_2 in itertools.combinations(regressors, r=2): + assert_array_almost_equal( + regressors[solver_1].coef_, regressors[solver_2].coef_, decimal=3 + ) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_logistic_regression_solvers_multiclass(fit_intercept): + """Test solvers converge to the same result for multiclass problems.""" + X, y = make_classification( + n_samples=20, n_features=20, n_informative=10, n_classes=3, random_state=0 + ) + tol = 1e-8 + params = dict(fit_intercept=fit_intercept, tol=tol, random_state=42) + + # Override max iteration count for specific solvers to allow for + # proper convergence. + solver_max_iter = {"lbfgs": 200, "sag": 10_000, "saga": 10_000} + + regressors = { + solver: LogisticRegression( + solver=solver, max_iter=solver_max_iter.get(solver, 100), **params + ).fit(X, y) + for solver in set(SOLVERS) - set(["liblinear"]) + } + + for solver_1, solver_2 in itertools.combinations(regressors, r=2): + assert_allclose( + regressors[solver_1].coef_, + regressors[solver_2].coef_, + rtol=5e-3 if (solver_1 == "saga" or solver_2 == "saga") else 1e-3, + err_msg=f"{solver_1} vs {solver_2}", + ) + if fit_intercept: + assert_allclose( + regressors[solver_1].intercept_, + regressors[solver_2].intercept_, + rtol=5e-3 if (solver_1 == "saga" or solver_2 == "saga") else 1e-3, + err_msg=f"{solver_1} vs {solver_2}", + ) + + +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_logistic_regression_solvers_multiclass_unpenalized( + fit_intercept, global_random_seed +): + """Test and compare solver results for unpenalized multinomial multiclass.""" + # We want to avoid perfect separation. + n_samples, n_features, n_classes = 100, 4, 3 + rng = np.random.RandomState(global_random_seed) + X = make_low_rank_matrix( + n_samples=n_samples, + n_features=n_features + fit_intercept, + effective_rank=n_features + fit_intercept, + tail_strength=0.1, + random_state=rng, + ) + if fit_intercept: + X[:, -1] = 1 + U, s, Vt = svd(X) + assert np.all(s > 1e-3) # to be sure that X is not singular + assert np.max(s) / np.min(s) < 100 # condition number of X + if fit_intercept: + X = X[:, :-1] + coef = rng.uniform(low=1, high=3, size=n_features * n_classes) + coef = coef.reshape(n_classes, n_features) + intercept = rng.uniform(low=-1, high=1, size=n_classes) * fit_intercept + raw_prediction = X @ coef.T + intercept + + loss = HalfMultinomialLoss(n_classes=n_classes) + proba = loss.link.inverse(raw_prediction) + # Only newer numpy version (1.22) support more dimensions on pvals. + y = np.zeros(n_samples) + for i in range(n_samples): + y[i] = np.argwhere(rng.multinomial(n=1, pvals=proba[i, :]))[0, 0] + + tol = 1e-9 + params = dict(fit_intercept=fit_intercept, random_state=42) + solver_max_iter = {"lbfgs": 200, "sag": 10_000, "saga": 10_000} + solver_tol = {"sag": 1e-8, "saga": 1e-8} + regressors = { + solver: LogisticRegression( + C=np.inf, + solver=solver, + tol=solver_tol.get(solver, tol), + max_iter=solver_max_iter.get(solver, 100), + **params, + ).fit(X, y) + for solver in set(SOLVERS) - set(["liblinear"]) + } + for solver in regressors.keys(): + # See the docstring of test_multinomial_identifiability_on_iris for reference. + assert_allclose( + regressors[solver].coef_.sum(axis=0), 0, atol=1e-10, err_msg=solver + ) + + for solver_1, solver_2 in itertools.combinations(regressors, r=2): + assert_allclose( + regressors[solver_1].coef_, + regressors[solver_2].coef_, + rtol=5e-3 if (solver_1 == "saga" or solver_2 == "saga") else 2e-3, + err_msg=f"{solver_1} vs {solver_2}", + ) + if fit_intercept: + assert_allclose( + regressors[solver_1].intercept_, + regressors[solver_2].intercept_, + rtol=5e-3 if (solver_1 == "saga" or solver_2 == "saga") else 1e-3, + err_msg=f"{solver_1} vs {solver_2}", + ) + + +@pytest.mark.parametrize("weight", [{0: 0.1, 1: 0.2}, {0: 0.1, 1: 0.2, 2: 0.5}]) +@pytest.mark.parametrize("class_weight", ["weight", "balanced"]) +def test_logistic_regressioncv_class_weights(weight, class_weight, global_random_seed): + """Test class_weight for LogisticRegressionCV.""" + n_classes = len(weight) + if class_weight == "weight": + class_weight = weight + + X, y = make_classification( + n_samples=30, + n_features=3, + n_repeated=0, + n_informative=3, + n_redundant=0, + n_classes=n_classes, + random_state=global_random_seed, + ) + params = dict( + Cs=1, + fit_intercept=False, + class_weight=class_weight, + tol=1e-8, + ) + clf_lbfgs = LogisticRegressionCV(solver="lbfgs", **params) + + # XXX: lbfgs' line search can fail and cause a ConvergenceWarning for some + # 10% of the random seeds, but only on specific platforms (in particular + # when using Atlas BLAS/LAPACK implementation). Doubling the maxls internal + # parameter of the solver does not help. However this lack of proper + # convergence does not seem to prevent the assertion to pass, so we ignore + # the warning for now. + # See: https://github.com/scikit-learn/scikit-learn/pull/27649 + with ignore_warnings(category=ConvergenceWarning): + clf_lbfgs.fit(X, y) + + for solver in set(SOLVERS) - set(["lbfgs", "liblinear", "newton-cholesky"]): + clf = LogisticRegressionCV(solver=solver, **params) + if solver in ("sag", "saga"): + clf.set_params( + tol=1e-18, max_iter=10000, random_state=global_random_seed + 1 + ) + clf.fit(X, y) + + assert_allclose( + clf.coef_, clf_lbfgs.coef_, rtol=1e-3, err_msg=f"{solver} vs lbfgs" + ) + + +@pytest.mark.parametrize("problem", ("single", "cv")) +@pytest.mark.parametrize( + "solver", ("lbfgs", "liblinear", "newton-cg", "newton-cholesky", "sag", "saga") +) +def test_logistic_regression_sample_weights(problem, solver, global_random_seed): + n_samples_per_cv_group = 200 + n_cv_groups = 3 + + X, y = make_classification( + n_samples=n_samples_per_cv_group * n_cv_groups, + n_features=5, + n_informative=3, + n_classes=2, + n_redundant=0, + random_state=global_random_seed, + ) + rng = np.random.RandomState(global_random_seed) + sw = np.ones(y.shape[0]) + + kw_weighted = { + "random_state": global_random_seed, + "fit_intercept": False, + "max_iter": 100_000 if solver.startswith("sag") else 1_000, + "tol": 1e-8, + } + kw_repeated = kw_weighted.copy() + sw[:n_samples_per_cv_group] = rng.randint(0, 5, size=n_samples_per_cv_group) + X_repeated = np.repeat(X, sw.astype(int), axis=0) + y_repeated = np.repeat(y, sw.astype(int), axis=0) + + if problem == "single": + LR = LogisticRegression + elif problem == "cv": + LR = LogisticRegressionCV + # We weight the first fold 2 times more. + groups_weighted = np.concatenate( + [ + np.full(n_samples_per_cv_group, 0), + np.full(n_samples_per_cv_group, 1), + np.full(n_samples_per_cv_group, 2), + ] + ) + splits_weighted = list(LeaveOneGroupOut().split(X, groups=groups_weighted)) + kw_weighted.update({"Cs": 100, "cv": splits_weighted}) + + groups_repeated = np.repeat(groups_weighted, sw.astype(int), axis=0) + splits_repeated = list( + LeaveOneGroupOut().split(X_repeated, groups=groups_repeated) + ) + kw_repeated.update({"Cs": 100, "cv": splits_repeated}) + + clf_sw_weighted = LR(solver=solver, **kw_weighted) + clf_sw_repeated = LR(solver=solver, **kw_repeated) + + if solver == "lbfgs": + # lbfgs has convergence issues on the data but this should not impact + # the quality of the results. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + clf_sw_weighted.fit(X, y, sample_weight=sw) + clf_sw_repeated.fit(X_repeated, y_repeated) + + else: + clf_sw_weighted.fit(X, y, sample_weight=sw) + clf_sw_repeated.fit(X_repeated, y_repeated) + + if problem == "cv": + assert_allclose(clf_sw_weighted.scores_[1], clf_sw_repeated.scores_[1]) + assert_allclose(clf_sw_weighted.coef_, clf_sw_repeated.coef_, atol=1e-5) + + +@pytest.mark.parametrize( + "solver", ("lbfgs", "newton-cg", "newton-cholesky", "sag", "saga") +) +def test_logistic_regression_solver_class_weights(solver, global_random_seed): + # Test that passing class_weight as [1, 2] is the same as + # passing class weight = [1,1] but adjusting sample weights + # to be 2 for all instances of class 1. + + X, y = make_classification( + n_samples=300, + n_features=5, + n_informative=3, + n_classes=2, + random_state=global_random_seed, + ) + + sample_weight = y + 1 + + kw_weighted = { + "random_state": global_random_seed, + "fit_intercept": False, + "max_iter": 100_000, + "tol": 1e-8, + } + clf_cw_12 = LogisticRegression( + solver=solver, class_weight={0: 1, 1: 2}, **kw_weighted + ) + clf_cw_12.fit(X, y) + clf_sw_12 = LogisticRegression(solver=solver, **kw_weighted) + clf_sw_12.fit(X, y, sample_weight=sample_weight) + assert_allclose(clf_cw_12.coef_, clf_sw_12.coef_, atol=1e-6) + + +def test_sample_and_class_weight_equivalence_liblinear(global_random_seed): + # Test the above for l1 penalty and l2 penalty with dual=True. + # since the patched liblinear code is different. + + X, y = make_classification( + n_samples=300, + n_features=5, + n_informative=3, + n_classes=2, + random_state=global_random_seed, + ) + + sample_weight = y + 1 + + clf_cw = LogisticRegression( + solver="liblinear", + fit_intercept=False, + class_weight={0: 1, 1: 2}, + penalty="l1", + max_iter=10_000, + tol=1e-12, + random_state=global_random_seed, + ) + clf_cw.fit(X, y) + clf_sw = LogisticRegression( + solver="liblinear", + fit_intercept=False, + penalty="l1", + max_iter=10_000, + tol=1e-12, + random_state=global_random_seed, + ) + clf_sw.fit(X, y, sample_weight) + assert_allclose(clf_cw.coef_, clf_sw.coef_, atol=1e-10) + + clf_cw = LogisticRegression( + solver="liblinear", + fit_intercept=False, + class_weight={0: 1, 1: 2}, + penalty="l2", + max_iter=10_000, + tol=1e-12, + dual=True, + random_state=global_random_seed, + ) + clf_cw.fit(X, y) + clf_sw = LogisticRegression( + solver="liblinear", + fit_intercept=False, + penalty="l2", + max_iter=10_000, + tol=1e-12, + dual=True, + random_state=global_random_seed, + ) + clf_sw.fit(X, y, sample_weight) + assert_allclose(clf_cw.coef_, clf_sw.coef_, atol=1e-10) + + +def _compute_class_weight_dictionary(y): + # helper for returning a dictionary instead of an array + classes = np.unique(y) + class_weight = compute_class_weight("balanced", classes=classes, y=y) + class_weight_dict = dict(zip(classes, class_weight)) + return class_weight_dict + + +@pytest.mark.parametrize("csr_container", [lambda x: x] + CSR_CONTAINERS) +def test_logistic_regression_class_weights(csr_container): + # Scale data to avoid convergence warnings with the lbfgs solver + X_iris = scale(iris.data) + # Multinomial case: remove 90% of class 0 + X = X_iris[45:, :] + X = csr_container(X) + y = iris.target[45:] + class_weight_dict = _compute_class_weight_dictionary(y) + + for solver in set(SOLVERS) - set(["liblinear", "newton-cholesky"]): + params = dict(solver=solver, max_iter=1000) + clf1 = LogisticRegression(class_weight="balanced", **params) + clf2 = LogisticRegression(class_weight=class_weight_dict, **params) + clf1.fit(X, y) + clf2.fit(X, y) + assert len(clf1.classes_) == 3 + assert_allclose(clf1.coef_, clf2.coef_, rtol=1e-4) + # Same as appropriate sample_weight. + sw = np.ones(X.shape[0]) + for c in clf1.classes_: + sw[y == c] *= class_weight_dict[c] + clf3 = LogisticRegression(**params).fit(X, y, sample_weight=sw) + assert_allclose(clf3.coef_, clf2.coef_, rtol=1e-4) + + # Binary case: remove 90% of class 0 and 100% of class 2 + X = X_iris[45:100, :] + y = iris.target[45:100] + class_weight_dict = _compute_class_weight_dictionary(y) + + for solver in SOLVERS: + params = dict(solver=solver, max_iter=1000) + clf1 = LogisticRegression(class_weight="balanced", **params) + clf2 = LogisticRegression(class_weight=class_weight_dict, **params) + clf1.fit(X, y) + clf2.fit(X, y) + assert_array_almost_equal(clf1.coef_, clf2.coef_, decimal=6) + + +def test_logistic_regression_multinomial(): + # Tests for the multinomial option in logistic regression + + # Some basic attributes of Logistic Regression + n_samples, n_features, n_classes = 50, 20, 3 + X, y = make_classification( + n_samples=n_samples, + n_features=n_features, + n_informative=10, + n_classes=n_classes, + random_state=0, + ) + + X = StandardScaler(with_mean=False).fit_transform(X) + + # 'lbfgs' is used as a referenced + solver = "lbfgs" + ref_i = LogisticRegression(solver=solver, tol=1e-6) + ref_w = LogisticRegression(solver=solver, fit_intercept=False, tol=1e-6) + ref_i.fit(X, y) + ref_w.fit(X, y) + assert ref_i.coef_.shape == (n_classes, n_features) + assert ref_w.coef_.shape == (n_classes, n_features) + for solver in ["sag", "saga", "newton-cg"]: + clf_i = LogisticRegression( + solver=solver, + random_state=42, + max_iter=2000, + tol=1e-7, + ) + clf_w = LogisticRegression( + solver=solver, + random_state=42, + max_iter=2000, + tol=1e-7, + fit_intercept=False, + ) + clf_i.fit(X, y) + clf_w.fit(X, y) + assert clf_i.coef_.shape == (n_classes, n_features) + assert clf_w.coef_.shape == (n_classes, n_features) + + # Compare solutions between lbfgs and the other solvers + assert_allclose(ref_i.coef_, clf_i.coef_, rtol=1e-3) + assert_allclose(ref_w.coef_, clf_w.coef_, rtol=1e-2) + assert_allclose(ref_i.intercept_, clf_i.intercept_, rtol=1e-3) + + # Test that the path give almost the same results. However since in this + # case we take the average of the coefs after fitting across all the + # folds, it need not be exactly the same. + for solver in ["lbfgs", "newton-cg", "sag", "saga"]: + clf_path = LogisticRegressionCV( + solver=solver, max_iter=2000, tol=1e-6, Cs=[1.0] + ) + clf_path.fit(X, y) + assert_allclose(clf_path.coef_, ref_i.coef_, rtol=1e-2) + assert_allclose(clf_path.intercept_, ref_i.intercept_, rtol=1e-2) + + +def test_liblinear_decision_function_zero(): + # Test negative prediction when decision_function values are zero. + # Liblinear predicts the positive class when decision_function values + # are zero. This is a test to verify that we do not do the same. + # See Issue: https://github.com/scikit-learn/scikit-learn/issues/3600 + # and the PR https://github.com/scikit-learn/scikit-learn/pull/3623 + X, y = make_classification(n_samples=5, n_features=5, random_state=0) + clf = LogisticRegression(fit_intercept=False, solver="liblinear") + clf.fit(X, y) + + # Dummy data such that the decision function becomes zero. + X = np.zeros((5, 5)) + assert_array_equal(clf.predict(X), np.zeros(5)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_liblinear_logregcv_sparse(csr_container): + # Test LogRegCV with solver='liblinear' works for sparse matrices + + X, y = make_classification(n_samples=10, n_features=5, random_state=0) + clf = LogisticRegressionCV(solver="liblinear") + clf.fit(csr_container(X), y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_saga_sparse(csr_container): + # Test LogRegCV with solver='liblinear' works for sparse matrices + + X, y = make_classification(n_samples=10, n_features=5, random_state=0) + clf = LogisticRegressionCV(solver="saga", tol=1e-2) + clf.fit(csr_container(X), y) + + +def test_logreg_intercept_scaling_zero(): + # Test that intercept_scaling is ignored when fit_intercept is False + + clf = LogisticRegression(fit_intercept=False) + clf.fit(X, Y1) + assert clf.intercept_ == 0.0 + + +def test_logreg_l1(): + # Because liblinear penalizes the intercept and saga does not, we do not + # fit the intercept to make it possible to compare the coefficients of + # the two models at convergence. + rng = np.random.RandomState(42) + n_samples = 50 + X, y = make_classification(n_samples=n_samples, n_features=20, random_state=0) + X_noise = rng.normal(size=(n_samples, 3)) + X_constant = np.ones(shape=(n_samples, 2)) + X = np.concatenate((X, X_noise, X_constant), axis=1) + lr_liblinear = LogisticRegression( + penalty="l1", + C=1.0, + solver="liblinear", + fit_intercept=False, + tol=1e-10, + ) + lr_liblinear.fit(X, y) + + lr_saga = LogisticRegression( + penalty="l1", + C=1.0, + solver="saga", + fit_intercept=False, + max_iter=1000, + tol=1e-10, + ) + lr_saga.fit(X, y) + assert_array_almost_equal(lr_saga.coef_, lr_liblinear.coef_) + + # Noise and constant features should be regularized to zero by the l1 + # penalty + assert_array_almost_equal(lr_liblinear.coef_[0, -5:], np.zeros(5)) + assert_array_almost_equal(lr_saga.coef_[0, -5:], np.zeros(5)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_logreg_l1_sparse_data(csr_container): + # Because liblinear penalizes the intercept and saga does not, we do not + # fit the intercept to make it possible to compare the coefficients of + # the two models at convergence. + rng = np.random.RandomState(42) + n_samples = 50 + X, y = make_classification(n_samples=n_samples, n_features=20, random_state=0) + X_noise = rng.normal(scale=0.1, size=(n_samples, 3)) + X_constant = np.zeros(shape=(n_samples, 2)) + X = np.concatenate((X, X_noise, X_constant), axis=1) + X[X < 1] = 0 + X = csr_container(X) + + lr_liblinear = LogisticRegression( + penalty="l1", + C=1.0, + solver="liblinear", + fit_intercept=False, + tol=1e-10, + ) + lr_liblinear.fit(X, y) + + lr_saga = LogisticRegression( + penalty="l1", + C=1.0, + solver="saga", + fit_intercept=False, + max_iter=1000, + tol=1e-10, + ) + lr_saga.fit(X, y) + assert_array_almost_equal(lr_saga.coef_, lr_liblinear.coef_) + # Noise and constant features should be regularized to zero by the l1 + # penalty + assert_array_almost_equal(lr_liblinear.coef_[0, -5:], np.zeros(5)) + assert_array_almost_equal(lr_saga.coef_[0, -5:], np.zeros(5)) + + # Check that solving on the sparse and dense data yield the same results + lr_saga_dense = LogisticRegression( + penalty="l1", + C=1.0, + solver="saga", + fit_intercept=False, + max_iter=1000, + tol=1e-10, + ) + lr_saga_dense.fit(X.toarray(), y) + assert_array_almost_equal(lr_saga.coef_, lr_saga_dense.coef_) + + +@pytest.mark.parametrize("random_seed", [42]) +@pytest.mark.parametrize("penalty", ["l1", "l2"]) +def test_logistic_regression_cv_refit(random_seed, penalty): + # Test that when refit=True, logistic regression cv with the saga solver + # converges to the same solution as logistic regression with a fixed + # regularization parameter. + # Internally the LogisticRegressionCV model uses a warm start to refit on + # the full data model with the optimal C found by CV. As the penalized + # logistic regression loss is convex, we should still recover exactly + # the same solution as long as the stopping criterion is strict enough (and + # that there are no exactly duplicated features when penalty='l1'). + X, y = make_classification(n_samples=100, n_features=20, random_state=random_seed) + common_params = dict( + solver="saga", + penalty=penalty, + random_state=random_seed, + max_iter=1000, + tol=1e-12, + ) + lr_cv = LogisticRegressionCV(Cs=[1.0], refit=True, **common_params) + lr_cv.fit(X, y) + lr = LogisticRegression(C=1.0, **common_params) + lr.fit(X, y) + assert_array_almost_equal(lr_cv.coef_, lr.coef_) + + +def test_logreg_predict_proba_multinomial(): + X, y = make_classification( + n_samples=10, n_features=20, random_state=0, n_classes=3, n_informative=10 + ) + + # Predicted probabilities using the true-entropy loss should give a + # smaller loss than those using the ovr method. + clf_multi = LogisticRegression(solver="lbfgs") + clf_multi.fit(X, y) + clf_multi_loss = log_loss(y, clf_multi.predict_proba(X)) + clf_ovr = OneVsRestClassifier(LogisticRegression(solver="lbfgs")) + clf_ovr.fit(X, y) + clf_ovr_loss = log_loss(y, clf_ovr.predict_proba(X)) + assert clf_ovr_loss > clf_multi_loss + + # Predicted probabilities using the soft-max function should give a + # smaller loss than those using the logistic function. + clf_multi_loss = log_loss(y, clf_multi.predict_proba(X)) + clf_wrong_loss = log_loss(y, clf_multi._predict_proba_lr(X)) + assert clf_wrong_loss > clf_multi_loss + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("max_iter", np.arange(1, 5)) +@pytest.mark.parametrize("multi_class", ["ovr", "multinomial"]) +@pytest.mark.parametrize( + "solver, message", + [ + ( + "newton-cg", + "newton-cg failed to converge.* Increase the number of iterations.", + ), + ( + "liblinear", + "Liblinear failed to converge, increase the number of iterations.", + ), + ("sag", "The max_iter was reached which means the coef_ did not converge"), + ("saga", "The max_iter was reached which means the coef_ did not converge"), + ("lbfgs", "lbfgs failed to converge"), + ("newton-cholesky", "Newton solver did not converge after [0-9]* iterations"), + ], +) +def test_max_iter(max_iter, multi_class, solver, message): + # Test that the maximum number of iteration is reached + X, y_bin = iris.data, iris.target.copy() + y_bin[y_bin == 2] = 0 + + if solver in ("liblinear",) and multi_class == "multinomial": + pytest.skip("'multinomial' is not supported by liblinear") + if solver == "newton-cholesky" and max_iter > 1: + pytest.skip("solver newton-cholesky might converge very fast") + + lr = LogisticRegression( + max_iter=max_iter, + tol=1e-15, + multi_class=multi_class, + random_state=0, + solver=solver, + ) + with pytest.warns(ConvergenceWarning, match=message): + lr.fit(X, y_bin) + + assert lr.n_iter_[0] == max_iter + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.filterwarnings( + "ignore:.*'liblinear' solver for multiclass classification is deprecated.*" +) +@pytest.mark.parametrize("solver", SOLVERS) +def test_n_iter(solver): + # Test that self.n_iter_ has the correct format. + X, y = iris.data, iris.target + if solver == "lbfgs": + # lbfgs requires scaling to avoid convergence warnings + X = scale(X) + + n_classes = np.unique(y).shape[0] + assert n_classes == 3 + + # Also generate a binary classification sub-problem. + y_bin = y.copy() + y_bin[y_bin == 2] = 0 + + n_Cs = 4 + n_cv_fold = 2 + + # Binary classification case + clf = LogisticRegression(tol=1e-2, C=1.0, solver=solver, random_state=42) + clf.fit(X, y_bin) + assert clf.n_iter_.shape == (1,) + + clf_cv = LogisticRegressionCV( + tol=1e-2, solver=solver, Cs=n_Cs, cv=n_cv_fold, random_state=42 + ) + clf_cv.fit(X, y_bin) + assert clf_cv.n_iter_.shape == (1, n_cv_fold, n_Cs) + + # OvR case + clf.set_params(multi_class="ovr").fit(X, y) + assert clf.n_iter_.shape == (n_classes,) + + clf_cv.set_params(multi_class="ovr").fit(X, y) + assert clf_cv.n_iter_.shape == (n_classes, n_cv_fold, n_Cs) + + # multinomial case + if solver in ("liblinear",): + # This solver only supports one-vs-rest multiclass classification. + return + + # When using the multinomial objective function, there is a single + # optimization problem to solve for all classes at once: + clf.set_params(multi_class="multinomial").fit(X, y) + assert clf.n_iter_.shape == (1,) + + clf_cv.set_params(multi_class="multinomial").fit(X, y) + assert clf_cv.n_iter_.shape == (1, n_cv_fold, n_Cs) + + +@pytest.mark.parametrize("solver", sorted(set(SOLVERS) - set(["liblinear"]))) +@pytest.mark.parametrize("warm_start", (True, False)) +@pytest.mark.parametrize("fit_intercept", (True, False)) +def test_warm_start(solver, warm_start, fit_intercept): + # A 1-iteration second fit on same data should give almost same result + # with warm starting, and quite different result without warm starting. + # Warm starting does not work with liblinear solver. + X, y = iris.data, iris.target + + clf = LogisticRegression( + tol=1e-4, + warm_start=warm_start, + solver=solver, + random_state=42, + fit_intercept=fit_intercept, + ) + with ignore_warnings(category=ConvergenceWarning): + clf.fit(X, y) + coef_1 = clf.coef_ + + clf.max_iter = 1 + clf.fit(X, y) + cum_diff = np.sum(np.abs(coef_1 - clf.coef_)) + msg = ( + f"Warm starting issue with solver {solver}" + f"with {fit_intercept=} and {warm_start=}" + ) + if warm_start: + assert 2.0 > cum_diff, msg + else: + assert cum_diff > 2.0, msg + + +@pytest.mark.parametrize("solver", ["newton-cholesky", "newton-cg"]) +@pytest.mark.parametrize("fit_intercept", (True, False)) +@pytest.mark.parametrize("penalty", ("l2", None)) +def test_warm_start_newton_solver(global_random_seed, solver, fit_intercept, penalty): + """Test that 2 steps at once are the same as 2 single steps with warm start.""" + X, y = iris.data, iris.target + + clf1 = LogisticRegression( + solver=solver, + max_iter=2, + fit_intercept=fit_intercept, + penalty=penalty, + random_state=global_random_seed, + ) + with ignore_warnings(category=ConvergenceWarning): + clf1.fit(X, y) + + clf2 = LogisticRegression( + solver=solver, + max_iter=1, + warm_start=True, + fit_intercept=fit_intercept, + penalty=penalty, + random_state=global_random_seed, + ) + with ignore_warnings(category=ConvergenceWarning): + clf2.fit(X, y) + clf2.fit(X, y) + + assert_allclose(clf2.coef_, clf1.coef_) + if fit_intercept: + assert_allclose(clf2.intercept_, clf1.intercept_) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_saga_vs_liblinear(csr_container): + iris = load_iris() + X, y = iris.data, iris.target + X = np.concatenate([X] * 3) + y = np.concatenate([y] * 3) + + X_bin = X[y <= 1] + y_bin = y[y <= 1] * 2 - 1 + + X_sparse, y_sparse = make_classification( + n_samples=50, n_features=20, random_state=0 + ) + X_sparse = csr_container(X_sparse) + + for X, y in ((X_bin, y_bin), (X_sparse, y_sparse)): + for penalty in ["l1", "l2"]: + n_samples = X.shape[0] + # alpha=1e-3 is time consuming + for alpha in np.logspace(-1, 1, 3): + saga = LogisticRegression( + C=1.0 / (n_samples * alpha), + solver="saga", + max_iter=200, + fit_intercept=False, + penalty=penalty, + random_state=0, + tol=1e-6, + ) + + liblinear = LogisticRegression( + C=1.0 / (n_samples * alpha), + solver="liblinear", + max_iter=200, + fit_intercept=False, + penalty=penalty, + random_state=0, + tol=1e-6, + ) + + saga.fit(X, y) + liblinear.fit(X, y) + # Convergence for alpha=1e-3 is very slow + assert_array_almost_equal(saga.coef_, liblinear.coef_, 3) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("multi_class", ["ovr", "multinomial"]) +@pytest.mark.parametrize( + "solver", ["liblinear", "newton-cg", "newton-cholesky", "saga"] +) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dtype_match(solver, multi_class, fit_intercept, csr_container): + # Test that np.float32 input data is not cast to np.float64 when possible + # and that the output is approximately the same no matter the input format. + + if solver == "liblinear" and multi_class == "multinomial": + pytest.skip(f"Solver={solver} does not support multinomial logistic.") + + out32_type = np.float64 if solver == "liblinear" else np.float32 + + X_32 = np.array(X).astype(np.float32) + 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 = csr_container(X, dtype=np.float32) + X_sparse_64 = csr_container(X, dtype=np.float64) + solver_tol = 5e-4 + + lr_templ = LogisticRegression( + solver=solver, + multi_class=multi_class, + random_state=42, + tol=solver_tol, + fit_intercept=fit_intercept, + ) + + # Check 32-bit type consistency + lr_32 = clone(lr_templ) + lr_32.fit(X_32, y_32) + assert lr_32.coef_.dtype == out32_type + + # Check 32-bit type consistency with sparsity + lr_32_sparse = clone(lr_templ) + lr_32_sparse.fit(X_sparse_32, y_32) + assert lr_32_sparse.coef_.dtype == out32_type + + # Check 64-bit type consistency + lr_64 = clone(lr_templ) + lr_64.fit(X_64, y_64) + assert lr_64.coef_.dtype == np.float64 + + # Check 64-bit type consistency with sparsity + lr_64_sparse = clone(lr_templ) + lr_64_sparse.fit(X_sparse_64, y_64) + assert lr_64_sparse.coef_.dtype == np.float64 + + # solver_tol bounds the norm of the loss gradient + # dw ~= inv(H)*grad ==> |dw| ~= |inv(H)| * solver_tol, where H - hessian + # + # See https://github.com/scikit-learn/scikit-learn/pull/13645 + # + # with Z = np.hstack((np.ones((3,1)), np.array(X))) + # In [8]: np.linalg.norm(np.diag([0,2,2]) + np.linalg.inv((Z.T @ Z)/4)) + # Out[8]: 1.7193336918135917 + + # factor of 2 to get the ball diameter + atol = 2 * 1.72 * solver_tol + if os.name == "nt" and _IS_32BIT: + # FIXME + atol = 1e-2 + + # Check accuracy consistency + assert_allclose(lr_32.coef_, lr_64.coef_.astype(np.float32), atol=atol) + + if solver == "saga" and fit_intercept: + # FIXME: SAGA on sparse data fits the intercept inaccurately with the + # default tol and max_iter parameters. + atol = 1e-1 + + assert_allclose(lr_32.coef_, lr_32_sparse.coef_, atol=atol) + assert_allclose(lr_64.coef_, lr_64_sparse.coef_, atol=atol) + + +def test_warm_start_converge_LR(): + # Test to see that the logistic regression converges on warm start, + # with multi_class='multinomial'. Non-regressive test for #10836 + + rng = np.random.RandomState(0) + X = np.concatenate((rng.randn(100, 2) + [1, 1], rng.randn(100, 2))) + y = np.array([1] * 100 + [-1] * 100) + lr_no_ws = LogisticRegression(solver="sag", warm_start=False, random_state=0) + lr_ws = LogisticRegression(solver="sag", warm_start=True, random_state=0) + + lr_no_ws_loss = log_loss(y, lr_no_ws.fit(X, y).predict_proba(X)) + for i in range(5): + lr_ws.fit(X, y) + lr_ws_loss = log_loss(y, lr_ws.predict_proba(X)) + assert_allclose(lr_no_ws_loss, lr_ws_loss, rtol=1e-5) + + +def test_elastic_net_coeffs(): + # make sure elasticnet penalty gives different coefficients from l1 and l2 + # with saga solver (l1_ratio different from 0 or 1) + X, y = make_classification(random_state=0) + + C = 2.0 + l1_ratio = 0.5 + coeffs = list() + for penalty, ratio in (("elasticnet", l1_ratio), ("l1", None), ("l2", None)): + lr = LogisticRegression( + penalty=penalty, + C=C, + solver="saga", + random_state=0, + l1_ratio=ratio, + tol=1e-3, + max_iter=200, + ) + lr.fit(X, y) + coeffs.append(lr.coef_) + + elastic_net_coeffs, l1_coeffs, l2_coeffs = coeffs + # make sure coeffs differ by at least .1 + assert not np.allclose(elastic_net_coeffs, l1_coeffs, rtol=0, atol=0.1) + assert not np.allclose(elastic_net_coeffs, l2_coeffs, rtol=0, atol=0.1) + assert not np.allclose(l2_coeffs, l1_coeffs, rtol=0, atol=0.1) + + +@pytest.mark.parametrize("C", [0.001, 0.1, 1, 10, 100, 1000, 1e6]) +@pytest.mark.parametrize("penalty, l1_ratio", [("l1", 1), ("l2", 0)]) +def test_elastic_net_l1_l2_equivalence(C, penalty, l1_ratio): + # Make sure elasticnet is equivalent to l1 when l1_ratio=1 and to l2 when + # l1_ratio=0. + X, y = make_classification(random_state=0) + + lr_enet = LogisticRegression( + penalty="elasticnet", + C=C, + l1_ratio=l1_ratio, + solver="saga", + random_state=0, + tol=1e-2, + ) + lr_expected = LogisticRegression( + penalty=penalty, C=C, solver="saga", random_state=0, tol=1e-2 + ) + lr_enet.fit(X, y) + lr_expected.fit(X, y) + + assert_array_almost_equal(lr_enet.coef_, lr_expected.coef_) + + +@pytest.mark.parametrize("C", [0.001, 1, 100, 1e6]) +def test_elastic_net_vs_l1_l2(C): + # Make sure that elasticnet with grid search on l1_ratio gives same or + # better results than just l1 or just l2. + + X, y = make_classification(500, random_state=0) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + param_grid = {"l1_ratio": np.linspace(0, 1, 5)} + + enet_clf = LogisticRegression( + penalty="elasticnet", C=C, solver="saga", random_state=0, tol=1e-2 + ) + gs = GridSearchCV(enet_clf, param_grid, refit=True) + + l1_clf = LogisticRegression( + penalty="l1", C=C, solver="saga", random_state=0, tol=1e-2 + ) + l2_clf = LogisticRegression( + penalty="l2", C=C, solver="saga", random_state=0, tol=1e-2 + ) + + for clf in (gs, l1_clf, l2_clf): + clf.fit(X_train, y_train) + + assert gs.score(X_test, y_test) >= l1_clf.score(X_test, y_test) + assert gs.score(X_test, y_test) >= l2_clf.score(X_test, y_test) + + +@pytest.mark.parametrize("C", np.logspace(-3, 2, 4)) +@pytest.mark.parametrize("l1_ratio", [0.1, 0.5, 0.9]) +def test_LogisticRegression_elastic_net_objective(C, l1_ratio): + # Check that training with a penalty matching the objective leads + # to a lower objective. + # Here we train a logistic regression with l2 (a) and elasticnet (b) + # penalties, and compute the elasticnet objective. That of a should be + # greater than that of b (both objectives are convex). + X, y = make_classification( + n_samples=1000, + n_classes=2, + n_features=20, + n_informative=10, + n_redundant=0, + n_repeated=0, + random_state=0, + ) + X = scale(X) + + lr_enet = LogisticRegression( + penalty="elasticnet", + solver="saga", + random_state=0, + C=C, + l1_ratio=l1_ratio, + fit_intercept=False, + ) + lr_l2 = LogisticRegression( + penalty="l2", solver="saga", random_state=0, C=C, fit_intercept=False + ) + lr_enet.fit(X, y) + lr_l2.fit(X, y) + + def enet_objective(lr): + coef = lr.coef_.ravel() + obj = C * log_loss(y, lr.predict_proba(X)) + obj += l1_ratio * np.sum(np.abs(coef)) + obj += (1.0 - l1_ratio) * 0.5 * np.dot(coef, coef) + return obj + + assert enet_objective(lr_enet) < enet_objective(lr_l2) + + +@pytest.mark.parametrize("n_classes", (2, 3)) +def test_LogisticRegressionCV_GridSearchCV_elastic_net(n_classes): + # make sure LogisticRegressionCV gives same best params (l1 and C) as + # GridSearchCV when penalty is elasticnet + + X, y = make_classification( + n_samples=100, n_classes=n_classes, n_informative=3, random_state=0 + ) + + cv = StratifiedKFold(5) + + l1_ratios = np.linspace(0, 1, 3) + Cs = np.logspace(-4, 4, 3) + + lrcv = LogisticRegressionCV( + penalty="elasticnet", + Cs=Cs, + solver="saga", + cv=cv, + l1_ratios=l1_ratios, + random_state=0, + tol=1e-2, + ) + lrcv.fit(X, y) + + param_grid = {"C": Cs, "l1_ratio": l1_ratios} + lr = LogisticRegression( + penalty="elasticnet", + solver="saga", + random_state=0, + tol=1e-2, + ) + gs = GridSearchCV(lr, param_grid, cv=cv) + gs.fit(X, y) + + assert gs.best_params_["l1_ratio"] == lrcv.l1_ratio_[0] + assert gs.best_params_["C"] == lrcv.C_[0] + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +# Maybe remove whole test after removal of the deprecated multi_class. +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +def test_LogisticRegressionCV_GridSearchCV_elastic_net_ovr(): + # make sure LogisticRegressionCV gives same best params (l1 and C) as + # GridSearchCV when penalty is elasticnet and multiclass is ovr. We can't + # compare best_params like in the previous test because + # LogisticRegressionCV with multi_class='ovr' will have one C and one + # l1_param for each class, while LogisticRegression will share the + # parameters over the *n_classes* classifiers. + + X, y = make_classification( + n_samples=100, n_classes=3, n_informative=3, random_state=0 + ) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + cv = StratifiedKFold(5) + + l1_ratios = np.linspace(0, 1, 3) + Cs = np.logspace(-4, 4, 3) + + lrcv = LogisticRegressionCV( + penalty="elasticnet", + Cs=Cs, + solver="saga", + cv=cv, + l1_ratios=l1_ratios, + random_state=0, + multi_class="ovr", + tol=1e-2, + ) + lrcv.fit(X_train, y_train) + + param_grid = {"C": Cs, "l1_ratio": l1_ratios} + lr = LogisticRegression( + penalty="elasticnet", + solver="saga", + random_state=0, + multi_class="ovr", + tol=1e-2, + ) + gs = GridSearchCV(lr, param_grid, cv=cv) + gs.fit(X_train, y_train) + + # Check that predictions are 80% the same + assert (lrcv.predict(X_train) == gs.predict(X_train)).mean() >= 0.8 + assert (lrcv.predict(X_test) == gs.predict(X_test)).mean() >= 0.8 + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("penalty", ("l2", "elasticnet")) +@pytest.mark.parametrize("multi_class", ("ovr", "multinomial", "auto")) +def test_LogisticRegressionCV_no_refit(penalty, multi_class): + # Test LogisticRegressionCV attribute shapes when refit is False + + n_classes = 3 + n_features = 20 + X, y = make_classification( + n_samples=200, + n_classes=n_classes, + n_informative=n_classes, + n_features=n_features, + random_state=0, + ) + + Cs = np.logspace(-4, 4, 3) + if penalty == "elasticnet": + l1_ratios = np.linspace(0, 1, 2) + else: + l1_ratios = None + + lrcv = LogisticRegressionCV( + penalty=penalty, + Cs=Cs, + solver="saga", + l1_ratios=l1_ratios, + random_state=0, + multi_class=multi_class, + tol=1e-2, + refit=False, + ) + lrcv.fit(X, y) + assert lrcv.C_.shape == (n_classes,) + assert lrcv.l1_ratio_.shape == (n_classes,) + assert lrcv.coef_.shape == (n_classes, n_features) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +# Remove multi_class an change first element of the expected n_iter_.shape from +# n_classes to 1 (according to the docstring). +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +def test_LogisticRegressionCV_elasticnet_attribute_shapes(): + # Make sure the shapes of scores_ and coefs_paths_ attributes are correct + # when using elasticnet (added one dimension for l1_ratios) + + n_classes = 3 + n_features = 20 + X, y = make_classification( + n_samples=200, + n_classes=n_classes, + n_informative=n_classes, + n_features=n_features, + random_state=0, + ) + + Cs = np.logspace(-4, 4, 3) + l1_ratios = np.linspace(0, 1, 2) + + n_folds = 2 + lrcv = LogisticRegressionCV( + penalty="elasticnet", + Cs=Cs, + solver="saga", + cv=n_folds, + l1_ratios=l1_ratios, + multi_class="ovr", + random_state=0, + tol=1e-2, + ) + lrcv.fit(X, y) + coefs_paths = np.asarray(list(lrcv.coefs_paths_.values())) + assert coefs_paths.shape == ( + n_classes, + n_folds, + Cs.size, + l1_ratios.size, + n_features + 1, + ) + scores = np.asarray(list(lrcv.scores_.values())) + assert scores.shape == (n_classes, n_folds, Cs.size, l1_ratios.size) + + assert lrcv.n_iter_.shape == (n_classes, n_folds, Cs.size, l1_ratios.size) + + +def test_l1_ratio_non_elasticnet(): + msg = ( + r"l1_ratio parameter is only used when penalty is" + r" 'elasticnet'\. Got \(penalty=l1\)" + ) + with pytest.warns(UserWarning, match=msg): + LogisticRegression(penalty="l1", solver="saga", l1_ratio=0.5).fit(X, Y1) + + +@pytest.mark.parametrize("C", np.logspace(-3, 2, 4)) +@pytest.mark.parametrize("l1_ratio", [0.1, 0.5, 0.9]) +def test_elastic_net_versus_sgd(C, l1_ratio): + # Compare elasticnet penalty in LogisticRegression() and SGD(loss='log') + n_samples = 500 + X, y = make_classification( + n_samples=n_samples, + n_classes=2, + n_features=5, + n_informative=5, + n_redundant=0, + n_repeated=0, + random_state=1, + ) + X = scale(X) + + sgd = SGDClassifier( + penalty="elasticnet", + random_state=1, + fit_intercept=False, + tol=None, + max_iter=2000, + l1_ratio=l1_ratio, + alpha=1.0 / C / n_samples, + loss="log_loss", + ) + log = LogisticRegression( + penalty="elasticnet", + random_state=1, + fit_intercept=False, + tol=1e-5, + max_iter=1000, + l1_ratio=l1_ratio, + C=C, + solver="saga", + ) + + sgd.fit(X, y) + log.fit(X, y) + assert_array_almost_equal(sgd.coef_, log.coef_, decimal=1) + + +def test_logistic_regression_path_coefs_multinomial(): + # Make sure that the returned coefs by logistic_regression_path when + # multi_class='multinomial' don't override each other (used to be a + # bug). + X, y = make_classification( + n_samples=200, + n_classes=3, + n_informative=2, + n_redundant=0, + n_clusters_per_class=1, + random_state=0, + n_features=2, + ) + Cs = [0.00001, 1, 10000] + coefs, _, _ = _logistic_regression_path( + X, + y, + penalty="l1", + Cs=Cs, + solver="saga", + random_state=0, + multi_class="multinomial", + ) + + with pytest.raises(AssertionError): + assert_array_almost_equal(coefs[0], coefs[1], decimal=1) + with pytest.raises(AssertionError): + assert_array_almost_equal(coefs[0], coefs[2], decimal=1) + with pytest.raises(AssertionError): + assert_array_almost_equal(coefs[1], coefs[2], decimal=1) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.filterwarnings( + "ignore:.*'liblinear' solver for multiclass classification is deprecated.*" +) +@pytest.mark.parametrize( + "est", + [ + LogisticRegression(random_state=0, max_iter=500), + LogisticRegressionCV(random_state=0, cv=3, Cs=3, tol=1e-3, max_iter=500), + ], + ids=lambda x: x.__class__.__name__, +) +@pytest.mark.parametrize("solver", SOLVERS) +def test_logistic_regression_multi_class_auto(est, solver): + # check multi_class='auto' => multi_class='ovr' + # iff binary y or liblinear + + def fit(X, y, **kw): + return clone(est).set_params(**kw).fit(X, y) + + scaled_data = scale(iris.data) + X = scaled_data[::10] + X2 = scaled_data[1::10] + y_multi = iris.target[::10] + y_bin = y_multi == 0 + est_auto_bin = fit(X, y_bin, multi_class="auto", solver=solver) + est_ovr_bin = fit(X, y_bin, multi_class="ovr", solver=solver) + assert_allclose(est_auto_bin.coef_, est_ovr_bin.coef_) + assert_allclose(est_auto_bin.predict_proba(X2), est_ovr_bin.predict_proba(X2)) + + est_auto_multi = fit(X, y_multi, multi_class="auto", solver=solver) + if solver == "liblinear": + est_ovr_multi = fit(X, y_multi, multi_class="ovr", solver=solver) + assert_allclose(est_auto_multi.coef_, est_ovr_multi.coef_) + assert_allclose( + est_auto_multi.predict_proba(X2), est_ovr_multi.predict_proba(X2) + ) + else: + est_multi_multi = fit(X, y_multi, multi_class="multinomial", solver=solver) + assert_allclose(est_auto_multi.coef_, est_multi_multi.coef_) + assert_allclose( + est_auto_multi.predict_proba(X2), est_multi_multi.predict_proba(X2) + ) + + # Make sure multi_class='ovr' is distinct from ='multinomial' + assert not np.allclose( + est_auto_bin.coef_, + fit(X, y_bin, multi_class="multinomial", solver=solver).coef_, + ) + assert not np.allclose( + est_auto_bin.coef_, + fit(X, y_multi, multi_class="multinomial", solver=solver).coef_, + ) + + +@pytest.mark.parametrize("solver", sorted(set(SOLVERS) - set(["liblinear"]))) +def test_penalty_none(solver): + # - Make sure warning is raised if penalty=None and C is set to a + # non-default value. + # - Make sure setting penalty=None is equivalent to setting C=np.inf with + # l2 penalty. + X, y = make_classification(n_samples=1000, n_redundant=0, random_state=0) + + msg = "Setting penalty=None will ignore the C" + lr = LogisticRegression(penalty=None, solver=solver, C=4) + with pytest.warns(UserWarning, match=msg): + lr.fit(X, y) + + lr_none = LogisticRegression(penalty=None, solver=solver, random_state=0) + lr_l2_C_inf = LogisticRegression( + penalty="l2", C=np.inf, solver=solver, random_state=0 + ) + pred_none = lr_none.fit(X, y).predict(X) + pred_l2_C_inf = lr_l2_C_inf.fit(X, y).predict(X) + assert_array_equal(pred_none, pred_l2_C_inf) + + +@pytest.mark.parametrize( + "params", + [ + {"penalty": "l1", "dual": False, "tol": 1e-6, "max_iter": 1000}, + {"penalty": "l2", "dual": True, "tol": 1e-12, "max_iter": 1000}, + {"penalty": "l2", "dual": False, "tol": 1e-12, "max_iter": 1000}, + ], +) +def test_logisticregression_liblinear_sample_weight(params): + # check that we support sample_weight with liblinear in all possible cases: + # l1-primal, l2-primal, l2-dual + X = np.array( + [ + [1, 3], + [1, 3], + [1, 3], + [1, 3], + [2, 1], + [2, 1], + [2, 1], + [2, 1], + [3, 3], + [3, 3], + [3, 3], + [3, 3], + [4, 1], + [4, 1], + [4, 1], + [4, 1], + ], + dtype=np.dtype("float"), + ) + y = np.array( + [1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2], dtype=np.dtype("int") + ) + + X2 = np.vstack([X, X]) + y2 = np.hstack([y, 3 - y]) + sample_weight = np.ones(shape=len(y) * 2) + sample_weight[len(y) :] = 0 + X2, y2, sample_weight = shuffle(X2, y2, sample_weight, random_state=0) + + base_clf = LogisticRegression(solver="liblinear", random_state=42) + base_clf.set_params(**params) + clf_no_weight = clone(base_clf).fit(X, y) + clf_with_weight = clone(base_clf).fit(X2, y2, sample_weight=sample_weight) + + for method in ("predict", "predict_proba", "decision_function"): + X_clf_no_weight = getattr(clf_no_weight, method)(X) + X_clf_with_weight = getattr(clf_with_weight, method)(X) + assert_allclose(X_clf_no_weight, X_clf_with_weight) + + +def test_scores_attribute_layout_elasticnet(): + # Non regression test for issue #14955. + # when penalty is elastic net the scores_ attribute has shape + # (n_classes, n_Cs, n_l1_ratios) + # We here make sure that the second dimension indeed corresponds to Cs and + # the third dimension corresponds to l1_ratios. + + X, y = make_classification(n_samples=1000, random_state=0) + cv = StratifiedKFold(n_splits=5) + + l1_ratios = [0.1, 0.9] + Cs = [0.1, 1, 10] + + lrcv = LogisticRegressionCV( + penalty="elasticnet", + solver="saga", + l1_ratios=l1_ratios, + Cs=Cs, + cv=cv, + random_state=0, + max_iter=250, + tol=1e-3, + ) + lrcv.fit(X, y) + + avg_scores_lrcv = lrcv.scores_[1].mean(axis=0) # average over folds + + for i, C in enumerate(Cs): + for j, l1_ratio in enumerate(l1_ratios): + lr = LogisticRegression( + penalty="elasticnet", + solver="saga", + C=C, + l1_ratio=l1_ratio, + random_state=0, + max_iter=250, + tol=1e-3, + ) + + avg_score_lr = cross_val_score(lr, X, y, cv=cv).mean() + assert avg_scores_lrcv[i, j] == pytest.approx(avg_score_lr) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("solver", ["lbfgs", "newton-cg", "newton-cholesky"]) +@pytest.mark.parametrize("fit_intercept", [False, True]) +def test_multinomial_identifiability_on_iris(solver, fit_intercept): + """Test that the multinomial classification is identifiable. + + A multinomial with c classes can be modeled with + probability_k = exp(X@coef_k) / sum(exp(X@coef_l), l=1..c) for k=1..c. + This is not identifiable, unless one chooses a further constraint. + According to [1], the maximum of the L2 penalized likelihood automatically + satisfies the symmetric constraint: + sum(coef_k, k=1..c) = 0 + + Further details can be found in [2]. + + Reference + --------- + .. [1] :doi:`Zhu, Ji and Trevor J. Hastie. "Classification of gene microarrays by + penalized logistic regression". Biostatistics 5 3 (2004): 427-43. + <10.1093/biostatistics/kxg046>` + + .. [2] :arxiv:`Noah Simon and Jerome Friedman and Trevor Hastie. (2013) + "A Blockwise Descent Algorithm for Group-penalized Multiresponse and + Multinomial Regression". <1311.6529>` + """ + # Test logistic regression with the iris dataset + n_samples, n_features = iris.data.shape + target = iris.target_names[iris.target] + + clf = LogisticRegression( + C=len(iris.data), + solver="lbfgs", + fit_intercept=fit_intercept, + ) + # Scaling X to ease convergence. + X_scaled = scale(iris.data) + clf.fit(X_scaled, target) + + # axis=0 is sum over classes + assert_allclose(clf.coef_.sum(axis=0), 0, atol=1e-10) + if fit_intercept: + assert clf.intercept_.sum(axis=0) == pytest.approx(0, abs=1e-11) + + +# TODO(1.8): remove filterwarnings after the deprecation of multi_class +@pytest.mark.filterwarnings("ignore:.*'multi_class' was deprecated.*:FutureWarning") +@pytest.mark.parametrize("multi_class", ["ovr", "multinomial", "auto"]) +@pytest.mark.parametrize("class_weight", [{0: 1.0, 1: 10.0, 2: 1.0}, "balanced"]) +def test_sample_weight_not_modified(multi_class, class_weight): + X, y = load_iris(return_X_y=True) + n_features = len(X) + W = np.ones(n_features) + W[: n_features // 2] = 2 + + expected = W.copy() + + clf = LogisticRegression( + random_state=0, class_weight=class_weight, max_iter=200, multi_class=multi_class + ) + clf.fit(X, y, sample_weight=W) + assert_allclose(expected, W) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_large_sparse_matrix(solver, global_random_seed, csr_container): + # Solvers either accept large sparse matrices, or raise helpful error. + # Non-regression test for pull-request #21093. + + # generate sparse matrix with int64 indices + X = csr_container(sparse.rand(20, 10, random_state=global_random_seed)) + for attr in ["indices", "indptr"]: + setattr(X, attr, getattr(X, attr).astype("int64")) + rng = np.random.RandomState(global_random_seed) + y = rng.randint(2, size=X.shape[0]) + + if solver in ["liblinear", "sag", "saga"]: + msg = "Only sparse matrices with 32-bit integer indices" + with pytest.raises(ValueError, match=msg): + LogisticRegression(solver=solver).fit(X, y) + else: + LogisticRegression(solver=solver).fit(X, y) + + +def test_single_feature_newton_cg(): + # Test that Newton-CG works with a single feature and intercept. + # Non-regression test for issue #23605. + + X = np.array([[0.5, 0.65, 1.1, 1.25, 0.8, 0.54, 0.95, 0.7]]).T + y = np.array([1, 1, 0, 0, 1, 1, 0, 1]) + assert X.shape[1] == 1 + LogisticRegression(solver="newton-cg", fit_intercept=True).fit(X, y) + + +def test_liblinear_not_stuck(): + # Non-regression https://github.com/scikit-learn/scikit-learn/issues/18264 + X = iris.data.copy() + y = iris.target.copy() + X = X[y != 2] + y = y[y != 2] + X_prep = StandardScaler().fit_transform(X) + + C = l1_min_c(X, y, loss="log") * 10 ** (10 / 29) + clf = LogisticRegression( + penalty="l1", + solver="liblinear", + tol=1e-6, + max_iter=100, + intercept_scaling=10000.0, + random_state=0, + C=C, + ) + + # test that the fit does not raise a ConvergenceWarning + with warnings.catch_warnings(): + warnings.simplefilter("error", ConvergenceWarning) + clf.fit(X_prep, y) + + +@config_context(enable_metadata_routing=True) +def test_lr_cv_scores_differ_when_sample_weight_is_requested(): + """Test that `sample_weight` is correctly passed to the scorer in + `LogisticRegressionCV.fit` and `LogisticRegressionCV.score` by + checking the difference in scores with the case when `sample_weight` + is not requested. + """ + rng = np.random.RandomState(10) + X, y = make_classification(n_samples=10, random_state=rng) + X_t, y_t = make_classification(n_samples=10, random_state=rng) + sample_weight = np.ones(len(y)) + sample_weight[: len(y) // 2] = 2 + kwargs = {"sample_weight": sample_weight} + + scorer1 = get_scorer("accuracy") + lr_cv1 = LogisticRegressionCV(scoring=scorer1) + lr_cv1.fit(X, y, **kwargs) + + scorer2 = get_scorer("accuracy") + scorer2.set_score_request(sample_weight=True) + lr_cv2 = LogisticRegressionCV(scoring=scorer2) + lr_cv2.fit(X, y, **kwargs) + + assert not np.allclose(lr_cv1.scores_[1], lr_cv2.scores_[1]) + + score_1 = lr_cv1.score(X_t, y_t, **kwargs) + score_2 = lr_cv2.score(X_t, y_t, **kwargs) + + assert not np.allclose(score_1, score_2) + + +def test_lr_cv_scores_without_enabling_metadata_routing(): + """Test that `sample_weight` is passed correctly to the scorer in + `LogisticRegressionCV.fit` and `LogisticRegressionCV.score` even + when `enable_metadata_routing=False` + """ + rng = np.random.RandomState(10) + X, y = make_classification(n_samples=10, random_state=rng) + X_t, y_t = make_classification(n_samples=10, random_state=rng) + sample_weight = np.ones(len(y)) + sample_weight[: len(y) // 2] = 2 + kwargs = {"sample_weight": sample_weight} + + with config_context(enable_metadata_routing=False): + scorer1 = get_scorer("accuracy") + lr_cv1 = LogisticRegressionCV(scoring=scorer1) + lr_cv1.fit(X, y, **kwargs) + score_1 = lr_cv1.score(X_t, y_t, **kwargs) + + with config_context(enable_metadata_routing=True): + scorer2 = get_scorer("accuracy") + scorer2.set_score_request(sample_weight=True) + lr_cv2 = LogisticRegressionCV(scoring=scorer2) + lr_cv2.fit(X, y, **kwargs) + score_2 = lr_cv2.score(X_t, y_t, **kwargs) + + assert_allclose(lr_cv1.scores_[1], lr_cv2.scores_[1]) + assert_allclose(score_1, score_2) + + +@pytest.mark.parametrize("solver", SOLVERS) +def test_zero_max_iter(solver): + # Make sure we can inspect the state of LogisticRegression right after + # initialization (before the first weight update). + X, y = load_iris(return_X_y=True) + y = y == 2 + with ignore_warnings(category=ConvergenceWarning): + clf = LogisticRegression(solver=solver, max_iter=0).fit(X, y) + if solver not in ["saga", "sag"]: + # XXX: sag and saga have n_iter_ = [1]... + assert clf.n_iter_ == 0 + + if solver != "lbfgs": + # XXX: lbfgs has already started to update the coefficients... + assert_allclose(clf.coef_, np.zeros_like(clf.coef_)) + assert_allclose( + clf.decision_function(X), + np.full(shape=X.shape[0], fill_value=clf.intercept_), + ) + assert_allclose( + clf.predict_proba(X), + np.full(shape=(X.shape[0], 2), fill_value=0.5), + ) + assert clf.score(X, y) < 0.7 + + +def test_passing_params_without_enabling_metadata_routing(): + """Test that the right error message is raised when metadata params + are passed while not supported when `enable_metadata_routing=False`.""" + X, y = make_classification(n_samples=10, random_state=0) + lr_cv = LogisticRegressionCV() + msg = "is only supported if enable_metadata_routing=True" + + with config_context(enable_metadata_routing=False): + params = {"extra_param": 1.0} + + with pytest.raises(ValueError, match=msg): + lr_cv.fit(X, y, **params) + + with pytest.raises(ValueError, match=msg): + lr_cv.score(X, y, **params) + + +# TODO(1.8): remove +def test_multi_class_deprecated(): + """Check `multi_class` parameter deprecated.""" + X, y = make_classification(n_classes=3, n_samples=50, n_informative=6) + lr = LogisticRegression(multi_class="ovr") + msg = "'multi_class' was deprecated" + with pytest.warns(FutureWarning, match=msg): + lr.fit(X, y) + + lrCV = LogisticRegressionCV(multi_class="ovr") + with pytest.warns(FutureWarning, match=msg): + lrCV.fit(X, y) + + # Special warning for "binary multinomial" + X, y = make_classification(n_classes=2, n_samples=50, n_informative=6) + lr = LogisticRegression(multi_class="multinomial") + msg = "'multi_class' was deprecated.*binary problems" + with pytest.warns(FutureWarning, match=msg): + lr.fit(X, y) + + lrCV = LogisticRegressionCV(multi_class="multinomial") + with pytest.warns(FutureWarning, match=msg): + lrCV.fit(X, y) + + +def test_newton_cholesky_fallback_to_lbfgs(global_random_seed): + # Wide data matrix should lead to a rank-deficient Hessian matrix + # hence make the Newton-Cholesky solver raise a warning and fallback to + # lbfgs. + X, y = make_classification( + n_samples=10, n_features=20, random_state=global_random_seed + ) + C = 1e30 # very high C to nearly disable regularization + + # Check that LBFGS can converge without any warning on this problem. + lr_lbfgs = LogisticRegression(solver="lbfgs", C=C) + with warnings.catch_warnings(): + warnings.simplefilter("error") + lr_lbfgs.fit(X, y) + n_iter_lbfgs = lr_lbfgs.n_iter_[0] + + assert n_iter_lbfgs >= 1 + + # Check that the Newton-Cholesky solver raises a warning and falls back to + # LBFGS. This should converge with the same number of iterations as the + # above call of lbfgs since the Newton-Cholesky triggers the fallback + # before completing the first iteration, for the problem setting at hand. + lr_nc = LogisticRegression(solver="newton-cholesky", C=C) + with ignore_warnings(category=LinAlgWarning): + lr_nc.fit(X, y) + n_iter_nc = lr_nc.n_iter_[0] + + assert n_iter_nc == n_iter_lbfgs + + # Trying to fit the same model again with a small iteration budget should + # therefore raise a ConvergenceWarning: + lr_nc_limited = LogisticRegression( + solver="newton-cholesky", C=C, max_iter=n_iter_lbfgs - 1 + ) + with ignore_warnings(category=LinAlgWarning): + with pytest.warns(ConvergenceWarning, match="lbfgs failed to converge"): + lr_nc_limited.fit(X, y) + n_iter_nc_limited = lr_nc_limited.n_iter_[0] + + assert n_iter_nc_limited == lr_nc_limited.max_iter - 1 + + +# TODO(1.8): check for an error instead +@pytest.mark.parametrize("Estimator", [LogisticRegression, LogisticRegressionCV]) +def test_liblinear_multiclass_warning(Estimator): + """Check that liblinear warns on multiclass problems.""" + msg = ( + "Using the 'liblinear' solver for multiclass classification is " + "deprecated. An error will be raised in 1.8. Either use another " + "solver which supports the multinomial loss or wrap the estimator " + "in a OneVsRestClassifier to keep applying a one-versus-rest " + "scheme." + ) + with pytest.warns(FutureWarning, match=msg): + Estimator(solver="liblinear").fit(iris.data, iris.target) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_omp.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_omp.py new file mode 100644 index 0000000000000000000000000000000000000000..cfdffe581e034ac33378bbd36e4dc64025fbcfcd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_omp.py @@ -0,0 +1,273 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + + +import numpy as np +import pytest + +from sklearn.datasets import make_sparse_coded_signal +from sklearn.linear_model import ( + LinearRegression, + OrthogonalMatchingPursuit, + OrthogonalMatchingPursuitCV, + orthogonal_mp, + orthogonal_mp_gram, +) +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + assert_allclose, + assert_array_almost_equal, + assert_array_equal, + ignore_warnings, +) + +n_samples, n_features, n_nonzero_coefs, n_targets = 25, 35, 5, 3 +y, X, gamma = make_sparse_coded_signal( + n_samples=n_targets, + n_components=n_features, + n_features=n_samples, + n_nonzero_coefs=n_nonzero_coefs, + random_state=0, +) +y, X, gamma = y.T, X.T, gamma.T +# Make X not of norm 1 for testing +X *= 10 +y *= 10 +G, Xy = np.dot(X.T, X), np.dot(X.T, y) +# this makes X (n_samples, n_features) +# and y (n_samples, 3) + + +def test_correct_shapes(): + assert orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5).shape == (n_features,) + assert orthogonal_mp(X, y, n_nonzero_coefs=5).shape == (n_features, 3) + + +def test_correct_shapes_gram(): + assert orthogonal_mp_gram(G, Xy[:, 0], n_nonzero_coefs=5).shape == (n_features,) + assert orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5).shape == (n_features, 3) + + +def test_n_nonzero_coefs(): + assert np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5)) <= 5 + assert ( + np.count_nonzero(orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5, precompute=True)) + <= 5 + ) + + +def test_tol(): + tol = 0.5 + gamma = orthogonal_mp(X, y[:, 0], tol=tol) + gamma_gram = orthogonal_mp(X, y[:, 0], tol=tol, precompute=True) + assert np.sum((y[:, 0] - np.dot(X, gamma)) ** 2) <= tol + assert np.sum((y[:, 0] - np.dot(X, gamma_gram)) ** 2) <= tol + + +def test_with_without_gram(): + assert_array_almost_equal( + orthogonal_mp(X, y, n_nonzero_coefs=5), + orthogonal_mp(X, y, n_nonzero_coefs=5, precompute=True), + ) + + +def test_with_without_gram_tol(): + assert_array_almost_equal( + orthogonal_mp(X, y, tol=1.0), orthogonal_mp(X, y, tol=1.0, precompute=True) + ) + + +def test_unreachable_accuracy(): + assert_array_almost_equal( + orthogonal_mp(X, y, tol=0), orthogonal_mp(X, y, n_nonzero_coefs=n_features) + ) + warning_message = ( + "Orthogonal matching pursuit ended prematurely " + "due to linear dependence in the dictionary. " + "The requested precision might not have been met." + ) + with pytest.warns(RuntimeWarning, match=warning_message): + assert_array_almost_equal( + orthogonal_mp(X, y, tol=0, precompute=True), + orthogonal_mp(X, y, precompute=True, n_nonzero_coefs=n_features), + ) + + +@pytest.mark.parametrize("positional_params", [(X, y), (G, Xy)]) +@pytest.mark.parametrize( + "keyword_params", + [{"n_nonzero_coefs": n_features + 1}], +) +def test_bad_input(positional_params, keyword_params): + with pytest.raises(ValueError): + orthogonal_mp(*positional_params, **keyword_params) + + +def test_perfect_signal_recovery(): + (idx,) = gamma[:, 0].nonzero() + gamma_rec = orthogonal_mp(X, y[:, 0], n_nonzero_coefs=5) + gamma_gram = orthogonal_mp_gram(G, Xy[:, 0], n_nonzero_coefs=5) + assert_array_equal(idx, np.flatnonzero(gamma_rec)) + assert_array_equal(idx, np.flatnonzero(gamma_gram)) + assert_array_almost_equal(gamma[:, 0], gamma_rec, decimal=2) + assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2) + + +def test_orthogonal_mp_gram_readonly(): + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/5956 + (idx,) = gamma[:, 0].nonzero() + G_readonly = G.copy() + G_readonly.setflags(write=False) + Xy_readonly = Xy.copy() + Xy_readonly.setflags(write=False) + gamma_gram = orthogonal_mp_gram( + G_readonly, Xy_readonly[:, 0], n_nonzero_coefs=5, copy_Gram=False, copy_Xy=False + ) + assert_array_equal(idx, np.flatnonzero(gamma_gram)) + assert_array_almost_equal(gamma[:, 0], gamma_gram, decimal=2) + + +def test_estimator(): + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs) + omp.fit(X, y[:, 0]) + assert omp.coef_.shape == (n_features,) + assert omp.intercept_.shape == () + assert np.count_nonzero(omp.coef_) <= n_nonzero_coefs + + omp.fit(X, y) + assert omp.coef_.shape == (n_targets, n_features) + assert omp.intercept_.shape == (n_targets,) + assert np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs + + coef_normalized = omp.coef_[0].copy() + omp.set_params(fit_intercept=True) + omp.fit(X, y[:, 0]) + assert_array_almost_equal(coef_normalized, omp.coef_) + + omp.set_params(fit_intercept=False) + omp.fit(X, y[:, 0]) + assert np.count_nonzero(omp.coef_) <= n_nonzero_coefs + assert omp.coef_.shape == (n_features,) + assert omp.intercept_ == 0 + + omp.fit(X, y) + assert omp.coef_.shape == (n_targets, n_features) + assert omp.intercept_ == 0 + assert np.count_nonzero(omp.coef_) <= n_targets * n_nonzero_coefs + + +def test_estimator_n_nonzero_coefs(): + """Check `n_nonzero_coefs_` correct when `tol` is and isn't set.""" + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs) + omp.fit(X, y[:, 0]) + assert omp.n_nonzero_coefs_ == n_nonzero_coefs + + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_nonzero_coefs, tol=0.5) + omp.fit(X, y[:, 0]) + assert omp.n_nonzero_coefs_ is None + + +def test_identical_regressors(): + newX = X.copy() + newX[:, 1] = newX[:, 0] + gamma = np.zeros(n_features) + gamma[0] = gamma[1] = 1.0 + newy = np.dot(newX, gamma) + warning_message = ( + "Orthogonal matching pursuit ended prematurely " + "due to linear dependence in the dictionary. " + "The requested precision might not have been met." + ) + with pytest.warns(RuntimeWarning, match=warning_message): + orthogonal_mp(newX, newy, n_nonzero_coefs=2) + + +def test_swapped_regressors(): + gamma = np.zeros(n_features) + # X[:, 21] should be selected first, then X[:, 0] selected second, + # which will take X[:, 21]'s place in case the algorithm does + # column swapping for optimization (which is the case at the moment) + gamma[21] = 1.0 + gamma[0] = 0.5 + new_y = np.dot(X, gamma) + new_Xy = np.dot(X.T, new_y) + gamma_hat = orthogonal_mp(X, new_y, n_nonzero_coefs=2) + gamma_hat_gram = orthogonal_mp_gram(G, new_Xy, n_nonzero_coefs=2) + assert_array_equal(np.flatnonzero(gamma_hat), [0, 21]) + assert_array_equal(np.flatnonzero(gamma_hat_gram), [0, 21]) + + +def test_no_atoms(): + y_empty = np.zeros_like(y) + Xy_empty = np.dot(X.T, y_empty) + gamma_empty = ignore_warnings(orthogonal_mp)(X, y_empty, n_nonzero_coefs=1) + gamma_empty_gram = ignore_warnings(orthogonal_mp)(G, Xy_empty, n_nonzero_coefs=1) + assert np.all(gamma_empty == 0) + assert np.all(gamma_empty_gram == 0) + + +def test_omp_path(): + path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True) + last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False) + assert path.shape == (n_features, n_targets, 5) + assert_array_almost_equal(path[:, :, -1], last) + path = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=True) + last = orthogonal_mp_gram(G, Xy, n_nonzero_coefs=5, return_path=False) + assert path.shape == (n_features, n_targets, 5) + assert_array_almost_equal(path[:, :, -1], last) + + +def test_omp_return_path_prop_with_gram(): + path = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=True, precompute=True) + last = orthogonal_mp(X, y, n_nonzero_coefs=5, return_path=False, precompute=True) + assert path.shape == (n_features, n_targets, 5) + assert_array_almost_equal(path[:, :, -1], last) + + +def test_omp_cv(): + y_ = y[:, 0] + gamma_ = gamma[:, 0] + ompcv = OrthogonalMatchingPursuitCV(fit_intercept=False, max_iter=10) + ompcv.fit(X, y_) + assert ompcv.n_nonzero_coefs_ == n_nonzero_coefs + assert_array_almost_equal(ompcv.coef_, gamma_) + omp = OrthogonalMatchingPursuit( + fit_intercept=False, n_nonzero_coefs=ompcv.n_nonzero_coefs_ + ) + omp.fit(X, y_) + assert_array_almost_equal(ompcv.coef_, omp.coef_) + + +def test_omp_reaches_least_squares(): + # Use small simple data; it's a sanity check but OMP can stop early + rng = check_random_state(0) + n_samples, n_features = (10, 8) + n_targets = 3 + X = rng.randn(n_samples, n_features) + Y = rng.randn(n_samples, n_targets) + omp = OrthogonalMatchingPursuit(n_nonzero_coefs=n_features) + lstsq = LinearRegression() + omp.fit(X, Y) + lstsq.fit(X, Y) + assert_array_almost_equal(omp.coef_, lstsq.coef_) + + +@pytest.mark.parametrize("data_type", (np.float32, np.float64)) +def test_omp_gram_dtype_match(data_type): + # verify matching input data type and output data type + coef = orthogonal_mp_gram( + G.astype(data_type), Xy.astype(data_type), n_nonzero_coefs=5 + ) + assert coef.dtype == data_type + + +def test_omp_gram_numerical_consistency(): + # verify numericaly consistency among np.float32 and np.float64 + coef_32 = orthogonal_mp_gram( + G.astype(np.float32), Xy.astype(np.float32), n_nonzero_coefs=5 + ) + coef_64 = orthogonal_mp_gram( + G.astype(np.float32), Xy.astype(np.float64), n_nonzero_coefs=5 + ) + assert_allclose(coef_32, coef_64) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_passive_aggressive.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_passive_aggressive.py new file mode 100644 index 0000000000000000000000000000000000000000..bcfd58b1eab2b51ecd8cc1097bd48577e2babe0d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_passive_aggressive.py @@ -0,0 +1,268 @@ +import numpy as np +import pytest + +from sklearn.base import ClassifierMixin +from sklearn.datasets import load_iris +from sklearn.linear_model import PassiveAggressiveClassifier, PassiveAggressiveRegressor +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + +iris = load_iris() +random_state = check_random_state(12) +indices = np.arange(iris.data.shape[0]) +random_state.shuffle(indices) +X = iris.data[indices] +y = iris.target[indices] + + +class MyPassiveAggressive(ClassifierMixin): + def __init__( + self, + C=1.0, + epsilon=0.01, + loss="hinge", + fit_intercept=True, + n_iter=1, + random_state=None, + ): + self.C = C + self.epsilon = epsilon + self.loss = loss + self.fit_intercept = fit_intercept + self.n_iter = n_iter + + def fit(self, X, y): + n_samples, n_features = X.shape + self.w = np.zeros(n_features, dtype=np.float64) + self.b = 0.0 + + for t in range(self.n_iter): + for i in range(n_samples): + p = self.project(X[i]) + if self.loss in ("hinge", "squared_hinge"): + loss = max(1 - y[i] * p, 0) + else: + loss = max(np.abs(p - y[i]) - self.epsilon, 0) + + sqnorm = np.dot(X[i], X[i]) + + if self.loss in ("hinge", "epsilon_insensitive"): + step = min(self.C, loss / sqnorm) + elif self.loss in ("squared_hinge", "squared_epsilon_insensitive"): + step = loss / (sqnorm + 1.0 / (2 * self.C)) + + if self.loss in ("hinge", "squared_hinge"): + step *= y[i] + else: + step *= np.sign(y[i] - p) + + self.w += step * X[i] + if self.fit_intercept: + self.b += step + + def project(self, X): + return np.dot(X, self.w) + self.b + + +@pytest.mark.parametrize("average", [False, True]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +def test_classifier_accuracy(csr_container, fit_intercept, average): + data = csr_container(X) if csr_container is not None else X + clf = PassiveAggressiveClassifier( + C=1.0, + max_iter=30, + fit_intercept=fit_intercept, + random_state=1, + average=average, + tol=None, + ) + clf.fit(data, y) + score = clf.score(data, y) + assert score > 0.79 + if average: + assert hasattr(clf, "_average_coef") + assert hasattr(clf, "_average_intercept") + assert hasattr(clf, "_standard_intercept") + assert hasattr(clf, "_standard_coef") + + +@pytest.mark.parametrize("average", [False, True]) +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +def test_classifier_partial_fit(csr_container, average): + classes = np.unique(y) + data = csr_container(X) if csr_container is not None else X + clf = PassiveAggressiveClassifier(random_state=0, average=average, max_iter=5) + for t in range(30): + clf.partial_fit(data, y, classes) + score = clf.score(data, y) + assert score > 0.79 + if average: + assert hasattr(clf, "_average_coef") + assert hasattr(clf, "_average_intercept") + assert hasattr(clf, "_standard_intercept") + assert hasattr(clf, "_standard_coef") + + +def test_classifier_refit(): + # Classifier can be retrained on different labels and features. + clf = PassiveAggressiveClassifier(max_iter=5).fit(X, y) + assert_array_equal(clf.classes_, np.unique(y)) + + clf.fit(X[:, :-1], iris.target_names[y]) + assert_array_equal(clf.classes_, iris.target_names) + + +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +@pytest.mark.parametrize("loss", ("hinge", "squared_hinge")) +def test_classifier_correctness(loss, csr_container): + y_bin = y.copy() + y_bin[y != 1] = -1 + + clf1 = MyPassiveAggressive(loss=loss, n_iter=2) + clf1.fit(X, y_bin) + + data = csr_container(X) if csr_container is not None else X + clf2 = PassiveAggressiveClassifier(loss=loss, max_iter=2, shuffle=False, tol=None) + clf2.fit(data, y_bin) + + assert_array_almost_equal(clf1.w, clf2.coef_.ravel(), decimal=2) + + +@pytest.mark.parametrize( + "response_method", ["predict_proba", "predict_log_proba", "transform"] +) +def test_classifier_undefined_methods(response_method): + clf = PassiveAggressiveClassifier(max_iter=100) + with pytest.raises(AttributeError): + getattr(clf, response_method) + + +def test_class_weights(): + # Test class weights. + X2 = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) + y2 = [1, 1, 1, -1, -1] + + clf = PassiveAggressiveClassifier( + C=0.1, max_iter=100, class_weight=None, random_state=100 + ) + clf.fit(X2, y2) + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1])) + + # we give a small weights to class 1 + clf = PassiveAggressiveClassifier( + C=0.1, max_iter=100, class_weight={1: 0.001}, random_state=100 + ) + clf.fit(X2, y2) + + # now the hyperplane should rotate clock-wise and + # the prediction on this point should shift + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) + + +def test_partial_fit_weight_class_balanced(): + # partial_fit with class_weight='balanced' not supported + clf = PassiveAggressiveClassifier(class_weight="balanced", max_iter=100) + with pytest.raises(ValueError): + clf.partial_fit(X, y, classes=np.unique(y)) + + +def test_equal_class_weight(): + X2 = [[1, 0], [1, 0], [0, 1], [0, 1]] + y2 = [0, 0, 1, 1] + clf = PassiveAggressiveClassifier(C=0.1, tol=None, class_weight=None) + clf.fit(X2, y2) + + # Already balanced, so "balanced" weights should have no effect + clf_balanced = PassiveAggressiveClassifier(C=0.1, tol=None, class_weight="balanced") + clf_balanced.fit(X2, y2) + + clf_weighted = PassiveAggressiveClassifier( + C=0.1, tol=None, class_weight={0: 0.5, 1: 0.5} + ) + clf_weighted.fit(X2, y2) + + # should be similar up to some epsilon due to learning rate schedule + assert_almost_equal(clf.coef_, clf_weighted.coef_, decimal=2) + assert_almost_equal(clf.coef_, clf_balanced.coef_, decimal=2) + + +def test_wrong_class_weight_label(): + # ValueError due to wrong class_weight label. + X2 = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) + y2 = [1, 1, 1, -1, -1] + + clf = PassiveAggressiveClassifier(class_weight={0: 0.5}, max_iter=100) + with pytest.raises(ValueError): + clf.fit(X2, y2) + + +@pytest.mark.parametrize("average", [False, True]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +def test_regressor_mse(csr_container, fit_intercept, average): + y_bin = y.copy() + y_bin[y != 1] = -1 + + data = csr_container(X) if csr_container is not None else X + reg = PassiveAggressiveRegressor( + C=1.0, + fit_intercept=fit_intercept, + random_state=0, + average=average, + max_iter=5, + ) + reg.fit(data, y_bin) + pred = reg.predict(data) + assert np.mean((pred - y_bin) ** 2) < 1.7 + if average: + assert hasattr(reg, "_average_coef") + assert hasattr(reg, "_average_intercept") + assert hasattr(reg, "_standard_intercept") + assert hasattr(reg, "_standard_coef") + + +@pytest.mark.parametrize("average", [False, True]) +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +def test_regressor_partial_fit(csr_container, average): + y_bin = y.copy() + y_bin[y != 1] = -1 + + data = csr_container(X) if csr_container is not None else X + reg = PassiveAggressiveRegressor(random_state=0, average=average, max_iter=100) + for t in range(50): + reg.partial_fit(data, y_bin) + pred = reg.predict(data) + assert np.mean((pred - y_bin) ** 2) < 1.7 + if average: + assert hasattr(reg, "_average_coef") + assert hasattr(reg, "_average_intercept") + assert hasattr(reg, "_standard_intercept") + assert hasattr(reg, "_standard_coef") + + +@pytest.mark.parametrize("csr_container", [None, *CSR_CONTAINERS]) +@pytest.mark.parametrize("loss", ("epsilon_insensitive", "squared_epsilon_insensitive")) +def test_regressor_correctness(loss, csr_container): + y_bin = y.copy() + y_bin[y != 1] = -1 + + reg1 = MyPassiveAggressive(loss=loss, n_iter=2) + reg1.fit(X, y_bin) + + data = csr_container(X) if csr_container is not None else X + reg2 = PassiveAggressiveRegressor(tol=None, loss=loss, max_iter=2, shuffle=False) + reg2.fit(data, y_bin) + + assert_array_almost_equal(reg1.w, reg2.coef_.ravel(), decimal=2) + + +def test_regressor_undefined_methods(): + reg = PassiveAggressiveRegressor(max_iter=100) + with pytest.raises(AttributeError): + reg.transform(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_perceptron.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_perceptron.py new file mode 100644 index 0000000000000000000000000000000000000000..71456ae72132ccebc76da96aea9213fd55f47c9d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_perceptron.py @@ -0,0 +1,88 @@ +import numpy as np +import pytest + +from sklearn.datasets import load_iris +from sklearn.linear_model import Perceptron +from sklearn.utils import check_random_state +from sklearn.utils._testing import assert_allclose, assert_array_almost_equal +from sklearn.utils.fixes import CSR_CONTAINERS + +iris = load_iris() +random_state = check_random_state(12) +indices = np.arange(iris.data.shape[0]) +random_state.shuffle(indices) +X = iris.data[indices] +y = iris.target[indices] + + +class MyPerceptron: + def __init__(self, n_iter=1): + self.n_iter = n_iter + + def fit(self, X, y): + n_samples, n_features = X.shape + self.w = np.zeros(n_features, dtype=np.float64) + self.b = 0.0 + + for t in range(self.n_iter): + for i in range(n_samples): + if self.predict(X[i])[0] != y[i]: + self.w += y[i] * X[i] + self.b += y[i] + + def project(self, X): + return np.dot(X, self.w) + self.b + + def predict(self, X): + X = np.atleast_2d(X) + return np.sign(self.project(X)) + + +@pytest.mark.parametrize("container", CSR_CONTAINERS + [np.array]) +def test_perceptron_accuracy(container): + data = container(X) + clf = Perceptron(max_iter=100, tol=None, shuffle=False) + clf.fit(data, y) + score = clf.score(data, y) + assert score > 0.7 + + +def test_perceptron_correctness(): + y_bin = y.copy() + y_bin[y != 1] = -1 + + clf1 = MyPerceptron(n_iter=2) + clf1.fit(X, y_bin) + + clf2 = Perceptron(max_iter=2, shuffle=False, tol=None) + clf2.fit(X, y_bin) + + assert_array_almost_equal(clf1.w, clf2.coef_.ravel()) + + +def test_undefined_methods(): + clf = Perceptron(max_iter=100) + for meth in ("predict_proba", "predict_log_proba"): + with pytest.raises(AttributeError): + getattr(clf, meth) + + +def test_perceptron_l1_ratio(): + """Check that `l1_ratio` has an impact when `penalty='elasticnet'`""" + clf1 = Perceptron(l1_ratio=0, penalty="elasticnet") + clf1.fit(X, y) + + clf2 = Perceptron(l1_ratio=0.15, penalty="elasticnet") + clf2.fit(X, y) + + assert clf1.score(X, y) != clf2.score(X, y) + + # check that the bounds of elastic net which should correspond to an l1 or + # l2 penalty depending of `l1_ratio` value. + clf_l1 = Perceptron(penalty="l1").fit(X, y) + clf_elasticnet = Perceptron(l1_ratio=1, penalty="elasticnet").fit(X, y) + assert_allclose(clf_l1.coef_, clf_elasticnet.coef_) + + clf_l2 = Perceptron(penalty="l2").fit(X, y) + clf_elasticnet = Perceptron(l1_ratio=0, penalty="elasticnet").fit(X, y) + assert_allclose(clf_l2.coef_, clf_elasticnet.coef_) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_quantile.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_quantile.py new file mode 100644 index 0000000000000000000000000000000000000000..1d166b14091ccc11e148184056a6d4a58a48a664 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_quantile.py @@ -0,0 +1,283 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +import pytest +from pytest import approx +from scipy.optimize import minimize + +from sklearn.datasets import make_regression +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import HuberRegressor, QuantileRegressor +from sklearn.metrics import mean_pinball_loss +from sklearn.utils._testing import assert_allclose +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + parse_version, + sp_version, +) + + +@pytest.fixture +def X_y_data(): + X, y = make_regression(n_samples=10, n_features=1, random_state=0, noise=1) + return X, y + + +@pytest.mark.skipif( + parse_version(sp_version.base_version) >= parse_version("1.11"), + reason="interior-point solver is not available in SciPy 1.11", +) +@pytest.mark.parametrize("solver", ["interior-point", "revised simplex"]) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_incompatible_solver_for_sparse_input(X_y_data, solver, csc_container): + X, y = X_y_data + X_sparse = csc_container(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( + "quantile, alpha, intercept, coef", + [ + # for 50% quantile w/o regularization, any slope in [1, 10] is okay + [0.5, 0, 1, None], + # if positive error costs more, the slope is maximal + [0.51, 0, 1, 10], + # if negative error costs more, the slope is minimal + [0.49, 0, 1, 1], + # for a small lasso penalty, the slope is also minimal + [0.5, 0.01, 1, 1], + # for a large lasso penalty, the model predicts the constant median + [0.5, 100, 2, 0], + ], +) +def test_quantile_toy_example(quantile, alpha, intercept, coef): + # test how different parameters affect a small intuitive example + X = [[0], [1], [1]] + y = [1, 2, 11] + model = QuantileRegressor(quantile=quantile, alpha=alpha).fit(X, y) + assert_allclose(model.intercept_, intercept, atol=1e-2) + if coef is not None: + assert_allclose(model.coef_[0], coef, atol=1e-2) + if alpha < 100: + assert model.coef_[0] >= 1 + assert model.coef_[0] <= 10 + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_quantile_equals_huber_for_low_epsilon(fit_intercept): + X, y = make_regression(n_samples=100, n_features=20, random_state=0, noise=1.0) + alpha = 1e-4 + huber = HuberRegressor( + epsilon=1 + 1e-4, alpha=alpha, fit_intercept=fit_intercept + ).fit(X, y) + quant = QuantileRegressor(alpha=alpha, fit_intercept=fit_intercept).fit(X, y) + assert_allclose(huber.coef_, quant.coef_, atol=1e-1) + if fit_intercept: + assert huber.intercept_ == approx(quant.intercept_, abs=1e-1) + # check that we still predict fraction + assert np.mean(y < quant.predict(X)) == approx(0.5, abs=1e-1) + + +@pytest.mark.parametrize("q", [0.5, 0.9, 0.05]) +def test_quantile_estimates_calibration(q): + # Test that model estimates percentage of points below the prediction + X, y = make_regression(n_samples=1000, n_features=20, random_state=0, noise=1.0) + quant = QuantileRegressor(quantile=q, alpha=0).fit(X, y) + assert np.mean(y < quant.predict(X)) == approx(q, abs=1e-2) + + +def test_quantile_sample_weight(): + # test that with unequal sample weights we still estimate weighted fraction + n = 1000 + X, y = make_regression(n_samples=n, n_features=5, random_state=0, noise=10.0) + weight = np.ones(n) + # when we increase weight of upper observations, + # estimate of quantile should go up + weight[y > y.mean()] = 100 + quant = QuantileRegressor(quantile=0.5, alpha=1e-8) + quant.fit(X, y, sample_weight=weight) + fraction_below = np.mean(y < quant.predict(X)) + assert fraction_below > 0.5 + weighted_fraction_below = np.average(y < quant.predict(X), weights=weight) + assert weighted_fraction_below == approx(0.5, abs=3e-2) + + +@pytest.mark.parametrize("quantile", [0.2, 0.5, 0.8]) +def test_asymmetric_error(quantile): + """Test quantile regression for asymmetric distributed targets.""" + n_samples = 1000 + rng = np.random.RandomState(42) + X = np.concatenate( + ( + np.abs(rng.randn(n_samples)[:, None]), + -rng.randint(2, size=(n_samples, 1)), + ), + axis=1, + ) + intercept = 1.23 + coef = np.array([0.5, -2]) + # Take care that X @ coef + intercept > 0 + assert np.min(X @ coef + intercept) > 0 + # For an exponential distribution with rate lambda, e.g. exp(-lambda * x), + # the quantile at level q is: + # quantile(q) = - log(1 - q) / lambda + # scale = 1/lambda = -quantile(q) / log(1 - q) + y = rng.exponential( + scale=-(X @ coef + intercept) / np.log(1 - quantile), size=n_samples + ) + model = QuantileRegressor( + quantile=quantile, + alpha=0, + ).fit(X, y) + # This test can be made to pass with any solver but in the interest + # of sparing continuous integration resources, the test is performed + # with the fastest solver only. + + assert model.intercept_ == approx(intercept, rel=0.2) + assert_allclose(model.coef_, coef, rtol=0.6) + assert_allclose(np.mean(model.predict(X) > y), quantile, atol=1e-2) + + # Now compare to Nelder-Mead optimization with L1 penalty + alpha = 0.01 + model.set_params(alpha=alpha).fit(X, y) + model_coef = np.r_[model.intercept_, model.coef_] + + def func(coef): + loss = mean_pinball_loss(y, X @ coef[1:] + coef[0], alpha=quantile) + L1 = np.sum(np.abs(coef[1:])) + return loss + alpha * L1 + + res = minimize( + fun=func, + x0=[1, 0, -1], + method="Nelder-Mead", + tol=1e-12, + options={"maxiter": 2000}, + ) + + assert func(model_coef) == approx(func(res.x)) + assert_allclose(model.intercept_, res.x[0]) + assert_allclose(model.coef_, res.x[1:]) + assert_allclose(np.mean(model.predict(X) > y), quantile, atol=1e-2) + + +@pytest.mark.parametrize("quantile", [0.2, 0.5, 0.8]) +def test_equivariance(quantile): + """Test equivariace of quantile regression. + + See Koenker (2005) Quantile Regression, Chapter 2.2.3. + """ + rng = np.random.RandomState(42) + n_samples, n_features = 100, 5 + X, y = make_regression( + n_samples=n_samples, + n_features=n_features, + n_informative=n_features, + noise=0, + random_state=rng, + shuffle=False, + ) + # make y asymmetric + y += rng.exponential(scale=100, size=y.shape) + params = dict(alpha=0) + model1 = QuantileRegressor(quantile=quantile, **params).fit(X, y) + + # coef(q; a*y, X) = a * coef(q; y, X) + a = 2.5 + model2 = QuantileRegressor(quantile=quantile, **params).fit(X, a * y) + assert model2.intercept_ == approx(a * model1.intercept_, rel=1e-5) + assert_allclose(model2.coef_, a * model1.coef_, rtol=1e-5) + + # coef(1-q; -a*y, X) = -a * coef(q; y, X) + model2 = QuantileRegressor(quantile=1 - quantile, **params).fit(X, -a * y) + assert model2.intercept_ == approx(-a * model1.intercept_, rel=1e-5) + assert_allclose(model2.coef_, -a * model1.coef_, rtol=1e-5) + + # coef(q; y + X @ g, X) = coef(q; y, X) + g + g_intercept, g_coef = rng.randn(), rng.randn(n_features) + model2 = QuantileRegressor(quantile=quantile, **params) + model2.fit(X, y + X @ g_coef + g_intercept) + assert model2.intercept_ == approx(model1.intercept_ + g_intercept) + assert_allclose(model2.coef_, model1.coef_ + g_coef, rtol=1e-6) + + # coef(q; y, X @ A) = A^-1 @ coef(q; y, X) + A = rng.randn(n_features, n_features) + model2 = QuantileRegressor(quantile=quantile, **params) + model2.fit(X @ A, y) + assert model2.intercept_ == approx(model1.intercept_, rel=1e-5) + assert_allclose(model2.coef_, np.linalg.solve(A, model1.coef_), rtol=1e-5) + + +@pytest.mark.skipif( + parse_version(sp_version.base_version) >= parse_version("1.11"), + reason="interior-point solver is not available in SciPy 1.11", +) +@pytest.mark.filterwarnings("ignore:`method='interior-point'` is deprecated") +def test_linprog_failure(): + """Test that linprog fails.""" + X = np.linspace(0, 10, num=10).reshape(-1, 1) + y = np.linspace(0, 10, num=10) + reg = QuantileRegressor( + alpha=0, solver="interior-point", solver_options={"maxiter": 1} + ) + + msg = "Linear programming for QuantileRegressor did not succeed." + with pytest.warns(ConvergenceWarning, match=msg): + reg.fit(X, y) + + +@pytest.mark.parametrize( + "sparse_container", CSC_CONTAINERS + CSR_CONTAINERS + COO_CONTAINERS +) +@pytest.mark.parametrize("solver", ["highs", "highs-ds", "highs-ipm"]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_sparse_input(sparse_container, solver, fit_intercept, global_random_seed): + """Test that sparse and dense X give same results.""" + n_informative = 10 + quantile_level = 0.6 + X, y = make_regression( + n_samples=300, + n_features=20, + n_informative=10, + random_state=global_random_seed, + noise=1.0, + ) + X_sparse = sparse_container(X) + alpha = 0.1 + quant_dense = QuantileRegressor( + quantile=quantile_level, alpha=alpha, fit_intercept=fit_intercept + ).fit(X, y) + quant_sparse = QuantileRegressor( + quantile=quantile_level, alpha=alpha, fit_intercept=fit_intercept, solver=solver + ).fit(X_sparse, y) + assert_allclose(quant_sparse.coef_, quant_dense.coef_, rtol=1e-2) + sparse_support = quant_sparse.coef_ != 0 + dense_support = quant_dense.coef_ != 0 + assert dense_support.sum() == pytest.approx(n_informative, abs=1) + assert sparse_support.sum() == pytest.approx(n_informative, abs=1) + if fit_intercept: + assert quant_sparse.intercept_ == approx(quant_dense.intercept_) + # check that we still predict fraction + empirical_coverage = np.mean(y < quant_sparse.predict(X_sparse)) + assert empirical_coverage == approx(quantile_level, abs=3e-2) + + +def test_error_interior_point_future(X_y_data, monkeypatch): + """Check that we will raise a proper error when requesting + `solver='interior-point'` in SciPy >= 1.11. + """ + X, y = X_y_data + import sklearn.linear_model._quantile + + with monkeypatch.context() as m: + m.setattr(sklearn.linear_model._quantile, "sp_version", parse_version("1.11.0")) + err_msg = "Solver interior-point is not anymore available in SciPy >= 1.11.0." + with pytest.raises(ValueError, match=err_msg): + QuantileRegressor(solver="interior-point").fit(X, y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ransac.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ransac.py new file mode 100644 index 0000000000000000000000000000000000000000..7b2bc66160ef3f5e686da7c546cf01314035ae57 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ransac.py @@ -0,0 +1,545 @@ +import numpy as np +import pytest +from numpy.testing import assert_array_almost_equal, assert_array_equal + +from sklearn.datasets import make_regression +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ( + LinearRegression, + OrthogonalMatchingPursuit, + RANSACRegressor, + Ridge, +) +from sklearn.linear_model._ransac import _dynamic_max_trials +from sklearn.utils import check_random_state +from sklearn.utils._testing import assert_allclose +from sklearn.utils.fixes import COO_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS + +# Generate coordinates of line +X = np.arange(-200, 200) +y = 0.2 * X + 20 +data = np.column_stack([X, y]) + +# Add some faulty data +rng = np.random.RandomState(1000) +outliers = np.unique(rng.randint(len(X), size=200)) +data[outliers, :] += 50 + rng.rand(len(outliers), 2) * 10 + +X = data[:, 0][:, np.newaxis] +y = data[:, 1] + + +def test_ransac_inliers_outliers(): + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, y) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_array_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_is_data_valid(): + def is_data_valid(X, y): + assert X.shape[0] == 2 + assert y.shape[0] == 2 + return False + + rng = np.random.RandomState(0) + X = rng.rand(10, 2) + y = rng.rand(10, 1) + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + is_data_valid=is_data_valid, + random_state=0, + ) + with pytest.raises(ValueError): + ransac_estimator.fit(X, y) + + +def test_ransac_is_model_valid(): + def is_model_valid(estimator, X, y): + assert X.shape[0] == 2 + assert y.shape[0] == 2 + return False + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + is_model_valid=is_model_valid, + random_state=0, + ) + with pytest.raises(ValueError): + ransac_estimator.fit(X, y) + + +def test_ransac_max_trials(): + estimator = LinearRegression() + + ransac_estimator = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + max_trials=0, + random_state=0, + ) + with pytest.raises(ValueError): + ransac_estimator.fit(X, y) + + # there is a 1e-9 chance it will take these many trials. No good reason + # 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(estimator, min_samples=2) + for i in range(50): + ransac_estimator.set_params(min_samples=2, random_state=i) + ransac_estimator.fit(X, y) + assert ransac_estimator.n_trials_ < max_trials + 1 + + +def test_ransac_stop_n_inliers(): + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + stop_n_inliers=2, + random_state=0, + ) + ransac_estimator.fit(X, y) + + assert ransac_estimator.n_trials_ == 1 + + +def test_ransac_stop_score(): + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + stop_score=0, + random_state=0, + ) + ransac_estimator.fit(X, y) + + assert ransac_estimator.n_trials_ == 1 + + +def test_ransac_score(): + X = np.arange(100)[:, None] + y = np.zeros((100,)) + y[0] = 1 + y[1] = 100 + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=0.5, random_state=0 + ) + ransac_estimator.fit(X, y) + + assert ransac_estimator.score(X[2:], y[2:]) == 1 + assert ransac_estimator.score(X[:2], y[:2]) < 1 + + +def test_ransac_predict(): + X = np.arange(100)[:, None] + y = np.zeros((100,)) + y[0] = 1 + y[1] = 100 + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=0.5, random_state=0 + ) + ransac_estimator.fit(X, y) + + assert_array_equal(ransac_estimator.predict(X), np.zeros(100)) + + +def test_ransac_no_valid_data(): + def is_data_valid(X, y): + return False + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, is_data_valid=is_data_valid, max_trials=5 + ) + + msg = "RANSAC could not find a valid consensus set" + with pytest.raises(ValueError, match=msg): + ransac_estimator.fit(X, y) + assert ransac_estimator.n_skips_no_inliers_ == 0 + assert ransac_estimator.n_skips_invalid_data_ == 5 + assert ransac_estimator.n_skips_invalid_model_ == 0 + + +def test_ransac_no_valid_model(): + def is_model_valid(estimator, X, y): + return False + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, is_model_valid=is_model_valid, max_trials=5 + ) + + msg = "RANSAC could not find a valid consensus set" + with pytest.raises(ValueError, match=msg): + ransac_estimator.fit(X, y) + assert ransac_estimator.n_skips_no_inliers_ == 0 + assert ransac_estimator.n_skips_invalid_data_ == 0 + assert ransac_estimator.n_skips_invalid_model_ == 5 + + +def test_ransac_exceed_max_skips(): + def is_data_valid(X, y): + return False + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, is_data_valid=is_data_valid, max_trials=5, max_skips=3 + ) + + msg = "RANSAC skipped more iterations than `max_skips`" + with pytest.raises(ValueError, match=msg): + ransac_estimator.fit(X, y) + assert ransac_estimator.n_skips_no_inliers_ == 0 + assert ransac_estimator.n_skips_invalid_data_ == 4 + assert ransac_estimator.n_skips_invalid_model_ == 0 + + +def test_ransac_warn_exceed_max_skips(): + global cause_skip + cause_skip = False + + def is_data_valid(X, y): + global cause_skip + if not cause_skip: + cause_skip = True + return True + else: + return False + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, is_data_valid=is_data_valid, max_skips=3, max_trials=5 + ) + warning_message = ( + "RANSAC found a valid consensus set but exited " + "early due to skipping more iterations than " + "`max_skips`. See estimator attributes for " + "diagnostics." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + ransac_estimator.fit(X, y) + assert ransac_estimator.n_skips_no_inliers_ == 0 + assert ransac_estimator.n_skips_invalid_data_ == 4 + assert ransac_estimator.n_skips_invalid_model_ == 0 + + +@pytest.mark.parametrize( + "sparse_container", COO_CONTAINERS + CSR_CONTAINERS + CSC_CONTAINERS +) +def test_ransac_sparse(sparse_container): + X_sparse = sparse_container(X) + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + ransac_estimator.fit(X_sparse, y) + + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_array_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_none_estimator(): + estimator = LinearRegression() + + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + ransac_none_estimator = RANSACRegressor( + None, min_samples=2, residual_threshold=5, random_state=0 + ) + + ransac_estimator.fit(X, y) + ransac_none_estimator.fit(X, y) + + assert_array_almost_equal( + ransac_estimator.predict(X), ransac_none_estimator.predict(X) + ) + + +def test_ransac_min_n_samples(): + estimator = LinearRegression() + ransac_estimator1 = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + ransac_estimator2 = RANSACRegressor( + estimator, + min_samples=2.0 / X.shape[0], + residual_threshold=5, + random_state=0, + ) + ransac_estimator5 = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + ransac_estimator6 = RANSACRegressor(estimator, residual_threshold=5, random_state=0) + ransac_estimator7 = RANSACRegressor( + estimator, min_samples=X.shape[0] + 1, residual_threshold=5, random_state=0 + ) + # GH #19390 + ransac_estimator8 = RANSACRegressor( + Ridge(), min_samples=None, residual_threshold=5, random_state=0 + ) + + ransac_estimator1.fit(X, y) + ransac_estimator2.fit(X, y) + ransac_estimator5.fit(X, y) + ransac_estimator6.fit(X, y) + + assert_array_almost_equal( + ransac_estimator1.predict(X), ransac_estimator2.predict(X) + ) + assert_array_almost_equal( + ransac_estimator1.predict(X), ransac_estimator5.predict(X) + ) + assert_array_almost_equal( + ransac_estimator1.predict(X), ransac_estimator6.predict(X) + ) + + with pytest.raises(ValueError): + ransac_estimator7.fit(X, y) + + err_msg = "`min_samples` needs to be explicitly set" + with pytest.raises(ValueError, match=err_msg): + ransac_estimator8.fit(X, y) + + +def test_ransac_multi_dimensional_targets(): + estimator = LinearRegression() + ransac_estimator = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + + # 3-D target values + yyy = np.column_stack([y, y, y]) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, yyy) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_array_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_residual_loss(): + def loss_multi1(y_true, y_pred): + return np.sum(np.abs(y_true - y_pred), axis=1) + + def loss_multi2(y_true, y_pred): + return np.sum((y_true - y_pred) ** 2, axis=1) + + def loss_mono(y_true, y_pred): + return np.abs(y_true - y_pred) + + yyy = np.column_stack([y, y, y]) + + estimator = LinearRegression() + ransac_estimator0 = RANSACRegressor( + estimator, min_samples=2, residual_threshold=5, random_state=0 + ) + ransac_estimator1 = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + random_state=0, + loss=loss_multi1, + ) + ransac_estimator2 = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + random_state=0, + loss=loss_multi2, + ) + + # multi-dimensional + ransac_estimator0.fit(X, yyy) + ransac_estimator1.fit(X, yyy) + ransac_estimator2.fit(X, yyy) + assert_array_almost_equal( + ransac_estimator0.predict(X), ransac_estimator1.predict(X) + ) + assert_array_almost_equal( + ransac_estimator0.predict(X), ransac_estimator2.predict(X) + ) + + # one-dimensional + ransac_estimator0.fit(X, y) + ransac_estimator2.loss = loss_mono + ransac_estimator2.fit(X, y) + assert_array_almost_equal( + ransac_estimator0.predict(X), ransac_estimator2.predict(X) + ) + ransac_estimator3 = RANSACRegressor( + estimator, + min_samples=2, + residual_threshold=5, + random_state=0, + loss="squared_error", + ) + ransac_estimator3.fit(X, y) + assert_array_almost_equal( + ransac_estimator0.predict(X), ransac_estimator2.predict(X) + ) + + +def test_ransac_default_residual_threshold(): + estimator = LinearRegression() + ransac_estimator = RANSACRegressor(estimator, min_samples=2, random_state=0) + + # Estimate parameters of corrupted data + ransac_estimator.fit(X, y) + + # Ground truth / reference inlier mask + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_).astype(np.bool_) + ref_inlier_mask[outliers] = False + + assert_array_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + +def test_ransac_dynamic_max_trials(): + # Numbers hand-calculated and confirmed on page 119 (Table 4.3) in + # Hartley, R.~I. and Zisserman, A., 2004, + # Multiple View Geometry in Computer Vision, Second Edition, + # Cambridge University Press, ISBN: 0521540518 + + # e = 0%, min_samples = X + assert _dynamic_max_trials(100, 100, 2, 0.99) == 1 + + # e = 5%, min_samples = 2 + assert _dynamic_max_trials(95, 100, 2, 0.99) == 2 + # e = 10%, min_samples = 2 + assert _dynamic_max_trials(90, 100, 2, 0.99) == 3 + # e = 30%, min_samples = 2 + assert _dynamic_max_trials(70, 100, 2, 0.99) == 7 + # e = 50%, min_samples = 2 + assert _dynamic_max_trials(50, 100, 2, 0.99) == 17 + + # e = 5%, min_samples = 8 + assert _dynamic_max_trials(95, 100, 8, 0.99) == 5 + # e = 10%, min_samples = 8 + assert _dynamic_max_trials(90, 100, 8, 0.99) == 9 + # e = 30%, min_samples = 8 + assert _dynamic_max_trials(70, 100, 8, 0.99) == 78 + # e = 50%, min_samples = 8 + assert _dynamic_max_trials(50, 100, 8, 0.99) == 1177 + + # e = 0%, min_samples = 10 + assert _dynamic_max_trials(1, 100, 10, 0) == 0 + assert _dynamic_max_trials(1, 100, 10, 1) == float("inf") + + +def test_ransac_fit_sample_weight(): + ransac_estimator = RANSACRegressor(random_state=0) + n_samples = y.shape[0] + weights = np.ones(n_samples) + ransac_estimator.fit(X, y, sample_weight=weights) + # sanity check + assert ransac_estimator.inlier_mask_.shape[0] == n_samples + + ref_inlier_mask = np.ones_like(ransac_estimator.inlier_mask_).astype(np.bool_) + ref_inlier_mask[outliers] = False + # check that mask is correct + assert_array_equal(ransac_estimator.inlier_mask_, ref_inlier_mask) + + # check that fit(X) = fit([X1, X2, X3],sample_weight = [n1, n2, n3]) where + # X = X1 repeated n1 times, X2 repeated n2 times and so forth + random_state = check_random_state(0) + X_ = random_state.randint(0, 200, [10, 1]) + y_ = np.ndarray.flatten(0.2 * X_ + 2) + sample_weight = random_state.randint(0, 10, 10) + outlier_X = random_state.randint(0, 1000, [1, 1]) + outlier_weight = random_state.randint(0, 10, 1) + outlier_y = random_state.randint(-1000, 0, 1) + + X_flat = np.append( + np.repeat(X_, sample_weight, axis=0), + np.repeat(outlier_X, outlier_weight, axis=0), + axis=0, + ) + y_flat = np.ndarray.flatten( + np.append( + np.repeat(y_, sample_weight, axis=0), + np.repeat(outlier_y, outlier_weight, axis=0), + axis=0, + ) + ) + ransac_estimator.fit(X_flat, y_flat) + ref_coef_ = ransac_estimator.estimator_.coef_ + + sample_weight = np.append(sample_weight, outlier_weight) + X_ = np.append(X_, outlier_X, axis=0) + y_ = np.append(y_, outlier_y) + ransac_estimator.fit(X_, y_, sample_weight=sample_weight) + + assert_allclose(ransac_estimator.estimator_.coef_, ref_coef_) + + # check that if estimator.fit doesn't support + # sample_weight, raises error + estimator = OrthogonalMatchingPursuit() + ransac_estimator = RANSACRegressor(estimator, min_samples=10) + + err_msg = f"{estimator.__class__.__name__} does not support sample_weight." + with pytest.raises(ValueError, match=err_msg): + ransac_estimator.fit(X, y, sample_weight=weights) + + +def test_ransac_final_model_fit_sample_weight(): + X, y = make_regression(n_samples=1000, random_state=10) + rng = check_random_state(42) + sample_weight = rng.randint(1, 4, size=y.shape[0]) + sample_weight = sample_weight / sample_weight.sum() + ransac = RANSACRegressor(random_state=0) + ransac.fit(X, y, sample_weight=sample_weight) + + final_model = LinearRegression() + mask_samples = ransac.inlier_mask_ + final_model.fit( + X[mask_samples], y[mask_samples], sample_weight=sample_weight[mask_samples] + ) + + assert_allclose(ransac.estimator_.coef_, final_model.coef_, atol=1e-12) + + +def test_perfect_horizontal_line(): + """Check that we can fit a line where all samples are inliers. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/19497 + """ + X = np.arange(100)[:, None] + y = np.zeros((100,)) + + estimator = LinearRegression() + ransac_estimator = RANSACRegressor(estimator, random_state=0) + ransac_estimator.fit(X, y) + + assert_allclose(ransac_estimator.estimator_.coef_, 0.0) + assert_allclose(ransac_estimator.estimator_.intercept_, 0.0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ridge.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ridge.py new file mode 100644 index 0000000000000000000000000000000000000000..24515195fb7ccd674091ab6b90a91b43a59a14aa --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_ridge.py @@ -0,0 +1,2380 @@ +import warnings +from itertools import product + +import numpy as np +import pytest +from scipy import linalg + +from sklearn import config_context, datasets +from sklearn.base import clone +from sklearn.datasets import ( + make_classification, + make_low_rank_matrix, + make_multilabel_classification, + make_regression, +) +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ( + LinearRegression, + Ridge, + RidgeClassifier, + RidgeClassifierCV, + RidgeCV, + ridge_regression, +) +from sklearn.linear_model._ridge import ( + _check_gcv_mode, + _RidgeGCV, + _solve_cholesky, + _solve_cholesky_kernel, + _solve_lbfgs, + _solve_svd, + _X_CenterStackOp, +) +from sklearn.metrics import get_scorer, make_scorer, mean_squared_error +from sklearn.model_selection import ( + GridSearchCV, + GroupKFold, + KFold, + LeaveOneOut, + cross_val_predict, +) +from sklearn.preprocessing import minmax_scale +from sklearn.utils import check_random_state +from sklearn.utils._array_api import ( + _NUMPY_NAMESPACE_NAMES, + _atol_for_type, + _convert_to_numpy, + _get_namespace_device_dtype_ids, + yield_namespace_device_dtype_combinations, + yield_namespaces, +) +from sklearn.utils._test_common.instance_generator import _get_check_estimator_ids +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + ignore_warnings, +) +from sklearn.utils.estimator_checks import ( + _array_api_for_tests, + check_array_api_input_and_values, +) +from sklearn.utils.fixes import ( + _IS_32BIT, + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, + LIL_CONTAINERS, +) + +SOLVERS = ["svd", "sparse_cg", "cholesky", "lsqr", "sag", "saga"] +SPARSE_SOLVERS_WITH_INTERCEPT = ("sparse_cg", "sag") +SPARSE_SOLVERS_WITHOUT_INTERCEPT = ("sparse_cg", "cholesky", "lsqr", "sag", "saga") + +diabetes = datasets.load_diabetes() +X_diabetes, y_diabetes = diabetes.data, diabetes.target +ind = np.arange(X_diabetes.shape[0]) +rng = np.random.RandomState(0) +rng.shuffle(ind) +ind = ind[:200] +X_diabetes, y_diabetes = X_diabetes[ind], y_diabetes[ind] + +iris = datasets.load_iris() +X_iris, y_iris = iris.data, iris.target + + +def _accuracy_callable(y_test, y_pred, **kwargs): + return np.mean(y_test == y_pred) + + +def _mean_squared_error_callable(y_test, y_pred): + return ((y_test - y_pred) ** 2).mean() + + +@pytest.fixture(params=["long", "wide"]) +def ols_ridge_dataset(global_random_seed, request): + """Dataset with OLS and Ridge solutions, well conditioned X. + + The construction is based on the SVD decomposition of X = U S V'. + + Parameters + ---------- + type : {"long", "wide"} + If "long", then n_samples > n_features. + If "wide", then n_features > n_samples. + + For "wide", we return the minimum norm solution w = X' (XX')^-1 y: + + min ||w||_2 subject to X w = y + + Returns + ------- + X : ndarray + Last column of 1, i.e. intercept. + y : ndarray + coef_ols : ndarray of shape + Minimum norm OLS solutions, i.e. min ||X w - y||_2_2 (with minimum ||w||_2 in + case of ambiguity) + Last coefficient is intercept. + coef_ridge : ndarray of shape (5,) + Ridge solution with alpha=1, i.e. min ||X w - y||_2_2 + ||w||_2^2. + Last coefficient is intercept. + """ + # Make larger dim more than double as big as the smaller one. + # This helps when constructing singular matrices like (X, X). + if request.param == "long": + n_samples, n_features = 12, 4 + else: + n_samples, n_features = 4, 12 + k = min(n_samples, n_features) + rng = np.random.RandomState(global_random_seed) + X = make_low_rank_matrix( + n_samples=n_samples, n_features=n_features, effective_rank=k, random_state=rng + ) + X[:, -1] = 1 # last columns acts as intercept + U, s, Vt = linalg.svd(X) + assert np.all(s > 1e-3) # to be sure + U1, U2 = U[:, :k], U[:, k:] + Vt1, _ = Vt[:k, :], Vt[k:, :] + + if request.param == "long": + # Add a term that vanishes in the product X'y + coef_ols = rng.uniform(low=-10, high=10, size=n_features) + y = X @ coef_ols + y += U2 @ rng.normal(size=n_samples - n_features) ** 2 + else: + y = rng.uniform(low=-10, high=10, size=n_samples) + # w = X'(XX')^-1 y = V s^-1 U' y + coef_ols = Vt1.T @ np.diag(1 / s) @ U1.T @ y + + # Add penalty alpha * ||coef||_2^2 for alpha=1 and solve via normal equations. + # Note that the problem is well conditioned such that we get accurate results. + alpha = 1 + d = alpha * np.identity(n_features) + d[-1, -1] = 0 # intercept gets no penalty + coef_ridge = linalg.solve(X.T @ X + d, X.T @ y) + + # To be sure + R_OLS = y - X @ coef_ols + R_Ridge = y - X @ coef_ridge + assert np.linalg.norm(R_OLS) < np.linalg.norm(R_Ridge) + + return X, y, coef_ols, coef_ridge + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression(solver, fit_intercept, ols_ridge_dataset, global_random_seed): + """Test that Ridge converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + """ + X, y, _, coef = ols_ridge_dataset + alpha = 1.0 # because ols_ridge_dataset uses this. + params = dict( + alpha=alpha, + fit_intercept=True, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + + # Calculate residuals and R2. + res_null = y - np.mean(y) + res_Ridge = y - X @ coef + R2_Ridge = 1 - np.sum(res_Ridge**2) / np.sum(res_null**2) + + model = Ridge(**params) + X = X[:, :-1] # remove intercept + if fit_intercept: + intercept = coef[-1] + else: + X = X - X.mean(axis=0) + y = y - y.mean() + intercept = 0 + model.fit(X, y) + coef = coef[:-1] + + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + assert model.score(X, y) == pytest.approx(R2_Ridge) + + # Same with sample_weight. + model = Ridge(**params).fit(X, y, sample_weight=np.ones(X.shape[0])) + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + assert model.score(X, y) == pytest.approx(R2_Ridge) + + assert model.solver_ == solver + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression_hstacked_X( + solver, fit_intercept, ols_ridge_dataset, global_random_seed +): + """Test that Ridge converges for all solvers to correct solution on hstacked data. + + We work with a simple constructed data set with known solution. + Fit on [X] with alpha is the same as fit on [X, X]/2 with alpha/2. + For long X, [X, X] is a singular matrix. + """ + X, y, _, coef = ols_ridge_dataset + n_samples, n_features = X.shape + alpha = 1.0 # because ols_ridge_dataset uses this. + + model = Ridge( + alpha=alpha / 2, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + X = X[:, :-1] # remove intercept + X = 0.5 * np.concatenate((X, X), axis=1) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features - 1) + if fit_intercept: + intercept = coef[-1] + else: + X = X - X.mean(axis=0) + y = y - y.mean() + intercept = 0 + model.fit(X, y) + coef = coef[:-1] + + assert model.intercept_ == pytest.approx(intercept) + # coefficients are not all on the same magnitude, adding a small atol to + # make this test less brittle + assert_allclose(model.coef_, np.r_[coef, coef], atol=1e-8) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression_vstacked_X( + solver, fit_intercept, ols_ridge_dataset, global_random_seed +): + """Test that Ridge converges for all solvers to correct solution on vstacked data. + + We work with a simple constructed data set with known solution. + Fit on [X] with alpha is the same as fit on [X], [y] + [X], [y] with 2 * alpha. + For wide X, [X', X'] is a singular matrix. + """ + X, y, _, coef = ols_ridge_dataset + n_samples, n_features = X.shape + alpha = 1.0 # because ols_ridge_dataset uses this. + + model = Ridge( + alpha=2 * alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + X = X[:, :-1] # remove intercept + X = np.concatenate((X, X), axis=0) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + y = np.r_[y, y] + if fit_intercept: + intercept = coef[-1] + else: + X = X - X.mean(axis=0) + y = y - y.mean() + intercept = 0 + model.fit(X, y) + coef = coef[:-1] + + assert model.intercept_ == pytest.approx(intercept) + # coefficients are not all on the same magnitude, adding a small atol to + # make this test less brittle + assert_allclose(model.coef_, coef, atol=1e-8) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression_unpenalized( + solver, fit_intercept, ols_ridge_dataset, global_random_seed +): + """Test that unpenalized Ridge = OLS converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + Note: This checks the minimum norm solution for wide X, i.e. + n_samples < n_features: + min ||w||_2 subject to X w = y + """ + X, y, coef, _ = ols_ridge_dataset + n_samples, n_features = X.shape + alpha = 0 # OLS + params = dict( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + + model = Ridge(**params) + # Note that cholesky might give a warning: "Singular matrix in solving dual + # problem. Using least-squares solution instead." + if fit_intercept: + X = X[:, :-1] # remove intercept + intercept = coef[-1] + coef = coef[:-1] + else: + intercept = 0 + model.fit(X, y) + + # FIXME: `assert_allclose(model.coef_, coef)` should work for all cases but fails + # for the wide/fat case with n_features > n_samples. The current Ridge solvers do + # NOT return the minimum norm solution with fit_intercept=True. + if n_samples > n_features or not fit_intercept: + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + else: + # As it is an underdetermined problem, residuals = 0. This shows that we get + # a solution to X w = y .... + assert_allclose(model.predict(X), y) + assert_allclose(X @ coef + intercept, y) + # But it is not the minimum norm solution. (This should be equal.) + assert np.linalg.norm(np.r_[model.intercept_, model.coef_]) > np.linalg.norm( + np.r_[intercept, coef] + ) + + pytest.xfail(reason="Ridge does not provide the minimum norm solution.") + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression_unpenalized_hstacked_X( + solver, fit_intercept, ols_ridge_dataset, global_random_seed +): + """Test that unpenalized Ridge = OLS converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + OLS fit on [X] is the same as fit on [X, X]/2. + For long X, [X, X] is a singular matrix and we check against the minimum norm + solution: + min ||w||_2 subject to min ||X w - y||_2 + """ + X, y, coef, _ = ols_ridge_dataset + n_samples, n_features = X.shape + alpha = 0 # OLS + + model = Ridge( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + if fit_intercept: + X = X[:, :-1] # remove intercept + intercept = coef[-1] + coef = coef[:-1] + else: + intercept = 0 + X = 0.5 * np.concatenate((X, X), axis=1) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + model.fit(X, y) + + if n_samples > n_features or not fit_intercept: + assert model.intercept_ == pytest.approx(intercept) + if solver == "cholesky": + # Cholesky is a bad choice for singular X. + pytest.skip() + assert_allclose(model.coef_, np.r_[coef, coef]) + else: + # FIXME: Same as in test_ridge_regression_unpenalized. + # As it is an underdetermined problem, residuals = 0. This shows that we get + # a solution to X w = y .... + assert_allclose(model.predict(X), y) + # But it is not the minimum norm solution. (This should be equal.) + assert np.linalg.norm(np.r_[model.intercept_, model.coef_]) > np.linalg.norm( + np.r_[intercept, coef, coef] + ) + + pytest.xfail(reason="Ridge does not provide the minimum norm solution.") + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, np.r_[coef, coef]) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +def test_ridge_regression_unpenalized_vstacked_X( + solver, fit_intercept, ols_ridge_dataset, global_random_seed +): + """Test that unpenalized Ridge = OLS converges for all solvers to correct solution. + + We work with a simple constructed data set with known solution. + OLS fit on [X] is the same as fit on [X], [y] + [X], [y]. + For wide X, [X', X'] is a singular matrix and we check against the minimum norm + solution: + min ||w||_2 subject to X w = y + """ + X, y, coef, _ = ols_ridge_dataset + n_samples, n_features = X.shape + alpha = 0 # OLS + + model = Ridge( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ("sag", "saga") else 1e-10, + random_state=global_random_seed, + ) + + if fit_intercept: + X = X[:, :-1] # remove intercept + intercept = coef[-1] + coef = coef[:-1] + else: + intercept = 0 + X = np.concatenate((X, X), axis=0) + assert np.linalg.matrix_rank(X) <= min(n_samples, n_features) + y = np.r_[y, y] + model.fit(X, y) + + if n_samples > n_features or not fit_intercept: + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + else: + # FIXME: Same as in test_ridge_regression_unpenalized. + # As it is an underdetermined problem, residuals = 0. This shows that we get + # a solution to X w = y .... + assert_allclose(model.predict(X), y) + # But it is not the minimum norm solution. (This should be equal.) + assert np.linalg.norm(np.r_[model.intercept_, model.coef_]) > np.linalg.norm( + np.r_[intercept, coef] + ) + + pytest.xfail(reason="Ridge does not provide the minimum norm solution.") + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + + +@pytest.mark.parametrize("solver", SOLVERS) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize("alpha", [1.0, 1e-2]) +def test_ridge_regression_sample_weights( + solver, + fit_intercept, + sparse_container, + alpha, + ols_ridge_dataset, + global_random_seed, +): + """Test that Ridge with sample weights gives correct results. + + We use the following trick: + ||y - Xw||_2 = (z - Aw)' W (z - Aw) + for z=[y, y], A' = [X', X'] (vstacked), and W[:n/2] + W[n/2:] = 1, W=diag(W) + """ + if sparse_container is not None: + if fit_intercept and solver not in SPARSE_SOLVERS_WITH_INTERCEPT: + pytest.skip() + elif not fit_intercept and solver not in SPARSE_SOLVERS_WITHOUT_INTERCEPT: + pytest.skip() + X, y, _, coef = ols_ridge_dataset + n_samples, n_features = X.shape + sw = rng.uniform(low=0, high=1, size=n_samples) + + model = Ridge( + alpha=alpha, + fit_intercept=fit_intercept, + solver=solver, + tol=1e-15 if solver in ["sag", "saga"] else 1e-10, + max_iter=100_000, + random_state=global_random_seed, + ) + X = X[:, :-1] # remove intercept + X = np.concatenate((X, X), axis=0) + y = np.r_[y, y] + sw = np.r_[sw, 1 - sw] * alpha + if fit_intercept: + intercept = coef[-1] + else: + X = X - X.mean(axis=0) + y = y - y.mean() + intercept = 0 + if sparse_container is not None: + X = sparse_container(X) + model.fit(X, y, sample_weight=sw) + coef = coef[:-1] + + assert model.intercept_ == pytest.approx(intercept) + assert_allclose(model.coef_, coef) + + +def test_primal_dual_relationship(): + y = y_diabetes.reshape(-1, 1) + coef = _solve_cholesky(X_diabetes, y, alpha=[1e-2]) + K = np.dot(X_diabetes, X_diabetes.T) + dual_coef = _solve_cholesky_kernel(K, y, alpha=[1e-2]) + coef2 = np.dot(X_diabetes.T, dual_coef).T + assert_array_almost_equal(coef, coef2) + + +def test_ridge_regression_convergence_fail(): + rng = np.random.RandomState(0) + y = rng.randn(5) + X = rng.randn(5, 10) + warning_message = r"sparse_cg did not converge after [0-9]+ iterations." + with pytest.warns(ConvergenceWarning, match=warning_message): + ridge_regression( + X, y, alpha=1.0, solver="sparse_cg", tol=0.0, max_iter=None, verbose=1 + ) + + +def test_ridge_shapes_type(): + # Test shape of coef_ and intercept_ + rng = np.random.RandomState(0) + n_samples, n_features = 5, 10 + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + Y1 = y[:, np.newaxis] + Y = np.c_[y, 1 + y] + + ridge = Ridge() + + ridge.fit(X, y) + assert ridge.coef_.shape == (n_features,) + assert ridge.intercept_.shape == () + assert isinstance(ridge.coef_, np.ndarray) + assert isinstance(ridge.intercept_, float) + + ridge.fit(X, Y1) + assert ridge.coef_.shape == (n_features,) + assert ridge.intercept_.shape == (1,) + assert isinstance(ridge.coef_, np.ndarray) + assert isinstance(ridge.intercept_, np.ndarray) + + ridge.fit(X, Y) + assert ridge.coef_.shape == (2, n_features) + assert ridge.intercept_.shape == (2,) + assert isinstance(ridge.coef_, np.ndarray) + assert isinstance(ridge.intercept_, np.ndarray) + + +def test_ridge_intercept(): + # Test intercept with multiple targets GH issue #708 + rng = np.random.RandomState(0) + n_samples, n_features = 5, 10 + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + Y = np.c_[y, 1.0 + y] + + ridge = Ridge() + + ridge.fit(X, y) + intercept = ridge.intercept_ + + ridge.fit(X, Y) + assert_almost_equal(ridge.intercept_[0], intercept) + assert_almost_equal(ridge.intercept_[1], intercept + 1.0) + + +def test_ridge_vs_lstsq(): + # On alpha=0., Ridge and OLS yield the same solution. + + rng = np.random.RandomState(0) + # we need more samples than features + n_samples, n_features = 5, 4 + y = rng.randn(n_samples) + X = rng.randn(n_samples, n_features) + + ridge = Ridge(alpha=0.0, fit_intercept=False) + ols = LinearRegression(fit_intercept=False) + + ridge.fit(X, y) + ols.fit(X, y) + assert_almost_equal(ridge.coef_, ols.coef_) + + ridge.fit(X, y) + ols.fit(X, y) + assert_almost_equal(ridge.coef_, ols.coef_) + + +def test_ridge_individual_penalties(): + # Tests the ridge object using individual penalties + + 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) + + penalties = np.arange(n_targets) + + coef_cholesky = np.array( + [ + Ridge(alpha=alpha, solver="cholesky").fit(X, target).coef_ + for alpha, target in zip(penalties, y.T) + ] + ) + + coefs_indiv_pen = [ + 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: + assert_array_almost_equal(coef_cholesky, coef_indiv_pen) + + # Test error is raised when number of targets and penalties do not match. + ridge = Ridge(alpha=penalties[:-1]) + err_msg = "Number of targets and number of penalties do not correspond: 4 != 5" + with pytest.raises(ValueError, match=err_msg): + ridge.fit(X, y) + + +@pytest.mark.parametrize("n_col", [(), (1,), (3,)]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_X_CenterStackOp(n_col, csr_container): + rng = np.random.RandomState(0) + X = rng.randn(11, 8) + X_m = rng.randn(8) + sqrt_sw = rng.randn(len(X)) + Y = rng.randn(11, *n_col) + A = rng.randn(9, *n_col) + operator = _X_CenterStackOp(csr_container(X), X_m, sqrt_sw) + reference_operator = np.hstack([X - sqrt_sw[:, None] * X_m, sqrt_sw[:, None]]) + assert_allclose(reference_operator.dot(A), operator.dot(A)) + assert_allclose(reference_operator.T.dot(Y), operator.T.dot(Y)) + + +@pytest.mark.parametrize("shape", [(10, 1), (13, 9), (3, 7), (2, 2), (20, 20)]) +@pytest.mark.parametrize("uniform_weights", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_compute_gram(shape, uniform_weights, csr_container): + rng = np.random.RandomState(0) + X = rng.randn(*shape) + if uniform_weights: + sw = np.ones(X.shape[0]) + else: + sw = rng.chisquare(1, shape[0]) + sqrt_sw = np.sqrt(sw) + X_mean = np.average(X, axis=0, weights=sw) + X_centered = (X - X_mean) * sqrt_sw[:, None] + true_gram = X_centered.dot(X_centered.T) + X_sparse = csr_container(X * sqrt_sw[:, None]) + gcv = _RidgeGCV(fit_intercept=True) + computed_gram, computed_mean = gcv._compute_gram(X_sparse, sqrt_sw) + assert_allclose(X_mean, computed_mean) + assert_allclose(true_gram, computed_gram) + + +@pytest.mark.parametrize("shape", [(10, 1), (13, 9), (3, 7), (2, 2), (20, 20)]) +@pytest.mark.parametrize("uniform_weights", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_compute_covariance(shape, uniform_weights, csr_container): + rng = np.random.RandomState(0) + X = rng.randn(*shape) + if uniform_weights: + sw = np.ones(X.shape[0]) + else: + sw = rng.chisquare(1, shape[0]) + sqrt_sw = np.sqrt(sw) + X_mean = np.average(X, axis=0, weights=sw) + X_centered = (X - X_mean) * sqrt_sw[:, None] + true_covariance = X_centered.T.dot(X_centered) + X_sparse = csr_container(X * sqrt_sw[:, None]) + gcv = _RidgeGCV(fit_intercept=True) + computed_cov, computed_mean = gcv._compute_covariance(X_sparse, sqrt_sw) + assert_allclose(X_mean, computed_mean) + assert_allclose(true_covariance, computed_cov) + + +def _make_sparse_offset_regression( + n_samples=100, + n_features=100, + proportion_nonzero=0.5, + n_informative=10, + n_targets=1, + bias=13.0, + X_offset=30.0, + noise=30.0, + shuffle=True, + coef=False, + positive=False, + random_state=None, +): + X, y, c = make_regression( + n_samples=n_samples, + n_features=n_features, + n_informative=n_informative, + n_targets=n_targets, + bias=bias, + noise=noise, + shuffle=shuffle, + coef=True, + random_state=random_state, + ) + if n_features == 1: + c = np.asarray([c]) + X += X_offset + mask = ( + np.random.RandomState(random_state).binomial(1, proportion_nonzero, X.shape) > 0 + ) + removed_X = X.copy() + 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: + return X, y, c + return X, y + + +@pytest.mark.parametrize( + "solver, sparse_container", + ( + (solver, sparse_container) + for (solver, sparse_container) in product( + ["cholesky", "sag", "sparse_cg", "lsqr", "saga", "ridgecv"], + [None] + CSR_CONTAINERS, + ) + if sparse_container is None or solver in ["sparse_cg", "ridgecv"] + ), +) +@pytest.mark.parametrize( + "n_samples,dtype,proportion_nonzero", + [(20, "float32", 0.1), (40, "float32", 1.0), (20, "float64", 0.2)], +) +def test_solver_consistency( + solver, proportion_nonzero, n_samples, dtype, sparse_container, global_random_seed +): + alpha = 1.0 + noise = 50.0 if proportion_nonzero > 0.9 else 500.0 + X, y = _make_sparse_offset_regression( + bias=10, + n_features=30, + proportion_nonzero=proportion_nonzero, + noise=noise, + random_state=global_random_seed, + n_samples=n_samples, + ) + # Manually scale the data to avoid pathological cases. We use + # minmax_scale to deal with the sparse case without breaking + # the sparsity pattern. + X = minmax_scale(X) + + svd_ridge = Ridge(solver="svd", alpha=alpha).fit(X, y) + X = X.astype(dtype, copy=False) + y = y.astype(dtype, copy=False) + if sparse_container is not None: + X = sparse_container(X) + if solver == "ridgecv": + ridge = RidgeCV(alphas=[alpha]) + else: + if solver.startswith("sag"): + # Avoid ConvergenceWarning for sag and saga solvers. + tol = 1e-7 + max_iter = 100_000 + else: + tol = 1e-10 + max_iter = None + + ridge = Ridge( + alpha=alpha, + solver=solver, + max_iter=max_iter, + tol=tol, + random_state=global_random_seed, + ) + ridge.fit(X, y) + assert_allclose(ridge.coef_, svd_ridge.coef_, atol=1e-3, rtol=1e-3) + assert_allclose(ridge.intercept_, svd_ridge.intercept_, atol=1e-3, rtol=1e-3) + + +@pytest.mark.parametrize("gcv_mode", ["svd", "eigen"]) +@pytest.mark.parametrize("X_container", [np.asarray] + CSR_CONTAINERS) +@pytest.mark.parametrize("X_shape", [(11, 8), (11, 20)]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize( + "y_shape, noise", + [ + ((11,), 1.0), + ((11, 1), 30.0), + ((11, 3), 150.0), + ], +) +def test_ridge_gcv_vs_ridge_loo_cv( + gcv_mode, X_container, X_shape, y_shape, fit_intercept, noise +): + n_samples, n_features = X_shape + n_targets = y_shape[-1] if len(y_shape) == 2 else 1 + X, y = _make_sparse_offset_regression( + n_samples=n_samples, + n_features=n_features, + n_targets=n_targets, + random_state=0, + shuffle=False, + noise=noise, + n_informative=5, + ) + y = y.reshape(y_shape) + + alphas = [1e-3, 0.1, 1.0, 10.0, 1e3] + loo_ridge = RidgeCV( + cv=n_samples, + fit_intercept=fit_intercept, + alphas=alphas, + scoring="neg_mean_squared_error", + ) + gcv_ridge = RidgeCV( + gcv_mode=gcv_mode, + fit_intercept=fit_intercept, + alphas=alphas, + ) + + loo_ridge.fit(X, y) + + X_gcv = X_container(X) + gcv_ridge.fit(X_gcv, y) + + assert gcv_ridge.alpha_ == pytest.approx(loo_ridge.alpha_) + assert_allclose(gcv_ridge.coef_, loo_ridge.coef_, rtol=1e-3) + assert_allclose(gcv_ridge.intercept_, loo_ridge.intercept_, rtol=1e-3) + + +def test_ridge_loo_cv_asym_scoring(): + # checking on asymmetric scoring + scoring = "explained_variance" + n_samples, n_features = 10, 5 + n_targets = 1 + X, y = _make_sparse_offset_regression( + n_samples=n_samples, + n_features=n_features, + n_targets=n_targets, + random_state=0, + shuffle=False, + noise=1, + n_informative=5, + ) + + alphas = [1e-3, 0.1, 1.0, 10.0, 1e3] + loo_ridge = RidgeCV( + cv=n_samples, fit_intercept=True, alphas=alphas, scoring=scoring + ) + + gcv_ridge = RidgeCV(fit_intercept=True, alphas=alphas, scoring=scoring) + + loo_ridge.fit(X, y) + gcv_ridge.fit(X, y) + + assert gcv_ridge.alpha_ == pytest.approx(loo_ridge.alpha_), ( + f"{gcv_ridge.alpha_=}, {loo_ridge.alpha_=}" + ) + assert_allclose(gcv_ridge.coef_, loo_ridge.coef_, rtol=1e-3) + assert_allclose(gcv_ridge.intercept_, loo_ridge.intercept_, rtol=1e-3) + + +@pytest.mark.parametrize("gcv_mode", ["svd", "eigen"]) +@pytest.mark.parametrize("X_container", [np.asarray] + CSR_CONTAINERS) +@pytest.mark.parametrize("n_features", [8, 20]) +@pytest.mark.parametrize( + "y_shape, fit_intercept, noise", + [ + ((11,), True, 1.0), + ((11, 1), True, 20.0), + ((11, 3), True, 150.0), + ((11, 3), False, 30.0), + ], +) +def test_ridge_gcv_sample_weights( + gcv_mode, X_container, fit_intercept, n_features, y_shape, noise +): + alphas = [1e-3, 0.1, 1.0, 10.0, 1e3] + rng = np.random.RandomState(0) + n_targets = y_shape[-1] if len(y_shape) == 2 else 1 + X, y = _make_sparse_offset_regression( + n_samples=11, + n_features=n_features, + n_targets=n_targets, + random_state=0, + shuffle=False, + noise=noise, + ) + y = y.reshape(y_shape) + + sample_weight = 3 * rng.randn(len(X)) + sample_weight = (sample_weight - sample_weight.min() + 1).astype(int) + indices = np.repeat(np.arange(X.shape[0]), sample_weight) + sample_weight = sample_weight.astype(float) + X_tiled, y_tiled = X[indices], y[indices] + + cv = GroupKFold(n_splits=X.shape[0]) + splits = cv.split(X_tiled, y_tiled, groups=indices) + kfold = RidgeCV( + alphas=alphas, + cv=splits, + scoring="neg_mean_squared_error", + fit_intercept=fit_intercept, + ) + kfold.fit(X_tiled, y_tiled) + + ridge_reg = Ridge(alpha=kfold.alpha_, fit_intercept=fit_intercept) + splits = cv.split(X_tiled, y_tiled, groups=indices) + predictions = cross_val_predict(ridge_reg, X_tiled, y_tiled, cv=splits) + if predictions.shape != y_tiled.shape: + predictions = predictions.reshape(y_tiled.shape) + kfold_errors = (y_tiled - predictions) ** 2 + kfold_errors = [ + np.sum(kfold_errors[indices == i], axis=0) for i in np.arange(X.shape[0]) + ] + kfold_errors = np.asarray(kfold_errors) + + X_gcv = X_container(X) + gcv_ridge = RidgeCV( + alphas=alphas, + store_cv_results=True, + gcv_mode=gcv_mode, + fit_intercept=fit_intercept, + ) + gcv_ridge.fit(X_gcv, y, sample_weight=sample_weight) + if len(y_shape) == 2: + gcv_errors = gcv_ridge.cv_results_[:, :, alphas.index(kfold.alpha_)] + else: + gcv_errors = gcv_ridge.cv_results_[:, alphas.index(kfold.alpha_)] + + assert kfold.alpha_ == pytest.approx(gcv_ridge.alpha_) + assert_allclose(gcv_errors, kfold_errors, rtol=1e-3) + assert_allclose(gcv_ridge.coef_, kfold.coef_, rtol=1e-3) + assert_allclose(gcv_ridge.intercept_, kfold.intercept_, rtol=1e-3) + + +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize( + "mode, mode_n_greater_than_p, mode_p_greater_than_n", + [ + (None, "svd", "eigen"), + ("auto", "svd", "eigen"), + ("eigen", "eigen", "eigen"), + ("svd", "svd", "svd"), + ], +) +def test_check_gcv_mode_choice( + sparse_container, mode, mode_n_greater_than_p, mode_p_greater_than_n +): + X, _ = make_regression(n_samples=5, n_features=2) + if sparse_container is not None: + X = sparse_container(X) + assert _check_gcv_mode(X, mode) == mode_n_greater_than_p + assert _check_gcv_mode(X.T, mode) == mode_p_greater_than_n + + +def _test_ridge_loo(sparse_container): + # test that can work with both dense or sparse matrices + n_samples = X_diabetes.shape[0] + + ret = [] + + if sparse_container is None: + X, fit_intercept = X_diabetes, True + else: + X, fit_intercept = sparse_container(X_diabetes), False + ridge_gcv = _RidgeGCV(fit_intercept=fit_intercept) + + # check best alpha + ridge_gcv.fit(X, y_diabetes) + alpha_ = ridge_gcv.alpha_ + ret.append(alpha_) + + # check that we get same best alpha with custom loss_func + f = ignore_warnings + scoring = make_scorer(mean_squared_error, greater_is_better=False) + ridge_gcv2 = RidgeCV(fit_intercept=False, scoring=scoring) + f(ridge_gcv2.fit)(X, y_diabetes) + assert ridge_gcv2.alpha_ == pytest.approx(alpha_) + + # check that we get same best alpha with custom score_func + def func(x, y): + return -mean_squared_error(x, y) + + scoring = make_scorer(func) + ridge_gcv3 = RidgeCV(fit_intercept=False, scoring=scoring) + f(ridge_gcv3.fit)(X, y_diabetes) + assert ridge_gcv3.alpha_ == pytest.approx(alpha_) + + # check that we get same best alpha with a scorer + scorer = get_scorer("neg_mean_squared_error") + ridge_gcv4 = RidgeCV(fit_intercept=False, scoring=scorer) + ridge_gcv4.fit(X, y_diabetes) + assert ridge_gcv4.alpha_ == pytest.approx(alpha_) + + # check that we get same best alpha with sample weights + if sparse_container is None: + ridge_gcv.fit(X, y_diabetes, sample_weight=np.ones(n_samples)) + assert ridge_gcv.alpha_ == pytest.approx(alpha_) + + # simulate several responses + Y = np.vstack((y_diabetes, y_diabetes)).T + + ridge_gcv.fit(X, Y) + Y_pred = ridge_gcv.predict(X) + ridge_gcv.fit(X, y_diabetes) + y_pred = ridge_gcv.predict(X) + + assert_allclose(np.vstack((y_pred, y_pred)).T, Y_pred, rtol=1e-5) + + return ret + + +def _test_ridge_cv(sparse_container): + X = X_diabetes if sparse_container is None else sparse_container(X_diabetes) + ridge_cv = RidgeCV() + ridge_cv.fit(X, y_diabetes) + ridge_cv.predict(X) + + assert len(ridge_cv.coef_.shape) == 1 + assert type(ridge_cv.intercept_) is np.float64 + + cv = KFold(5) + ridge_cv.set_params(cv=cv) + ridge_cv.fit(X, y_diabetes) + ridge_cv.predict(X) + + assert len(ridge_cv.coef_.shape) == 1 + assert type(ridge_cv.intercept_) is np.float64 + + +@pytest.mark.parametrize( + "ridge, make_dataset", + [ + (RidgeCV(store_cv_results=False), make_regression), + (RidgeClassifierCV(store_cv_results=False), make_classification), + ], +) +def test_ridge_gcv_cv_results_not_stored(ridge, make_dataset): + # Check that `cv_results_` is not stored when store_cv_results is False + X, y = make_dataset(n_samples=6, random_state=42) + ridge.fit(X, y) + assert not hasattr(ridge, "cv_results_") + + +@pytest.mark.parametrize( + "ridge, make_dataset", + [(RidgeCV(), make_regression), (RidgeClassifierCV(), make_classification)], +) +@pytest.mark.parametrize("cv", [None, 3]) +def test_ridge_best_score(ridge, make_dataset, cv): + # check that the best_score_ is store + X, y = make_dataset(n_samples=6, random_state=42) + ridge.set_params(store_cv_results=False, cv=cv) + ridge.fit(X, y) + assert hasattr(ridge, "best_score_") + 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_results_ + ridge_cv = RidgeCV(alphas=alphas, alpha_per_target=True, store_cv_results=True).fit( + X, y + ) + assert ridge_cv.alpha_.shape == (n_targets,) + assert ridge_cv.best_score_.shape == (n_targets,) + assert ridge_cv.cv_results_.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_results=True).fit(X, y) + assert ridge_cv.alpha_.shape == (n_targets,) + assert ridge_cv.best_score_.shape == (n_targets,) + assert ridge_cv.cv_results_.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_results=True).fit( + X, y[:, 0] + ) + assert np.isscalar(ridge_cv.alpha_) + assert np.isscalar(ridge_cv.best_score_) + assert ridge_cv.cv_results_.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(sparse_container): + X = X_diabetes if sparse_container is None else sparse_container(X_diabetes) + ridge = Ridge(fit_intercept=False) + ridge.fit(X, y_diabetes) + return np.round(ridge.score(X, y_diabetes), 5) + + +def _test_multi_ridge_diabetes(sparse_container): + # simulate several responses + X = X_diabetes if sparse_container is None else sparse_container(X_diabetes) + Y = np.vstack((y_diabetes, y_diabetes)).T + n_features = X_diabetes.shape[1] + + ridge = Ridge(fit_intercept=False) + ridge.fit(X, Y) + assert ridge.coef_.shape == (2, n_features) + Y_pred = ridge.predict(X) + ridge.fit(X, y_diabetes) + y_pred = ridge.predict(X) + assert_array_almost_equal(np.vstack((y_pred, y_pred)).T, Y_pred, decimal=3) + + +def _test_ridge_classifiers(sparse_container): + n_classes = np.unique(y_iris).shape[0] + n_features = X_iris.shape[1] + X = X_iris if sparse_container is None else sparse_container(X_iris) + + for reg in (RidgeClassifier(), RidgeClassifierCV()): + reg.fit(X, y_iris) + assert reg.coef_.shape == (n_classes, n_features) + y_pred = reg.predict(X) + assert np.mean(y_iris == y_pred) > 0.79 + + cv = KFold(5) + reg = RidgeClassifierCV(cv=cv) + reg.fit(X, y_iris) + y_pred = reg.predict(X) + assert np.mean(y_iris == y_pred) >= 0.8 + + +@pytest.mark.parametrize("scoring", [None, "accuracy", _accuracy_callable]) +@pytest.mark.parametrize("cv", [None, KFold(5)]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_ridge_classifier_with_scoring(sparse_container, scoring, cv): + # non-regression test for #14672 + # check that RidgeClassifierCV works with all sort of scoring and + # cross-validation + X = X_iris if sparse_container is None else sparse_container(X_iris) + scoring_ = make_scorer(scoring) if callable(scoring) else scoring + clf = RidgeClassifierCV(scoring=scoring_, cv=cv) + # Smoke test to check that fit/predict does not raise error + clf.fit(X, y_iris).predict(X) + + +@pytest.mark.parametrize("cv", [None, KFold(5)]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +def test_ridge_regression_custom_scoring(sparse_container, cv): + # check that custom scoring is working as expected + # check the tie breaking strategy (keep the first alpha tried) + + def _dummy_score(y_test, y_pred, **kwargs): + return 0.42 + + X = X_iris if sparse_container is None else sparse_container(X_iris) + alphas = np.logspace(-2, 2, num=5) + clf = RidgeClassifierCV(alphas=alphas, scoring=make_scorer(_dummy_score), cv=cv) + clf.fit(X, y_iris) + assert clf.best_score_ == pytest.approx(0.42) + # In case of tie score, the first alphas will be kept + assert clf.alpha_ == pytest.approx(alphas[0]) + + +def _test_tolerance(sparse_container): + X = X_diabetes if sparse_container is None else sparse_container(X_diabetes) + + ridge = Ridge(tol=1e-5, fit_intercept=False) + ridge.fit(X, y_diabetes) + score = ridge.score(X, y_diabetes) + + ridge2 = Ridge(tol=1e-3, fit_intercept=False) + ridge2.fit(X, y_diabetes) + score2 = ridge2.score(X, y_diabetes) + + assert score >= score2 + + +def check_array_api_attributes(name, estimator, array_namespace, device, dtype_name): + xp = _array_api_for_tests(array_namespace, device) + + X_iris_np = X_iris.astype(dtype_name) + y_iris_np = y_iris.astype(dtype_name) + + X_iris_xp = xp.asarray(X_iris_np, device=device) + y_iris_xp = xp.asarray(y_iris_np, device=device) + + estimator.fit(X_iris_np, y_iris_np) + coef_np = estimator.coef_ + intercept_np = estimator.intercept_ + + with config_context(array_api_dispatch=True): + estimator_xp = clone(estimator).fit(X_iris_xp, y_iris_xp) + coef_xp = estimator_xp.coef_ + assert coef_xp.shape == (4,) + assert coef_xp.dtype == X_iris_xp.dtype + + assert_allclose( + _convert_to_numpy(coef_xp, xp=xp), + coef_np, + atol=_atol_for_type(dtype_name), + ) + intercept_xp = estimator_xp.intercept_ + assert intercept_xp.shape == () + assert intercept_xp.dtype == X_iris_xp.dtype + + assert_allclose( + _convert_to_numpy(intercept_xp, xp=xp), + intercept_np, + atol=_atol_for_type(dtype_name), + ) + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", + yield_namespace_device_dtype_combinations(), + ids=_get_namespace_device_dtype_ids, +) +@pytest.mark.parametrize( + "check", + [check_array_api_input_and_values, check_array_api_attributes], + ids=_get_check_estimator_ids, +) +@pytest.mark.parametrize( + "estimator", + [Ridge(solver="svd")], + ids=_get_check_estimator_ids, +) +def test_ridge_array_api_compliance( + estimator, check, array_namespace, device, dtype_name +): + name = estimator.__class__.__name__ + check(name, estimator, array_namespace, device=device, dtype_name=dtype_name) + + +@pytest.mark.parametrize( + "array_namespace", yield_namespaces(include_numpy_namespaces=False) +) +def test_array_api_error_and_warnings_for_solver_parameter(array_namespace): + xp = _array_api_for_tests(array_namespace, device=None) + + X_iris_xp = xp.asarray(X_iris[:5]) + y_iris_xp = xp.asarray(y_iris[:5]) + + available_solvers = Ridge._parameter_constraints["solver"][0].options + for solver in available_solvers - {"auto", "svd"}: + ridge = Ridge(solver=solver, positive=solver == "lbfgs") + expected_msg = ( + f"Array API dispatch to namespace {xp.__name__} only supports " + f"solver 'svd'. Got '{solver}'." + ) + + with pytest.raises(ValueError, match=expected_msg): + with config_context(array_api_dispatch=True): + ridge.fit(X_iris_xp, y_iris_xp) + + ridge = Ridge(solver="auto", positive=True) + expected_msg = ( + "The solvers that support positive fitting do not support " + f"Array API dispatch to namespace {xp.__name__}. Please " + "either disable Array API dispatch, or use a numpy-like " + "namespace, or set `positive=False`." + ) + + with pytest.raises(ValueError, match=expected_msg): + with config_context(array_api_dispatch=True): + ridge.fit(X_iris_xp, y_iris_xp) + + ridge = Ridge() + expected_msg = ( + f"Using Array API dispatch to namespace {xp.__name__} with `solver='auto'` " + "will result in using the solver 'svd'. The results may differ from those " + "when using a Numpy array, because in that case the preferred solver would " + "be cholesky. Set `solver='svd'` to suppress this warning." + ) + with pytest.warns(UserWarning, match=expected_msg): + with config_context(array_api_dispatch=True): + ridge.fit(X_iris_xp, y_iris_xp) + + +@pytest.mark.parametrize("array_namespace", sorted(_NUMPY_NAMESPACE_NAMES)) +def test_array_api_numpy_namespace_no_warning(array_namespace): + xp = _array_api_for_tests(array_namespace, device=None) + + X_iris_xp = xp.asarray(X_iris[:5]) + y_iris_xp = xp.asarray(y_iris[:5]) + + ridge = Ridge() + expected_msg = ( + "Results might be different than when Array API dispatch is " + "disabled, or when a numpy-like namespace is used" + ) + + with warnings.catch_warnings(): + warnings.filterwarnings("error", message=expected_msg, category=UserWarning) + with config_context(array_api_dispatch=True): + ridge.fit(X_iris_xp, y_iris_xp) + + # All numpy namespaces are compatible with all solver, in particular + # solvers that support `positive=True` (like 'lbfgs') should work. + with config_context(array_api_dispatch=True): + Ridge(solver="auto", positive=True).fit(X_iris_xp, y_iris_xp) + + +@pytest.mark.parametrize( + "test_func", + ( + _test_ridge_loo, + _test_ridge_cv, + _test_ridge_diabetes, + _test_multi_ridge_diabetes, + _test_ridge_classifiers, + _test_tolerance, + ), +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_dense_sparse(test_func, csr_container): + # test dense matrix + ret_dense = test_func(None) + # test sparse matrix + ret_sparse = test_func(csr_container) + # test that the outputs are the same + if ret_dense is not None and ret_sparse is not None: + assert_array_almost_equal(ret_dense, ret_sparse, decimal=3) + + +def test_class_weights(): + # Test class weights. + 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] + + reg = RidgeClassifier(class_weight=None) + reg.fit(X, y) + assert_array_equal(reg.predict([[0.2, -1.0]]), np.array([1])) + + # we give a small weights to class 1 + reg = RidgeClassifier(class_weight={1: 0.001}) + reg.fit(X, y) + + # now the hyperplane should rotate clock-wise and + # the prediction on this point should shift + assert_array_equal(reg.predict([[0.2, -1.0]]), np.array([-1])) + + # check if class_weight = 'balanced' can handle negative labels. + reg = RidgeClassifier(class_weight="balanced") + reg.fit(X, y) + assert_array_equal(reg.predict([[0.2, -1.0]]), np.array([1])) + + # class_weight = 'balanced', and class_weight = None should return + # same values when y has equal number of all labels + X = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0]]) + y = [1, 1, -1, -1] + reg = RidgeClassifier(class_weight=None) + reg.fit(X, y) + rega = RidgeClassifier(class_weight="balanced") + rega.fit(X, y) + assert len(rega.classes_) == 2 + assert_array_almost_equal(reg.coef_, rega.coef_) + assert_array_almost_equal(reg.intercept_, rega.intercept_) + + +@pytest.mark.parametrize("reg", (RidgeClassifier, RidgeClassifierCV)) +def test_class_weight_vs_sample_weight(reg): + """Check class_weights resemble sample_weights behavior.""" + + # Iris is balanced, so no effect expected for using 'balanced' weights + reg1 = reg() + reg1.fit(iris.data, iris.target) + reg2 = reg(class_weight="balanced") + reg2.fit(iris.data, iris.target) + assert_almost_equal(reg1.coef_, reg2.coef_) + + # Inflate importance of class 1, check against user-defined weights + sample_weight = np.ones(iris.target.shape) + sample_weight[iris.target == 1] *= 100 + class_weight = {0: 1.0, 1: 100.0, 2: 1.0} + reg1 = reg() + reg1.fit(iris.data, iris.target, sample_weight) + reg2 = reg(class_weight=class_weight) + reg2.fit(iris.data, iris.target) + assert_almost_equal(reg1.coef_, reg2.coef_) + + # Check that sample_weight and class_weight are multiplicative + reg1 = reg() + reg1.fit(iris.data, iris.target, sample_weight**2) + reg2 = reg(class_weight=class_weight) + reg2.fit(iris.data, iris.target, sample_weight) + assert_almost_equal(reg1.coef_, reg2.coef_) + + +def test_class_weights_cv(): + # Test class weights for cross validated ridge classifier. + 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] + + reg = RidgeClassifierCV(class_weight=None, alphas=[0.01, 0.1, 1]) + reg.fit(X, y) + + # we give a small weights to class 1 + reg = RidgeClassifierCV(class_weight={1: 0.001}, alphas=[0.01, 0.1, 1, 10]) + reg.fit(X, y) + + assert_array_equal(reg.predict([[-0.2, 2]]), np.array([-1])) + + +@pytest.mark.parametrize( + "scoring", [None, "neg_mean_squared_error", _mean_squared_error_callable] +) +def test_ridgecv_store_cv_results(scoring): + rng = np.random.RandomState(42) + + n_samples = 8 + n_features = 5 + x = rng.randn(n_samples, n_features) + alphas = [1e-1, 1e0, 1e1] + n_alphas = len(alphas) + + scoring_ = make_scorer(scoring) if callable(scoring) else scoring + + r = RidgeCV(alphas=alphas, cv=None, store_cv_results=True, scoring=scoring_) + + # with len(y.shape) == 1 + y = rng.randn(n_samples) + r.fit(x, y) + assert r.cv_results_.shape == (n_samples, n_alphas) + + # with len(y.shape) == 2 + n_targets = 3 + y = rng.randn(n_samples, n_targets) + r.fit(x, y) + assert r.cv_results_.shape == (n_samples, n_targets, n_alphas) + + r = RidgeCV(cv=3, store_cv_results=True, scoring=scoring) + with pytest.raises(ValueError, match="cv!=None and store_cv_results"): + r.fit(x, y) + + +@pytest.mark.parametrize("scoring", [None, "accuracy", _accuracy_callable]) +def test_ridge_classifier_cv_store_cv_results(scoring): + x = np.array([[-1.0, -1.0], [-1.0, 0], [-0.8, -1.0], [1.0, 1.0], [1.0, 0.0]]) + y = np.array([1, 1, 1, -1, -1]) + + n_samples = x.shape[0] + alphas = [1e-1, 1e0, 1e1] + n_alphas = len(alphas) + + scoring_ = make_scorer(scoring) if callable(scoring) else scoring + + r = RidgeClassifierCV( + alphas=alphas, cv=None, store_cv_results=True, scoring=scoring_ + ) + + # with len(y.shape) == 1 + n_targets = 1 + r.fit(x, y) + assert r.cv_results_.shape == (n_samples, n_targets, n_alphas) + + # with len(y.shape) == 2 + y = np.array( + [[1, 1, 1, -1, -1], [1, -1, 1, -1, 1], [-1, -1, 1, -1, -1]] + ).transpose() + n_targets = y.shape[1] + r.fit(x, y) + assert r.cv_results_.shape == (n_samples, n_targets, n_alphas) + + +@pytest.mark.parametrize("Estimator", [RidgeCV, RidgeClassifierCV]) +def test_ridgecv_alphas_conversion(Estimator): + rng = np.random.RandomState(0) + alphas = (0.1, 1.0, 10.0) + + n_samples, n_features = 5, 5 + if Estimator is RidgeCV: + y = rng.randn(n_samples) + else: + y = rng.randint(0, 2, n_samples) + X = rng.randn(n_samples, n_features) + + ridge_est = Estimator(alphas=alphas) + assert ridge_est.alphas is alphas, ( + f"`alphas` was mutated in `{Estimator.__name__}.__init__`" + ) + + ridge_est.fit(X, y) + assert_array_equal(ridge_est.alphas, np.asarray(alphas)) + + +@pytest.mark.parametrize("cv", [None, 3]) +@pytest.mark.parametrize("Estimator", [RidgeCV, RidgeClassifierCV]) +def test_ridgecv_alphas_zero(cv, Estimator): + """Check alpha=0.0 raises error only when `cv=None`.""" + rng = np.random.RandomState(0) + alphas = (0.0, 1.0, 10.0) + + n_samples, n_features = 5, 5 + if Estimator is RidgeCV: + y = rng.randn(n_samples) + else: + y = rng.randint(0, 2, n_samples) + X = rng.randn(n_samples, n_features) + + ridge_est = Estimator(alphas=alphas, cv=cv) + if cv is None: + with pytest.raises(ValueError, match=r"alphas\[0\] == 0.0, must be > 0.0."): + ridge_est.fit(X, y) + else: + ridge_est.fit(X, y) + + +def test_ridgecv_sample_weight(): + rng = np.random.RandomState(0) + alphas = (0.1, 1.0, 10.0) + + # There are different algorithms for n_samples > n_features + # and the opposite, so test them both. + for n_samples, n_features in ((6, 5), (5, 10)): + y = rng.randn(n_samples) + X = rng.randn(n_samples, n_features) + sample_weight = 1.0 + rng.rand(n_samples) + + cv = KFold(5) + ridgecv = RidgeCV(alphas=alphas, cv=cv) + ridgecv.fit(X, y, sample_weight=sample_weight) + + # Check using GridSearchCV directly + parameters = {"alpha": alphas} + gs = GridSearchCV(Ridge(), parameters, cv=cv) + gs.fit(X, y, sample_weight=sample_weight) + + assert ridgecv.alpha_ == gs.best_estimator_.alpha + assert_array_almost_equal(ridgecv.coef_, gs.best_estimator_.coef_) + + +def test_raises_value_error_if_sample_weights_greater_than_1d(): + # Sample weights must be either scalar or 1D + + n_sampless = [2, 3] + n_featuress = [3, 2] + + rng = np.random.RandomState(42) + + for n_samples, n_features in zip(n_sampless, n_featuress): + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + sample_weights_OK = rng.randn(n_samples) ** 2 + 1 + sample_weights_OK_1 = 1.0 + sample_weights_OK_2 = 2.0 + sample_weights_not_OK = sample_weights_OK[:, np.newaxis] + sample_weights_not_OK_2 = sample_weights_OK[np.newaxis, :] + + ridge = Ridge(alpha=1) + + # make sure the "OK" sample weights actually work + ridge.fit(X, y, sample_weights_OK) + ridge.fit(X, y, sample_weights_OK_1) + ridge.fit(X, y, sample_weights_OK_2) + + def fit_ridge_not_ok(): + ridge.fit(X, y, sample_weights_not_OK) + + def fit_ridge_not_ok_2(): + ridge.fit(X, y, sample_weights_not_OK_2) + + err_msg = "Sample weights must be 1D array or scalar" + with pytest.raises(ValueError, match=err_msg): + fit_ridge_not_ok() + + err_msg = "Sample weights must be 1D array or scalar" + with pytest.raises(ValueError, match=err_msg): + fit_ridge_not_ok_2() + + +@pytest.mark.parametrize("n_samples,n_features", [[2, 3], [3, 2]]) +@pytest.mark.parametrize( + "sparse_container", + COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +def test_sparse_design_with_sample_weights(n_samples, n_features, sparse_container): + # Sample weights must work with sparse matrices + rng = np.random.RandomState(42) + + sparse_ridge = Ridge(alpha=1.0, fit_intercept=False) + dense_ridge = Ridge(alpha=1.0, fit_intercept=False) + + X = rng.randn(n_samples, n_features) + y = rng.randn(n_samples) + sample_weights = rng.randn(n_samples) ** 2 + 1 + X_sparse = sparse_container(X) + sparse_ridge.fit(X_sparse, y, sample_weight=sample_weights) + dense_ridge.fit(X, y, sample_weight=sample_weights) + + assert_array_almost_equal(sparse_ridge.coef_, dense_ridge.coef_, decimal=6) + + +def test_ridgecv_int_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] + + # Integers + ridge = RidgeCV(alphas=(1, 10, 100)) + ridge.fit(X, y) + + +@pytest.mark.parametrize("Estimator", [RidgeCV, RidgeClassifierCV]) +@pytest.mark.parametrize( + "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 float, not str", + ), + ], +) +def test_ridgecv_alphas_validation(Estimator, params, err_type, err_msg): + """Check the `alphas` validation in RidgeCV and RidgeClassifierCV.""" + + n_samples, n_features = 5, 5 + X = rng.randn(n_samples, n_features) + y = rng.randint(0, 2, n_samples) + + with pytest.raises(err_type, match=err_msg): + Estimator(**params).fit(X, y) + + +@pytest.mark.parametrize("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_sparse_cg_max_iter(): + reg = Ridge(solver="sparse_cg", max_iter=1) + reg.fit(X_diabetes, y_diabetes) + assert reg.coef_.shape[0] == X_diabetes.shape[1] + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_n_iter(): + # Test that self.n_iter_ is correct. + n_targets = 2 + X, y = X_diabetes, y_diabetes + y_n = np.tile(y, (n_targets, 1)).T + + for max_iter in range(1, 4): + for solver in ("sag", "saga", "lsqr"): + reg = Ridge(solver=solver, max_iter=max_iter, tol=1e-12) + reg.fit(X, y_n) + assert_array_equal(reg.n_iter_, np.tile(max_iter, n_targets)) + + for solver in ("sparse_cg", "svd", "cholesky"): + reg = Ridge(solver=solver, max_iter=1, tol=1e-1) + reg.fit(X, y_n) + assert reg.n_iter_ is None + + +@pytest.mark.parametrize("solver", ["lsqr", "sparse_cg", "lbfgs", "auto"]) +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_ridge_fit_intercept_sparse( + solver, with_sample_weight, global_random_seed, csr_container +): + """Check that ridge finds the same coefs and intercept on dense and sparse input + in the presence of sample weights. + + 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. + Other solvers raise an exception, as checked in + test_ridge_fit_intercept_sparse_error + """ + positive = solver == "lbfgs" + X, y = _make_sparse_offset_regression( + n_features=20, random_state=global_random_seed, positive=positive + ) + + sample_weight = None + if with_sample_weight: + rng = np.random.RandomState(global_random_seed) + sample_weight = 1.0 + rng.uniform(size=X.shape[0]) + + # "auto" should switch to "sparse_cg" when X is sparse + # 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_solver = "sparse_cg" if solver == "auto" else solver + dense_ridge = Ridge(solver=dense_solver, tol=1e-12, positive=positive) + sparse_ridge = Ridge(solver=solver, tol=1e-12, positive=positive) + + dense_ridge.fit(X, y, sample_weight=sample_weight) + sparse_ridge.fit(csr_container(X), y, sample_weight=sample_weight) + + assert_allclose(dense_ridge.intercept_, sparse_ridge.intercept_) + assert_allclose(dense_ridge.coef_, sparse_ridge.coef_, rtol=5e-7) + + +@pytest.mark.parametrize("solver", ["saga", "svd", "cholesky"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_ridge_fit_intercept_sparse_error(solver, csr_container): + X, y = _make_sparse_offset_regression(n_features=20, random_state=0) + X_csr = csr_container(X) + sparse_ridge = Ridge(solver=solver) + err_msg = "solver='{}' does not support".format(solver) + with pytest.raises(ValueError, match=err_msg): + sparse_ridge.fit(X_csr, y) + + +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_ridge_fit_intercept_sparse_sag( + with_sample_weight, global_random_seed, csr_container +): + X, y = _make_sparse_offset_regression( + n_features=5, n_samples=20, random_state=global_random_seed, X_offset=5.0 + ) + if with_sample_weight: + rng = np.random.RandomState(global_random_seed) + sample_weight = 1.0 + rng.uniform(size=X.shape[0]) + else: + sample_weight = None + X_csr = csr_container(X) + + params = dict( + alpha=1.0, solver="sag", fit_intercept=True, tol=1e-10, max_iter=100000 + ) + dense_ridge = Ridge(**params) + sparse_ridge = Ridge(**params) + dense_ridge.fit(X, y, sample_weight=sample_weight) + with warnings.catch_warnings(): + warnings.simplefilter("error", UserWarning) + sparse_ridge.fit(X_csr, y, sample_weight=sample_weight) + assert_allclose(dense_ridge.intercept_, sparse_ridge.intercept_, rtol=1e-4) + assert_allclose(dense_ridge.coef_, sparse_ridge.coef_, rtol=1e-4) + with pytest.warns(UserWarning, match='"sag" solver requires.*'): + Ridge(solver="sag", fit_intercept=True, tol=1e-3, max_iter=None).fit(X_csr, y) + + +@pytest.mark.parametrize("return_intercept", [False, True]) +@pytest.mark.parametrize("sample_weight", [None, np.ones(1000)]) +@pytest.mark.parametrize("container", [np.array] + CSR_CONTAINERS) +@pytest.mark.parametrize( + "solver", ["auto", "sparse_cg", "cholesky", "lsqr", "sag", "saga", "lbfgs"] +) +def test_ridge_regression_check_arguments_validity( + return_intercept, sample_weight, container, solver +): + """check if all combinations of arguments give valid estimations""" + + # test excludes 'svd' solver because it raises exception for sparse inputs + + rng = check_random_state(42) + X = rng.rand(1000, 3) + true_coefs = [1, 2, 0.1] + y = np.dot(X, true_coefs) + true_intercept = 0.0 + if return_intercept: + true_intercept = 10000.0 + y += true_intercept + X_testing = container(X) + + 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( + X_testing, + y, + alpha=alpha, + solver=solver, + sample_weight=sample_weight, + return_intercept=return_intercept, + positive=positive, + tol=tol, + ) + return + + out = ridge_regression( + X_testing, + y, + alpha=alpha, + solver=solver, + sample_weight=sample_weight, + positive=positive, + return_intercept=return_intercept, + tol=tol, + ) + + if return_intercept: + coef, intercept = out + assert_allclose(coef, true_coefs, rtol=0, atol=atol) + assert_allclose(intercept, true_intercept, rtol=0, atol=atol) + else: + assert_allclose(out, true_coefs, rtol=0, atol=atol) + + +@pytest.mark.parametrize( + "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) + y_64 = rng.randn(n_samples) + X_32 = X_64.astype(np.float32) + y_32 = y_64.astype(np.float32) + + tol = 2 * np.finfo(np.float32).resolution + # Check type consistency 32bits + 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, positive=positive + ) + ridge_64.fit(X_64, y_64) + coef_64 = ridge_64.coef_ + + # Do the actual checks at once for easier debug + assert coef_32.dtype == X_32.dtype + assert coef_64.dtype == X_64.dtype + assert ridge_32.predict(X_32).dtype == X_32.dtype + assert ridge_64.predict(X_64).dtype == X_64.dtype + assert_allclose(ridge_32.coef_, ridge_64.coef_, rtol=1e-4, atol=5e-4) + + +def test_dtype_match_cholesky(): + # Test different alphas in cholesky solver to ensure full coverage. + # This test is separated from test_dtype_match for clarity. + rng = np.random.RandomState(0) + alpha = np.array([1.0, 0.5]) + + n_samples, n_features, n_target = 6, 7, 2 + X_64 = rng.randn(n_samples, n_features) + y_64 = rng.randn(n_samples, n_target) + X_32 = X_64.astype(np.float32) + y_32 = y_64.astype(np.float32) + + # Check type consistency 32bits + ridge_32 = Ridge(alpha=alpha, solver="cholesky") + ridge_32.fit(X_32, y_32) + coef_32 = ridge_32.coef_ + + # Check type consistency 64 bits + ridge_64 = Ridge(alpha=alpha, solver="cholesky") + ridge_64.fit(X_64, y_64) + coef_64 = ridge_64.coef_ + + # Do all the checks at once, like this is easier to debug + assert coef_32.dtype == X_32.dtype + assert coef_64.dtype == X_64.dtype + assert ridge_32.predict(X_32).dtype == X_32.dtype + assert ridge_64.predict(X_64).dtype == X_64.dtype + assert_almost_equal(ridge_32.coef_, ridge_64.coef_, decimal=5) + + +@pytest.mark.parametrize( + "solver", ["svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga", "lbfgs"] +) +@pytest.mark.parametrize("seed", range(1)) +def test_ridge_regression_dtype_stability(solver, seed): + random_state = np.random.RandomState(seed) + n_samples, n_features = 6, 5 + X = random_state.randn(n_samples, n_features) + 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. + atol = 1e-3 if solver == "sparse_cg" else 1e-5 + for current_dtype in (np.float32, np.float64): + results[current_dtype] = ridge_regression( + X.astype(current_dtype), + y.astype(current_dtype), + alpha=alpha, + solver=solver, + random_state=random_state, + sample_weight=None, + positive=positive, + max_iter=500, + tol=1e-10, + return_n_iter=False, + return_intercept=False, + ) + + assert results[np.float32].dtype == np.float32 + assert results[np.float64].dtype == np.float64 + assert_allclose(results[np.float32], results[np.float64], atol=atol) + + +def test_ridge_sag_with_X_fortran(): + # check that Fortran array are converted when using SAG solver + X, y = make_regression(random_state=42) + # for the order of X and y to not be C-ordered arrays + X = np.asfortranarray(X) + X = X[::2, :] + y = y[::2] + Ridge(solver="sag").fit(X, y) + + +@pytest.mark.parametrize( + "Classifier, params", + [ + (RidgeClassifier, {}), + (RidgeClassifierCV, {"cv": None}), + (RidgeClassifierCV, {"cv": 3}), + ], +) +def test_ridgeclassifier_multilabel(Classifier, params): + """Check that multilabel classification is supported and give meaningful + results.""" + X, y = make_multilabel_classification(n_classes=1, random_state=0) + y = y.reshape(-1, 1) + Y = np.concatenate([y, y], axis=1) + clf = Classifier(**params).fit(X, Y) + Y_pred = clf.predict(X) + + assert Y_pred.shape == Y.shape + assert_array_equal(Y_pred[:, 0], Y_pred[:, 1]) + Ridge(solver="sag").fit(X, y) + + +@pytest.mark.parametrize("solver", ["auto", "lbfgs"]) +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize("fit_intercept", [True, False]) +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize( + "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 + ) + + +@pytest.mark.parametrize("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 + + +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("sparse_container", [None] + CSR_CONTAINERS) +@pytest.mark.parametrize("data", ["tall", "wide"]) +@pytest.mark.parametrize("solver", SOLVERS + ["lbfgs"]) +def test_ridge_sample_weight_consistency( + fit_intercept, sparse_container, data, solver, global_random_seed +): + """Test that the impact of sample_weight is consistent. + + Note that this test is stricter than the common test + check_sample_weight_equivalence alone. + """ + # filter out solver that do not support sparse input + if sparse_container is not None: + if solver == "svd" or (solver in ("cholesky", "saga") and fit_intercept): + pytest.skip("unsupported configuration") + + # XXX: this test is quite sensitive to the seed used to generate the data: + # ideally we would like the test to pass for any global_random_seed but this is not + # the case at the moment. + rng = np.random.RandomState(42) + n_samples = 12 + if data == "tall": + n_features = n_samples // 2 + else: + n_features = n_samples * 2 + + X = rng.rand(n_samples, n_features) + y = rng.rand(n_samples) + if sparse_container is not None: + X = sparse_container(X) + params = dict( + fit_intercept=fit_intercept, + alpha=1.0, + solver=solver, + positive=(solver == "lbfgs"), + random_state=global_random_seed, # for sag/saga + tol=1e-12, + ) + + # 1) sample_weight=np.ones(..) should be equivalent to sample_weight=None, + # a special case of check_sample_weight_equivalence(name, reg), but we also + # test with sparse input. + reg = Ridge(**params).fit(X, y, sample_weight=None) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + sample_weight = np.ones_like(y) + reg.fit(X, y, sample_weight=sample_weight) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 2) setting elements of sample_weight to 0 is equivalent to removing these samples, + # another special case of check_sample_weight_equivalence(name, reg), but we + # also test with sparse input + sample_weight = rng.uniform(low=0.01, high=2, size=X.shape[0]) + sample_weight[-5:] = 0 + y[-5:] *= 1000 # to make excluding those samples important + reg.fit(X, y, sample_weight=sample_weight) + coef = reg.coef_.copy() + if fit_intercept: + intercept = reg.intercept_ + reg.fit(X[:-5, :], y[:-5], sample_weight=sample_weight[:-5]) + assert_allclose(reg.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg.intercept_, intercept) + + # 3) scaling of sample_weight should have no effect + # Note: For models with penalty, scaling the penalty term might work. + reg2 = Ridge(**params).set_params(alpha=np.pi * params["alpha"]) + reg2.fit(X, y, sample_weight=np.pi * sample_weight) + if solver in ("sag", "saga") and not fit_intercept: + pytest.xfail(f"Solver {solver} does fail test for scaling of sample_weight.") + assert_allclose(reg2.coef_, coef, rtol=1e-6) + if fit_intercept: + assert_allclose(reg2.intercept_, intercept) + + # 4) check that multiplying sample_weight by 2 is equivalent + # to repeating corresponding samples twice + if sparse_container is not None: + X = X.toarray() + X2 = np.concatenate([X, X[: n_samples // 2]], axis=0) + y2 = np.concatenate([y, y[: n_samples // 2]]) + sample_weight_1 = sample_weight.copy() + sample_weight_1[: n_samples // 2] *= 2 + sample_weight_2 = np.concatenate( + [sample_weight, sample_weight[: n_samples // 2]], axis=0 + ) + if sparse_container is not None: + X = sparse_container(X) + X2 = sparse_container(X2) + reg1 = Ridge(**params).fit(X, y, sample_weight=sample_weight_1) + reg2 = Ridge(**params).fit(X2, y2, sample_weight=sample_weight_2) + assert_allclose(reg1.coef_, reg2.coef_) + if fit_intercept: + assert_allclose(reg1.intercept_, reg2.intercept_) + + +@pytest.mark.parametrize("with_sample_weight", [False, True]) +@pytest.mark.parametrize("fit_intercept", [False, True]) +@pytest.mark.parametrize("n_targets", [1, 2]) +def test_ridge_cv_results_predictions(with_sample_weight, fit_intercept, n_targets): + """Check that the predictions stored in `cv_results_` are on the original scale. + + The GCV approach works on scaled data: centered by an offset and scaled by the + square root of the sample weights. Thus, prior to computing scores, the + predictions need to be scaled back to the original scale. These predictions are + the ones stored in `cv_results_` in `RidgeCV`. + + In this test, we check that the internal predictions stored in `cv_results_` are + equivalent to a naive LOO-CV grid search with a `Ridge` estimator. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/13998 + """ + X, y = make_regression( + n_samples=100, n_features=10, n_targets=n_targets, random_state=0 + ) + sample_weight = np.ones(shape=(X.shape[0],)) + if with_sample_weight: + sample_weight[::2] = 0.5 + + alphas = (0.1, 1.0, 10.0) + + # scoring should be set to store predictions and not the squared error + ridge_cv = RidgeCV( + alphas=alphas, + scoring="neg_mean_squared_error", + fit_intercept=fit_intercept, + store_cv_results=True, + ) + ridge_cv.fit(X, y, sample_weight=sample_weight) + + # manual grid-search with a `Ridge` estimator + predictions = np.empty(shape=(*y.shape, len(alphas))) + cv = LeaveOneOut() + for alpha_idx, alpha in enumerate(alphas): + for idx, (train_idx, test_idx) in enumerate(cv.split(X, y)): + ridge = Ridge(alpha=alpha, fit_intercept=fit_intercept) + ridge.fit(X[train_idx], y[train_idx], sample_weight[train_idx]) + predictions[idx, ..., alpha_idx] = ridge.predict(X[test_idx]) + assert_allclose(ridge_cv.cv_results_, predictions) + + +def test_ridge_cv_multioutput_sample_weight(global_random_seed): + """Check that `RidgeCV` works properly with multioutput and sample_weight + when `scoring != None`. + + We check the error reported by the RidgeCV is close to a naive LOO-CV using a + Ridge estimator. + """ + X, y = make_regression(n_targets=2, random_state=global_random_seed) + sample_weight = np.ones(shape=(X.shape[0],)) + + ridge_cv = RidgeCV(scoring="neg_mean_squared_error", store_cv_results=True) + ridge_cv.fit(X, y, sample_weight=sample_weight) + + cv = LeaveOneOut() + ridge = Ridge(alpha=ridge_cv.alpha_) + y_pred_loo = np.squeeze( + [ + ridge.fit(X[train], y[train], sample_weight=sample_weight[train]).predict( + X[test] + ) + for train, test in cv.split(X) + ] + ) + assert_allclose(ridge_cv.best_score_, -mean_squared_error(y, y_pred_loo)) + + +def test_ridge_cv_custom_multioutput_scorer(): + """Check that `RidgeCV` works properly with a custom multioutput scorer.""" + X, y = make_regression(n_targets=2, random_state=0) + + def custom_error(y_true, y_pred): + errors = (y_true - y_pred) ** 2 + mean_errors = np.mean(errors, axis=0) + if mean_errors.ndim == 1: + # case of multioutput + return -np.average(mean_errors, weights=[2, 1]) + # single output - this part of the code should not be reached in the case of + # multioutput scoring + return -mean_errors # pragma: no cover + + def custom_multioutput_scorer(estimator, X, y): + """Multioutput score that give twice more importance to the second target.""" + return -custom_error(y, estimator.predict(X)) + + ridge_cv = RidgeCV(scoring=custom_multioutput_scorer) + ridge_cv.fit(X, y) + + cv = LeaveOneOut() + ridge = Ridge(alpha=ridge_cv.alpha_) + y_pred_loo = np.squeeze( + [ridge.fit(X[train], y[train]).predict(X[test]) for train, test in cv.split(X)] + ) + + assert_allclose(ridge_cv.best_score_, -custom_error(y, y_pred_loo)) + + +# Metadata Routing Tests +# ====================== + + +@pytest.mark.parametrize("metaestimator", [RidgeCV, RidgeClassifierCV]) +@config_context(enable_metadata_routing=True) +def test_metadata_routing_with_default_scoring(metaestimator): + """Test that `RidgeCV` or `RidgeClassifierCV` with default `scoring` + argument (`None`), don't enter into `RecursionError` when metadata is routed. + """ + metaestimator().get_metadata_routing() + + +@pytest.mark.parametrize( + "metaestimator, make_dataset", + [ + (RidgeCV(), make_regression), + (RidgeClassifierCV(), make_classification), + ], +) +@config_context(enable_metadata_routing=True) +def test_set_score_request_with_default_scoring(metaestimator, make_dataset): + """Test that `set_score_request` is set within `RidgeCV.fit()` and + `RidgeClassifierCV.fit()` when using the default scoring and no + UnsetMetadataPassedError is raised. Regression test for the fix in PR #29634.""" + X, y = make_dataset(n_samples=100, n_features=5, random_state=42) + metaestimator.fit(X, y, sample_weight=np.ones(X.shape[0])) + + +# End of Metadata Routing Tests +# ============================= diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sag.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sag.py new file mode 100644 index 0000000000000000000000000000000000000000..575838f8e8497a01c60adbb74ddad95dadc6e662 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sag.py @@ -0,0 +1,861 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import math +import re + +import numpy as np +import pytest + +from sklearn.base import clone +from sklearn.datasets import load_iris, make_blobs, make_classification +from sklearn.linear_model import LogisticRegression, Ridge +from sklearn.linear_model._sag import get_auto_step_size +from sklearn.multiclass import OneVsRestClassifier +from sklearn.preprocessing import LabelEncoder +from sklearn.utils import check_random_state, compute_class_weight +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, +) +from sklearn.utils.extmath import row_norms +from sklearn.utils.fixes import CSR_CONTAINERS + +iris = load_iris() + + +# this is used for sag classification +def log_dloss(p, y): + z = p * y + # approximately equal and saves the computation of the log + if z > 18.0: + return math.exp(-z) * -y + if z < -18.0: + return -y + return -y / (math.exp(z) + 1.0) + + +def log_loss(p, y): + return np.mean(np.log(1.0 + np.exp(-y * p))) + + +# this is used for sag regression +def squared_dloss(p, y): + return p - y + + +def squared_loss(p, y): + return np.mean(0.5 * (p - y) * (p - y)) + + +# function for measuring the log loss +def get_pobj(w, alpha, myX, myy, loss): + w = w.ravel() + pred = np.dot(myX, w) + p = loss(pred, myy) + p += alpha * w.dot(w) / 2.0 + return p + + +def sag( + X, + y, + step_size, + alpha, + n_iter=1, + dloss=None, + sparse=False, + sample_weight=None, + fit_intercept=True, + saga=False, +): + n_samples, n_features = X.shape[0], X.shape[1] + + weights = np.zeros(X.shape[1]) + sum_gradient = np.zeros(X.shape[1]) + gradient_memory = np.zeros((n_samples, n_features)) + + intercept = 0.0 + intercept_sum_gradient = 0.0 + intercept_gradient_memory = np.zeros(n_samples) + + rng = np.random.RandomState(77) + decay = 1.0 + seen = set() + + # sparse data has a fixed decay of .01 + if sparse: + decay = 0.01 + + for epoch in range(n_iter): + for k in range(n_samples): + idx = int(rng.rand() * n_samples) + # idx = k + entry = X[idx] + seen.add(idx) + p = np.dot(entry, weights) + intercept + gradient = dloss(p, y[idx]) + if sample_weight is not None: + gradient *= sample_weight[idx] + update = entry * gradient + alpha * weights + gradient_correction = update - gradient_memory[idx] + sum_gradient += gradient_correction + gradient_memory[idx] = update + if saga: + weights -= gradient_correction * step_size * (1 - 1.0 / len(seen)) + + if fit_intercept: + gradient_correction = gradient - intercept_gradient_memory[idx] + intercept_gradient_memory[idx] = gradient + intercept_sum_gradient += gradient_correction + gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) + if saga: + intercept -= ( + step_size * intercept_sum_gradient / len(seen) * decay + ) + gradient_correction + else: + intercept -= step_size * intercept_sum_gradient / len(seen) * decay + + weights -= step_size * sum_gradient / len(seen) + + return weights, intercept + + +def sag_sparse( + X, + y, + step_size, + alpha, + n_iter=1, + dloss=None, + sample_weight=None, + sparse=False, + fit_intercept=True, + saga=False, + random_state=0, +): + if step_size * alpha == 1.0: + raise ZeroDivisionError( + "Sparse sag does not handle the case step_size * alpha == 1" + ) + n_samples, n_features = X.shape[0], X.shape[1] + + weights = np.zeros(n_features) + sum_gradient = np.zeros(n_features) + last_updated = np.zeros(n_features, dtype=int) + gradient_memory = np.zeros(n_samples) + rng = check_random_state(random_state) + intercept = 0.0 + intercept_sum_gradient = 0.0 + wscale = 1.0 + decay = 1.0 + seen = set() + + c_sum = np.zeros(n_iter * n_samples) + + # sparse data has a fixed decay of .01 + if sparse: + decay = 0.01 + + counter = 0 + for epoch in range(n_iter): + for k in range(n_samples): + # idx = k + idx = int(rng.rand() * n_samples) + entry = X[idx] + seen.add(idx) + + if counter >= 1: + for j in range(n_features): + if last_updated[j] == 0: + weights[j] -= c_sum[counter - 1] * sum_gradient[j] + else: + weights[j] -= ( + c_sum[counter - 1] - c_sum[last_updated[j] - 1] + ) * sum_gradient[j] + last_updated[j] = counter + + p = (wscale * np.dot(entry, weights)) + intercept + gradient = dloss(p, y[idx]) + + if sample_weight is not None: + gradient *= sample_weight[idx] + + update = entry * gradient + gradient_correction = update - (gradient_memory[idx] * entry) + sum_gradient += gradient_correction + if saga: + for j in range(n_features): + weights[j] -= ( + gradient_correction[j] + * step_size + * (1 - 1.0 / len(seen)) + / wscale + ) + + if fit_intercept: + gradient_correction = gradient - gradient_memory[idx] + intercept_sum_gradient += gradient_correction + gradient_correction *= step_size * (1.0 - 1.0 / len(seen)) + if saga: + intercept -= ( + step_size * intercept_sum_gradient / len(seen) * decay + ) + gradient_correction + else: + intercept -= step_size * intercept_sum_gradient / len(seen) * decay + + gradient_memory[idx] = gradient + + wscale *= 1.0 - alpha * step_size + if counter == 0: + c_sum[0] = step_size / (wscale * len(seen)) + else: + c_sum[counter] = c_sum[counter - 1] + step_size / (wscale * len(seen)) + + if counter >= 1 and wscale < 1e-9: + for j in range(n_features): + if last_updated[j] == 0: + weights[j] -= c_sum[counter] * sum_gradient[j] + else: + weights[j] -= ( + c_sum[counter] - c_sum[last_updated[j] - 1] + ) * sum_gradient[j] + last_updated[j] = counter + 1 + c_sum[counter] = 0 + weights *= wscale + wscale = 1.0 + + counter += 1 + + for j in range(n_features): + if last_updated[j] == 0: + weights[j] -= c_sum[counter - 1] * sum_gradient[j] + else: + weights[j] -= ( + c_sum[counter - 1] - c_sum[last_updated[j] - 1] + ) * sum_gradient[j] + weights *= wscale + return weights, intercept + + +def get_step_size(X, alpha, fit_intercept, classification=True): + if classification: + return 4.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + 4.0 * alpha) + else: + return 1.0 / (np.max(np.sum(X * X, axis=1)) + fit_intercept + alpha) + + +def test_classifier_matching(): + n_samples = 20 + X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) + # y must be 0 or 1 + alpha = 1.1 + fit_intercept = True + step_size = get_step_size(X, alpha, fit_intercept) + for solver in ["sag", "saga"]: + if solver == "sag": + n_iter = 80 + else: + # SAGA variance w.r.t. stream order is higher + n_iter = 300 + clf = LogisticRegression( + solver=solver, + fit_intercept=fit_intercept, + tol=1e-11, + C=1.0 / alpha / n_samples, + max_iter=n_iter, + random_state=10, + ) + clf.fit(X, y) + + weights, intercept = sag_sparse( + X, + 2 * y - 1, # y must be -1 or +1 + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + fit_intercept=fit_intercept, + saga=solver == "saga", + ) + weights2, intercept2 = sag( + X, + 2 * y - 1, # y must be -1 or +1 + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + fit_intercept=fit_intercept, + saga=solver == "saga", + ) + weights = np.atleast_2d(weights) + intercept = np.atleast_1d(intercept) + weights2 = np.atleast_2d(weights2) + intercept2 = np.atleast_1d(intercept2) + + assert_array_almost_equal(weights, clf.coef_, decimal=9) + assert_array_almost_equal(intercept, clf.intercept_, decimal=9) + assert_array_almost_equal(weights2, clf.coef_, decimal=9) + assert_array_almost_equal(intercept2, clf.intercept_, decimal=9) + + +def test_regressor_matching(): + n_samples = 10 + n_features = 5 + + rng = np.random.RandomState(10) + X = rng.normal(size=(n_samples, n_features)) + true_w = rng.normal(size=n_features) + y = X.dot(true_w) + + alpha = 1.0 + n_iter = 100 + fit_intercept = True + + step_size = get_step_size(X, alpha, fit_intercept, classification=False) + clf = Ridge( + fit_intercept=fit_intercept, + tol=0.00000000001, + solver="sag", + alpha=alpha * n_samples, + max_iter=n_iter, + ) + clf.fit(X, y) + + weights1, intercept1 = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=squared_dloss, + fit_intercept=fit_intercept, + ) + weights2, intercept2 = sag( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=squared_dloss, + fit_intercept=fit_intercept, + ) + + assert_allclose(weights1, clf.coef_) + assert_allclose(intercept1, clf.intercept_) + assert_allclose(weights2, clf.coef_) + assert_allclose(intercept2, clf.intercept_) + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_pobj_matches_logistic_regression(csr_container): + """tests if the sag pobj matches log reg""" + n_samples = 100 + alpha = 1.0 + max_iter = 20 + X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) + + clf1 = LogisticRegression( + solver="sag", + fit_intercept=False, + tol=0.0000001, + C=1.0 / alpha / n_samples, + max_iter=max_iter, + random_state=10, + ) + clf2 = clone(clf1) + clf3 = LogisticRegression( + fit_intercept=False, + tol=0.0000001, + C=1.0 / alpha / n_samples, + max_iter=max_iter, + random_state=10, + ) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + clf3.fit(X, y) + + pobj1 = get_pobj(clf1.coef_, alpha, X, y, log_loss) + pobj2 = get_pobj(clf2.coef_, alpha, X, y, log_loss) + pobj3 = get_pobj(clf3.coef_, alpha, X, y, log_loss) + + assert_array_almost_equal(pobj1, pobj2, decimal=4) + assert_array_almost_equal(pobj2, pobj3, decimal=4) + assert_array_almost_equal(pobj3, pobj1, decimal=4) + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_pobj_matches_ridge_regression(csr_container): + """tests if the sag pobj matches ridge reg""" + n_samples = 100 + n_features = 10 + alpha = 1.0 + n_iter = 100 + fit_intercept = False + rng = np.random.RandomState(10) + X = rng.normal(size=(n_samples, n_features)) + true_w = rng.normal(size=n_features) + y = X.dot(true_w) + + clf1 = Ridge( + fit_intercept=fit_intercept, + tol=0.00000000001, + solver="sag", + alpha=alpha, + max_iter=n_iter, + random_state=42, + ) + clf2 = clone(clf1) + clf3 = Ridge( + fit_intercept=fit_intercept, + tol=0.00001, + solver="lsqr", + alpha=alpha, + max_iter=n_iter, + random_state=42, + ) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + clf3.fit(X, y) + + pobj1 = get_pobj(clf1.coef_, alpha, X, y, squared_loss) + pobj2 = get_pobj(clf2.coef_, alpha, X, y, squared_loss) + pobj3 = get_pobj(clf3.coef_, alpha, X, y, squared_loss) + + assert_array_almost_equal(pobj1, pobj2, decimal=4) + assert_array_almost_equal(pobj1, pobj3, decimal=4) + assert_array_almost_equal(pobj3, pobj2, decimal=4) + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_regressor_computed_correctly(csr_container): + """tests if the sag regressor is computed correctly""" + alpha = 0.1 + n_features = 10 + n_samples = 40 + max_iter = 100 + tol = 0.000001 + fit_intercept = True + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + y = np.dot(X, w) + 2.0 + step_size = get_step_size(X, alpha, fit_intercept, classification=False) + + clf1 = Ridge( + fit_intercept=fit_intercept, + tol=tol, + solver="sag", + alpha=alpha * n_samples, + max_iter=max_iter, + random_state=rng, + ) + clf2 = clone(clf1) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + + spweights1, spintercept1 = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=max_iter, + dloss=squared_dloss, + fit_intercept=fit_intercept, + random_state=rng, + ) + + spweights2, spintercept2 = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=max_iter, + dloss=squared_dloss, + sparse=True, + fit_intercept=fit_intercept, + random_state=rng, + ) + + assert_array_almost_equal(clf1.coef_.ravel(), spweights1.ravel(), decimal=3) + assert_almost_equal(clf1.intercept_, spintercept1, decimal=1) + + # TODO: uncomment when sparse Ridge with intercept will be fixed (#4710) + # assert_array_almost_equal(clf2.coef_.ravel(), + # spweights2.ravel(), + # decimal=3) + # assert_almost_equal(clf2.intercept_, spintercept2, decimal=1)''' + + +def test_get_auto_step_size(): + X = np.array([[1, 2, 3], [2, 3, 4], [2, 3, 2]], dtype=np.float64) + alpha = 1.2 + fit_intercept = False + # sum the squares of the second sample because that's the largest + max_squared_sum = 4 + 9 + 16 + max_squared_sum_ = row_norms(X, squared=True).max() + n_samples = X.shape[0] + assert_almost_equal(max_squared_sum, max_squared_sum_, decimal=4) + + for saga in [True, False]: + for fit_intercept in (True, False): + if saga: + L_sqr = max_squared_sum + alpha + int(fit_intercept) + L_log = (max_squared_sum + 4.0 * alpha + int(fit_intercept)) / 4.0 + mun_sqr = min(2 * n_samples * alpha, L_sqr) + mun_log = min(2 * n_samples * alpha, L_log) + step_size_sqr = 1 / (2 * L_sqr + mun_sqr) + step_size_log = 1 / (2 * L_log + mun_log) + else: + step_size_sqr = 1.0 / (max_squared_sum + alpha + int(fit_intercept)) + step_size_log = 4.0 / ( + max_squared_sum + 4.0 * alpha + int(fit_intercept) + ) + + step_size_sqr_ = get_auto_step_size( + max_squared_sum_, + alpha, + "squared", + fit_intercept, + n_samples=n_samples, + is_saga=saga, + ) + step_size_log_ = get_auto_step_size( + max_squared_sum_, + alpha, + "log", + fit_intercept, + n_samples=n_samples, + is_saga=saga, + ) + + assert_almost_equal(step_size_sqr, step_size_sqr_, decimal=4) + assert_almost_equal(step_size_log, step_size_log_, decimal=4) + + msg = "Unknown loss function for SAG solver, got wrong instead of" + with pytest.raises(ValueError, match=msg): + get_auto_step_size(max_squared_sum_, alpha, "wrong", fit_intercept) + + +@pytest.mark.parametrize("seed", range(3)) # locally tested with 1000 seeds +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_regressor(seed, csr_container): + """tests if the sag regressor performs well""" + xmin, xmax = -5, 5 + n_samples = 300 + tol = 0.001 + max_iter = 100 + alpha = 0.1 + rng = np.random.RandomState(seed) + X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1) + + # simple linear function without noise + y = 0.5 * X.ravel() + + clf1 = Ridge( + tol=tol, + solver="sag", + max_iter=max_iter, + alpha=alpha * n_samples, + random_state=rng, + ) + clf2 = clone(clf1) + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + score1 = clf1.score(X, y) + score2 = clf2.score(X, y) + assert score1 > 0.98 + assert score2 > 0.98 + + # simple linear function with noise + y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel() + + clf1 = Ridge(tol=tol, solver="sag", max_iter=max_iter, alpha=alpha * n_samples) + clf2 = clone(clf1) + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + score1 = clf1.score(X, y) + score2 = clf2.score(X, y) + assert score1 > 0.45 + assert score2 > 0.45 + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_classifier_computed_correctly(csr_container): + """tests if the binary classifier is computed correctly""" + alpha = 0.1 + n_samples = 50 + n_iter = 50 + tol = 0.00001 + fit_intercept = True + X, y = make_blobs(n_samples=n_samples, centers=2, random_state=0, cluster_std=0.1) + step_size = get_step_size(X, alpha, fit_intercept, classification=True) + classes = np.unique(y) + y_tmp = np.ones(n_samples) + y_tmp[y != classes[1]] = -1 + y = y_tmp + + clf1 = LogisticRegression( + solver="sag", + C=1.0 / alpha / n_samples, + max_iter=n_iter, + tol=tol, + random_state=77, + fit_intercept=fit_intercept, + ) + clf2 = clone(clf1) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + + spweights, spintercept = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + fit_intercept=fit_intercept, + ) + spweights2, spintercept2 = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + sparse=True, + fit_intercept=fit_intercept, + ) + + assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) + assert_almost_equal(clf1.intercept_, spintercept, decimal=1) + + assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) + assert_almost_equal(clf2.intercept_, spintercept2, decimal=1) + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sag_multiclass_computed_correctly(csr_container): + """tests if the multiclass classifier is computed correctly""" + alpha = 0.1 + n_samples = 20 + tol = 1e-5 + max_iter = 70 + fit_intercept = True + X, y = make_blobs(n_samples=n_samples, centers=3, random_state=0, cluster_std=0.1) + step_size = get_step_size(X, alpha, fit_intercept, classification=True) + classes = np.unique(y) + + clf1 = OneVsRestClassifier( + LogisticRegression( + solver="sag", + C=1.0 / alpha / n_samples, + max_iter=max_iter, + tol=tol, + random_state=77, + fit_intercept=fit_intercept, + ) + ) + clf2 = clone(clf1) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + + coef1 = [] + intercept1 = [] + coef2 = [] + intercept2 = [] + for cl in classes: + y_encoded = np.ones(n_samples) + y_encoded[y != cl] = -1 + + spweights1, spintercept1 = sag_sparse( + X, + y_encoded, + step_size, + alpha, + dloss=log_dloss, + n_iter=max_iter, + fit_intercept=fit_intercept, + ) + spweights2, spintercept2 = sag_sparse( + X, + y_encoded, + step_size, + alpha, + dloss=log_dloss, + n_iter=max_iter, + sparse=True, + fit_intercept=fit_intercept, + ) + coef1.append(spweights1) + intercept1.append(spintercept1) + + coef2.append(spweights2) + intercept2.append(spintercept2) + + coef1 = np.vstack(coef1) + intercept1 = np.array(intercept1) + coef2 = np.vstack(coef2) + intercept2 = np.array(intercept2) + + for i, cl in enumerate(classes): + assert_allclose(clf1.estimators_[i].coef_.ravel(), coef1[i], rtol=1e-2) + assert_allclose(clf1.estimators_[i].intercept_, intercept1[i], rtol=1e-1) + + assert_allclose(clf2.estimators_[i].coef_.ravel(), coef2[i], rtol=1e-2) + # Note the very crude accuracy, i.e. high rtol. + assert_allclose(clf2.estimators_[i].intercept_, intercept2[i], rtol=5e-1) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_classifier_results(csr_container): + """tests if classifier results match target""" + alpha = 0.1 + n_features = 20 + n_samples = 10 + tol = 0.01 + max_iter = 200 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + y = np.dot(X, w) + y = np.sign(y) + clf1 = LogisticRegression( + solver="sag", + C=1.0 / alpha / n_samples, + max_iter=max_iter, + tol=tol, + random_state=77, + ) + clf2 = clone(clf1) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + pred1 = clf1.predict(X) + pred2 = clf2.predict(X) + assert_almost_equal(pred1, y, decimal=12) + assert_almost_equal(pred2, y, decimal=12) + + +@pytest.mark.filterwarnings("ignore:The max_iter was reached") +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_binary_classifier_class_weight(csr_container): + """tests binary classifier with classweights for each class""" + alpha = 0.1 + n_samples = 50 + n_iter = 20 + tol = 0.00001 + fit_intercept = True + X, y = make_blobs(n_samples=n_samples, centers=2, random_state=10, cluster_std=0.1) + step_size = get_step_size(X, alpha, fit_intercept, classification=True) + classes = np.unique(y) + y_tmp = np.ones(n_samples) + y_tmp[y != classes[1]] = -1 + y = y_tmp + + class_weight = {1: 0.45, -1: 0.55} + clf1 = LogisticRegression( + solver="sag", + C=1.0 / alpha / n_samples, + max_iter=n_iter, + tol=tol, + random_state=77, + fit_intercept=fit_intercept, + class_weight=class_weight, + ) + clf2 = clone(clf1) + + clf1.fit(X, y) + clf2.fit(csr_container(X), y) + + le = LabelEncoder() + class_weight_ = compute_class_weight(class_weight, classes=np.unique(y), y=y) + sample_weight = class_weight_[le.fit_transform(y)] + spweights, spintercept = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + sample_weight=sample_weight, + fit_intercept=fit_intercept, + ) + spweights2, spintercept2 = sag_sparse( + X, + y, + step_size, + alpha, + n_iter=n_iter, + dloss=log_dloss, + sparse=True, + sample_weight=sample_weight, + fit_intercept=fit_intercept, + ) + + assert_array_almost_equal(clf1.coef_.ravel(), spweights.ravel(), decimal=2) + assert_almost_equal(clf1.intercept_, spintercept, decimal=1) + + assert_array_almost_equal(clf2.coef_.ravel(), spweights2.ravel(), decimal=2) + assert_almost_equal(clf2.intercept_, spintercept2, decimal=1) + + +def test_classifier_single_class(): + """tests if ValueError is thrown with only one class""" + X = [[1, 2], [3, 4]] + y = [1, 1] + + msg = "This solver needs samples of at least 2 classes in the data" + with pytest.raises(ValueError, match=msg): + LogisticRegression(solver="sag").fit(X, y) + + +def test_step_size_alpha_error(): + X = [[0, 0], [0, 0]] + y = [1, -1] + fit_intercept = False + alpha = 1.0 + msg = re.escape( + "Current sag implementation does not handle the case" + " step_size * alpha_scaled == 1" + ) + + clf1 = LogisticRegression(solver="sag", C=1.0 / alpha, fit_intercept=fit_intercept) + with pytest.raises(ZeroDivisionError, match=msg): + clf1.fit(X, y) + + clf2 = Ridge(fit_intercept=fit_intercept, solver="sag", alpha=alpha) + with pytest.raises(ZeroDivisionError, match=msg): + clf2.fit(X, y) + + +@pytest.mark.parametrize("solver", ["sag", "saga"]) +def test_sag_classifier_raises_error(solver): + # Following #13316, the error handling behavior changed in cython sag. This + # is simply a non-regression test to make sure numerical errors are + # properly raised. + + # Train a classifier on a simple problem + rng = np.random.RandomState(42) + X, y = make_classification(random_state=rng) + clf = LogisticRegression(solver=solver, random_state=rng, warm_start=True) + clf.fit(X, y) + + # Trigger a numerical error by: + # - corrupting the fitted coefficients of the classifier + # - fit it again starting from its current state thanks to warm_start + clf.coef_[:] = np.nan + + with pytest.raises(ValueError, match="Floating-point under-/overflow"): + clf.fit(X, y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sgd.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..26d138ae3649b22c4848dcacae1391a399e72fcd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sgd.py @@ -0,0 +1,2195 @@ +import pickle +from unittest.mock import Mock + +import joblib +import numpy as np +import pytest +import scipy.sparse as sp + +from sklearn import datasets, linear_model, metrics +from sklearn.base import clone, is_classifier +from sklearn.exceptions import ConvergenceWarning +from sklearn.kernel_approximation import Nystroem +from sklearn.linear_model import _sgd_fast as sgd_fast +from sklearn.linear_model import _stochastic_gradient +from sklearn.model_selection import ( + RandomizedSearchCV, + ShuffleSplit, + StratifiedShuffleSplit, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler, scale +from sklearn.svm import OneClassSVM +from sklearn.utils import get_tags +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) + + +def _update_kwargs(kwargs): + if "random_state" not in kwargs: + kwargs["random_state"] = 42 + + if "tol" not in kwargs: + kwargs["tol"] = None + if "max_iter" not in kwargs: + kwargs["max_iter"] = 5 + + +class _SparseSGDClassifier(linear_model.SGDClassifier): + def fit(self, X, y, *args, **kw): + X = sp.csr_matrix(X) + return super().fit(X, y, *args, **kw) + + def partial_fit(self, X, y, *args, **kw): + X = sp.csr_matrix(X) + return super().partial_fit(X, y, *args, **kw) + + def decision_function(self, X): + X = sp.csr_matrix(X) + return super().decision_function(X) + + def predict_proba(self, X): + X = sp.csr_matrix(X) + return super().predict_proba(X) + + +class _SparseSGDRegressor(linear_model.SGDRegressor): + def fit(self, X, y, *args, **kw): + X = sp.csr_matrix(X) + return linear_model.SGDRegressor.fit(self, X, y, *args, **kw) + + def partial_fit(self, X, y, *args, **kw): + X = sp.csr_matrix(X) + return linear_model.SGDRegressor.partial_fit(self, X, y, *args, **kw) + + def decision_function(self, X, *args, **kw): + # XXX untested as of v0.22 + X = sp.csr_matrix(X) + return linear_model.SGDRegressor.decision_function(self, X, *args, **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) + + +def SGDRegressor(**kwargs): + _update_kwargs(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) + + +def SparseSGDRegressor(**kwargs): + _update_kwargs(kwargs) + return _SparseSGDRegressor(**kwargs) + + +def SparseSGDOneClassSVM(**kwargs): + _update_kwargs(kwargs) + return _SparseSGDOneClassSVM(**kwargs) + + +# Test Data + +# test sample 1 +X = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) +Y = [1, 1, 1, 2, 2, 2] +T = np.array([[-1, -1], [2, 2], [3, 2]]) +true_result = [1, 2, 2] + +# test sample 2; string class labels +X2 = np.array( + [ + [-1, 1], + [-0.75, 0.5], + [-1.5, 1.5], + [1, 1], + [0.75, 0.5], + [1.5, 1.5], + [-1, -1], + [0, -0.5], + [1, -1], + ] +) +Y2 = ["one"] * 3 + ["two"] * 3 + ["three"] * 3 +T2 = np.array([[-1.5, 0.5], [1, 2], [0, -2]]) +true_result2 = ["one", "two", "three"] + +# test sample 3 +X3 = np.array( + [ + [1, 1, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 0, 0, 1, 1], + [0, 0, 0, 0, 1, 1], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 0, 0], + ] +) +Y3 = np.array([1, 1, 1, 1, 2, 2, 2, 2]) + +# test sample 4 - two more or less redundant feature groups +X4 = np.array( + [ + [1, 0.9, 0.8, 0, 0, 0], + [1, 0.84, 0.98, 0, 0, 0], + [1, 0.96, 0.88, 0, 0, 0], + [1, 0.91, 0.99, 0, 0, 0], + [0, 0, 0, 0.89, 0.91, 1], + [0, 0, 0, 0.79, 0.84, 1], + [0, 0, 0, 0.91, 0.95, 1], + [0, 0, 0, 0.93, 1, 1], + ] +) +Y4 = np.array([1, 1, 1, 1, 2, 2, 2, 2]) + +iris = datasets.load_iris() + +# test sample 5 - test sample 1 as binary classification problem +X5 = np.array([[-2, -1], [-1, -1], [-1, -2], [1, 1], [1, 2], [2, 1]]) +Y5 = [1, 1, 1, 2, 2, 2] +true_result5 = [0, 1, 1] + + +############################################################################### +# Common Test Case to classification and regression + + +# a simple implementation of ASGD to use for testing +# uses squared loss to find the gradient +def asgd(klass, X, y, eta, alpha, weight_init=None, intercept_init=0.0): + if weight_init is None: + weights = np.zeros(X.shape[1]) + else: + weights = weight_init + + average_weights = np.zeros(X.shape[1]) + intercept = intercept_init + average_intercept = 0.0 + decay = 1.0 + + # sparse data has a fixed decay of .01 + if klass in (SparseSGDClassifier, SparseSGDRegressor): + decay = 0.01 + + for i, entry in enumerate(X): + p = np.dot(entry, weights) + p += intercept + gradient = p - y[i] + weights *= 1.0 - (eta * alpha) + weights += -(eta * gradient * entry) + intercept += -(eta * gradient) * decay + + average_weights *= i + average_weights += weights + average_weights /= i + 1.0 + + average_intercept *= i + average_intercept += intercept + average_intercept /= i + 1.0 + + return average_weights, average_intercept + + +def _test_warm_start(klass, X, Y, lr): + # Test that explicit warm restart... + clf = klass(alpha=0.01, eta0=0.01, shuffle=False, learning_rate=lr) + clf.fit(X, Y) + + clf2 = klass(alpha=0.001, eta0=0.01, shuffle=False, learning_rate=lr) + clf2.fit(X, Y, coef_init=clf.coef_.copy(), intercept_init=clf.intercept_.copy()) + + # ... and implicit warm restart are equivalent. + clf3 = klass( + alpha=0.01, eta0=0.01, shuffle=False, warm_start=True, learning_rate=lr + ) + clf3.fit(X, Y) + + assert clf3.t_ == clf.t_ + assert_array_almost_equal(clf3.coef_, clf.coef_) + + clf3.set_params(alpha=0.001) + clf3.fit(X, Y) + + assert clf3.t_ == clf2.t_ + assert_array_almost_equal(clf3.coef_, clf2.coef_) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +@pytest.mark.parametrize("lr", ["constant", "optimal", "invscaling", "adaptive"]) +def test_warm_start(klass, lr): + _test_warm_start(klass, X, Y, lr) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_input_format(klass): + # Input format tests. + clf = klass(alpha=0.01, shuffle=False) + clf.fit(X, Y) + Y_ = np.array(Y)[:, np.newaxis] + + Y_ = np.c_[Y_, Y_] + with pytest.raises(ValueError): + clf.fit(X, Y_) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_clone(klass): + # Test whether clone works ok. + clf = klass(alpha=0.01, penalty="l1") + clf = clone(clf) + clf.set_params(penalty="l2") + clf.fit(X, Y) + + clf2 = klass(alpha=0.01, penalty="l2") + clf2.fit(X, Y) + + assert_array_equal(clf.coef_, clf2.coef_) + + +@pytest.mark.parametrize( + "klass", + [ + SGDClassifier, + SparseSGDClassifier, + SGDRegressor, + SparseSGDRegressor, + SGDOneClassSVM, + SparseSGDOneClassSVM, + ], +) +def test_plain_has_no_average_attr(klass): + clf = klass(average=True, eta0=0.01) + clf.fit(X, Y) + + assert hasattr(clf, "_average_coef") + assert hasattr(clf, "_average_intercept") + assert hasattr(clf, "_standard_intercept") + assert hasattr(clf, "_standard_coef") + + clf = klass() + clf.fit(X, Y) + + assert not hasattr(clf, "_average_coef") + assert not hasattr(clf, "_average_intercept") + assert not hasattr(clf, "_standard_intercept") + assert not hasattr(clf, "_standard_coef") + + +@pytest.mark.parametrize( + "klass", + [ + SGDClassifier, + SparseSGDClassifier, + SGDRegressor, + SparseSGDRegressor, + SGDOneClassSVM, + SparseSGDOneClassSVM, + ], +) +def test_late_onset_averaging_not_reached(klass): + clf1 = klass(average=600) + clf2 = klass() + for _ in range(100): + if is_classifier(clf1): + clf1.partial_fit(X, Y, classes=np.unique(Y)) + clf2.partial_fit(X, Y, classes=np.unique(Y)) + else: + clf1.partial_fit(X, Y) + clf2.partial_fit(X, Y) + + assert_array_almost_equal(clf1.coef_, clf2.coef_, 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, SGDRegressor, SparseSGDRegressor] +) +def test_late_onset_averaging_reached(klass): + eta0 = 0.001 + alpha = 0.0001 + Y_encode = np.array(Y) + Y_encode[Y_encode == 1] = -1.0 + Y_encode[Y_encode == 2] = 1.0 + + clf1 = klass( + average=7, + learning_rate="constant", + loss="squared_error", + eta0=eta0, + alpha=alpha, + max_iter=2, + shuffle=False, + ) + clf2 = klass( + average=False, + learning_rate="constant", + loss="squared_error", + eta0=eta0, + alpha=alpha, + max_iter=1, + shuffle=False, + ) + + clf1.fit(X, Y_encode) + clf2.fit(X, Y_encode) + + average_weights, average_intercept = asgd( + klass, + X, + Y_encode, + eta0, + alpha, + weight_init=clf2.coef_.ravel(), + intercept_init=clf2.intercept_, + ) + + assert_array_almost_equal(clf1.coef_.ravel(), average_weights.ravel(), decimal=16) + assert_almost_equal(clf1.intercept_, average_intercept, decimal=16) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_early_stopping(klass): + X = iris.data[iris.target > 0] + Y = iris.target[iris.target > 0] + for early_stopping in [True, False]: + max_iter = 1000 + clf = klass(early_stopping=early_stopping, tol=1e-3, max_iter=max_iter).fit( + X, Y + ) + assert clf.n_iter_ < max_iter + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_adaptive_longer_than_constant(klass): + clf1 = klass(learning_rate="adaptive", eta0=0.01, tol=1e-3, max_iter=100) + clf1.fit(iris.data, iris.target) + clf2 = klass(learning_rate="constant", eta0=0.01, tol=1e-3, max_iter=100) + clf2.fit(iris.data, iris.target) + assert clf1.n_iter_ > clf2.n_iter_ + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_validation_set_not_used_for_training(klass): + X, Y = iris.data, iris.target + validation_fraction = 0.4 + seed = 42 + shuffle = False + max_iter = 10 + clf1 = klass( + early_stopping=True, + random_state=np.random.RandomState(seed), + validation_fraction=validation_fraction, + learning_rate="constant", + eta0=0.01, + tol=None, + max_iter=max_iter, + shuffle=shuffle, + ) + clf1.fit(X, Y) + assert clf1.n_iter_ == max_iter + + clf2 = klass( + early_stopping=False, + random_state=np.random.RandomState(seed), + learning_rate="constant", + eta0=0.01, + tol=None, + max_iter=max_iter, + shuffle=shuffle, + ) + + if is_classifier(clf2): + cv = StratifiedShuffleSplit(test_size=validation_fraction, random_state=seed) + else: + cv = ShuffleSplit(test_size=validation_fraction, random_state=seed) + idx_train, idx_val = next(cv.split(X, Y)) + idx_train = np.sort(idx_train) # remove shuffling + clf2.fit(X[idx_train], Y[idx_train]) + assert clf2.n_iter_ == max_iter + + assert_array_equal(clf1.coef_, clf2.coef_) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_n_iter_no_change(klass): + X, Y = iris.data, iris.target + # test that n_iter_ increases monotonically with n_iter_no_change + for early_stopping in [True, False]: + n_iter_list = [ + klass( + early_stopping=early_stopping, + n_iter_no_change=n_iter_no_change, + tol=1e-4, + max_iter=1000, + ) + .fit(X, Y) + .n_iter_ + for n_iter_no_change in [2, 3, 10] + ] + assert_array_equal(n_iter_list, sorted(n_iter_list)) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_not_enough_sample_for_early_stopping(klass): + # test an error is raised if the training or validation set is empty + clf = klass(early_stopping=True, validation_fraction=0.99) + with pytest.raises(ValueError): + clf.fit(X3, Y3) + + +@pytest.mark.parametrize("Estimator", [SGDClassifier, SGDRegressor]) +@pytest.mark.parametrize("l1_ratio", [0, 0.7, 1]) +def test_sgd_l1_ratio_not_used(Estimator, l1_ratio): + """Check that l1_ratio is not used when penalty is not 'elasticnet'""" + clf1 = Estimator(penalty="l1", l1_ratio=None, random_state=0).fit(X, Y) + clf2 = Estimator(penalty="l1", l1_ratio=l1_ratio, random_state=0).fit(X, Y) + + assert_allclose(clf1.coef_, clf2.coef_) + + +@pytest.mark.parametrize( + "Estimator", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_sgd_failing_penalty_validation(Estimator): + clf = Estimator(penalty="elasticnet", l1_ratio=None) + with pytest.raises( + ValueError, match="l1_ratio must be set when penalty is 'elasticnet'" + ): + clf.fit(X, Y) + + +############################################################################### +# Classification Test Case + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_clf(klass): + # Check that SGD gives any results :-) + + for loss in ("hinge", "squared_hinge", "log_loss", "modified_huber"): + clf = klass( + penalty="l2", + alpha=0.01, + fit_intercept=True, + loss=loss, + max_iter=10, + shuffle=True, + ) + clf.fit(X, Y) + # assert_almost_equal(clf.coef_[0], clf.coef_[1], decimal=7) + assert_array_equal(clf.predict(T), true_result) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDOneClassSVM, SparseSGDOneClassSVM] +) +def test_provide_coef(klass): + """Check that the shape of `coef_init` is validated.""" + with pytest.raises(ValueError, match="Provided coef_init does not match dataset"): + klass().fit(X, Y, coef_init=np.zeros((3,))) + + +@pytest.mark.parametrize( + "klass, fit_params", + [ + (SGDClassifier, {"intercept_init": np.zeros((3,))}), + (SparseSGDClassifier, {"intercept_init": np.zeros((3,))}), + (SGDOneClassSVM, {"offset_init": np.zeros((3,))}), + (SparseSGDOneClassSVM, {"offset_init": np.zeros((3,))}), + ], +) +def test_set_intercept_offset(klass, fit_params): + """Check that `intercept_init` or `offset_init` is validated.""" + sgd_estimator = klass() + with pytest.raises(ValueError, match="does not match dataset"): + sgd_estimator.fit(X, Y, **fit_params) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDRegressor, SparseSGDRegressor] +) +def test_sgd_early_stopping_with_partial_fit(klass): + """Check that we raise an error for `early_stopping` used with + `partial_fit`. + """ + err_msg = "early_stopping should be False with partial_fit" + with pytest.raises(ValueError, match=err_msg): + klass(early_stopping=True).partial_fit(X, Y) + + +@pytest.mark.parametrize( + "klass, fit_params", + [ + (SGDClassifier, {"intercept_init": 0}), + (SparseSGDClassifier, {"intercept_init": 0}), + (SGDOneClassSVM, {"offset_init": 0}), + (SparseSGDOneClassSVM, {"offset_init": 0}), + ], +) +def test_set_intercept_offset_binary(klass, fit_params): + """Check that we can pass a scaler with binary classification to + `intercept_init` or `offset_init`.""" + klass().fit(X5, Y5, **fit_params) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_average_binary_computed_correctly(klass): + # Checks the SGDClassifier correctly computes the average weights + eta = 0.1 + alpha = 2.0 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + clf = klass( + loss="squared_error", + learning_rate="constant", + eta0=eta, + alpha=alpha, + fit_intercept=True, + max_iter=1, + average=True, + shuffle=False, + ) + + # simple linear function without noise + y = np.dot(X, w) + y = np.sign(y) + + clf.fit(X, y) + + average_weights, average_intercept = asgd(klass, X, y, eta, alpha) + average_weights = average_weights.reshape(1, -1) + assert_array_almost_equal(clf.coef_, average_weights, decimal=14) + assert_almost_equal(clf.intercept_, average_intercept, decimal=14) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_set_intercept_to_intercept(klass): + # Checks intercept_ shape consistency for the warm starts + # Inconsistent intercept_ shape. + clf = klass().fit(X5, Y5) + klass().fit(X5, Y5, intercept_init=clf.intercept_) + clf = klass().fit(X, Y) + klass().fit(X, Y, intercept_init=clf.intercept_) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_at_least_two_labels(klass): + # Target must have at least two labels + clf = klass(alpha=0.01, max_iter=20) + with pytest.raises(ValueError): + clf.fit(X2, np.ones(9)) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_partial_fit_weight_class_balanced(klass): + # partial_fit with class_weight='balanced' not supported""" + regex = ( + r"class_weight 'balanced' is not supported for " + r"partial_fit\. In order to use 'balanced' weights, " + r"use compute_class_weight\('balanced', classes=classes, y=y\). " + r"In place of y you can use a large enough sample " + r"of the full training set target to properly " + r"estimate the class frequency distributions\. " + r"Pass the resulting weights as the class_weight " + r"parameter\." + ) + with pytest.raises(ValueError, match=regex): + klass(class_weight="balanced").partial_fit(X, Y, classes=np.unique(Y)) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_multiclass(klass): + # Multi-class test case + clf = klass(alpha=0.01, max_iter=20).fit(X2, Y2) + assert clf.coef_.shape == (3, 2) + assert clf.intercept_.shape == (3,) + assert clf.decision_function([[0, 0]]).shape == (1, 3) + pred = clf.predict(T2) + assert_array_equal(pred, true_result2) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_multiclass_average(klass): + eta = 0.001 + alpha = 0.01 + # Multi-class average test case + clf = klass( + loss="squared_error", + learning_rate="constant", + eta0=eta, + alpha=alpha, + fit_intercept=True, + max_iter=1, + average=True, + shuffle=False, + ) + + np_Y2 = np.array(Y2) + clf.fit(X2, np_Y2) + classes = np.unique(np_Y2) + + for i, cl in enumerate(classes): + y_i = np.ones(np_Y2.shape[0]) + y_i[np_Y2 != cl] = -1 + average_coef, average_intercept = asgd(klass, X2, y_i, eta, alpha) + assert_array_almost_equal(average_coef, clf.coef_[i], decimal=16) + assert_almost_equal(average_intercept, clf.intercept_[i], decimal=16) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_multiclass_with_init_coef(klass): + # Multi-class test case + clf = klass(alpha=0.01, max_iter=20) + clf.fit(X2, Y2, coef_init=np.zeros((3, 2)), intercept_init=np.zeros(3)) + assert clf.coef_.shape == (3, 2) + assert clf.intercept_.shape, (3,) + pred = clf.predict(T2) + assert_array_equal(pred, true_result2) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_multiclass_njobs(klass): + # Multi-class test case with multi-core support + clf = klass(alpha=0.01, max_iter=20, n_jobs=2).fit(X2, Y2) + assert clf.coef_.shape == (3, 2) + assert clf.intercept_.shape == (3,) + assert clf.decision_function([[0, 0]]).shape == (1, 3) + pred = clf.predict(T2) + assert_array_equal(pred, true_result2) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_set_coef_multiclass(klass): + # Checks coef_init and intercept_init shape for multi-class + # problems + # Provided coef_ does not match dataset + clf = klass() + with pytest.raises(ValueError): + clf.fit(X2, Y2, coef_init=np.zeros((2, 2))) + + # Provided coef_ does match dataset + clf = klass().fit(X2, Y2, coef_init=np.zeros((3, 2))) + + # Provided intercept_ does not match dataset + clf = klass() + with pytest.raises(ValueError): + clf.fit(X2, Y2, intercept_init=np.zeros((1,))) + + # Provided intercept_ does match dataset. + clf = klass().fit(X2, Y2, intercept_init=np.zeros((3,))) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_predict_proba_method_access(klass): + # Checks that SGDClassifier predict_proba and predict_log_proba methods + # can either be accessed or raise an appropriate error message + # otherwise. See + # https://github.com/scikit-learn/scikit-learn/issues/10938 for more + # details. + for loss in linear_model.SGDClassifier.loss_functions: + clf = SGDClassifier(loss=loss) + if loss in ("log_loss", "modified_huber"): + assert hasattr(clf, "predict_proba") + assert hasattr(clf, "predict_log_proba") + else: + inner_msg = "probability estimates are not available for loss={!r}".format( + loss + ) + assert not hasattr(clf, "predict_proba") + assert not hasattr(clf, "predict_log_proba") + with pytest.raises( + AttributeError, match="has no attribute 'predict_proba'" + ) as exec_info: + clf.predict_proba + + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg in str(exec_info.value.__cause__) + + with pytest.raises( + AttributeError, match="has no attribute 'predict_log_proba'" + ) as exec_info: + clf.predict_log_proba + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg in str(exec_info.value.__cause__) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_proba(klass): + # Check SGD.predict_proba + + # Hinge loss does not allow for conditional prob estimate. + # We cannot use the factory here, because it defines predict_proba + # anyway. + clf = SGDClassifier(loss="hinge", alpha=0.01, max_iter=10, tol=None).fit(X, Y) + assert not hasattr(clf, "predict_proba") + assert not hasattr(clf, "predict_log_proba") + + # log and modified_huber losses can output probability estimates + # binary case + for loss in ["log_loss", "modified_huber"]: + clf = klass(loss=loss, alpha=0.01, max_iter=10) + clf.fit(X, Y) + p = clf.predict_proba([[3, 2]]) + assert p[0, 1] > 0.5 + p = clf.predict_proba([[-1, -1]]) + assert p[0, 1] < 0.5 + + # If predict_proba is 0, we get "RuntimeWarning: divide by zero encountered + # in log". We avoid it here. + with np.errstate(divide="ignore"): + p = clf.predict_log_proba([[3, 2]]) + assert p[0, 1] > p[0, 0] + p = clf.predict_log_proba([[-1, -1]]) + assert p[0, 1] < p[0, 0] + + # log loss multiclass probability estimates + clf = klass(loss="log_loss", alpha=0.01, max_iter=10).fit(X2, Y2) + + d = clf.decision_function([[0.1, -0.1], [0.3, 0.2]]) + p = clf.predict_proba([[0.1, -0.1], [0.3, 0.2]]) + assert_array_equal(np.argmax(p, axis=1), np.argmax(d, axis=1)) + assert_almost_equal(p[0].sum(), 1) + assert np.all(p[0] >= 0) + + p = clf.predict_proba([[-1, -1]]) + d = clf.decision_function([[-1, -1]]) + assert_array_equal(np.argsort(p[0]), np.argsort(d[0])) + + lp = clf.predict_log_proba([[3, 2]]) + p = clf.predict_proba([[3, 2]]) + assert_array_almost_equal(np.log(p), lp) + + lp = clf.predict_log_proba([[-1, -1]]) + p = clf.predict_proba([[-1, -1]]) + assert_array_almost_equal(np.log(p), lp) + + # Modified Huber multiclass probability estimates; requires a separate + # test because the hard zero/one probabilities may destroy the + # ordering present in decision_function output. + clf = klass(loss="modified_huber", alpha=0.01, max_iter=10) + clf.fit(X2, Y2) + d = clf.decision_function([[3, 2]]) + p = clf.predict_proba([[3, 2]]) + if klass != SparseSGDClassifier: + assert np.argmax(d, axis=1) == np.argmax(p, axis=1) + else: # XXX the sparse test gets a different X2 (?) + assert np.argmin(d, axis=1) == np.argmin(p, axis=1) + + # the following sample produces decision_function values < -1, + # which would cause naive normalization to fail (see comment + # in SGDClassifier.predict_proba) + x = X.mean(axis=0) + d = clf.decision_function([x]) + if np.all(d < -1): # XXX not true in sparse test case (why?) + p = clf.predict_proba([x]) + assert_array_almost_equal(p[0], [1 / 3.0] * 3) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sgd_l1(klass): + # Test L1 regularization + n = len(X4) + rng = np.random.RandomState(13) + idx = np.arange(n) + rng.shuffle(idx) + + X = X4[idx, :] + Y = Y4[idx] + + clf = klass( + penalty="l1", + alpha=0.2, + fit_intercept=False, + max_iter=2000, + tol=None, + shuffle=False, + ) + clf.fit(X, Y) + assert_array_equal(clf.coef_[0, 1:-1], np.zeros((4,))) + pred = clf.predict(X) + assert_array_equal(pred, Y) + + # test sparsify with dense inputs + clf.sparsify() + assert sp.issparse(clf.coef_) + pred = clf.predict(X) + assert_array_equal(pred, Y) + + # pickle and unpickle with sparse coef_ + clf = pickle.loads(pickle.dumps(clf)) + assert sp.issparse(clf.coef_) + pred = clf.predict(X) + assert_array_equal(pred, Y) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_class_weights(klass): + # Test class weights. + 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] + + clf = klass(alpha=0.1, max_iter=1000, fit_intercept=False, class_weight=None) + clf.fit(X, y) + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1])) + + # we give a small weights to class 1 + clf = klass(alpha=0.1, max_iter=1000, fit_intercept=False, class_weight={1: 0.001}) + clf.fit(X, y) + + # now the hyperplane should rotate clock-wise and + # the prediction on this point should shift + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_equal_class_weight(klass): + # Test if equal class weights approx. equals no class weights. + X = [[1, 0], [1, 0], [0, 1], [0, 1]] + y = [0, 0, 1, 1] + clf = klass(alpha=0.1, max_iter=1000, class_weight=None) + clf.fit(X, y) + + X = [[1, 0], [0, 1]] + y = [0, 1] + clf_weighted = klass(alpha=0.1, max_iter=1000, class_weight={0: 0.5, 1: 0.5}) + clf_weighted.fit(X, y) + + # should be similar up to some epsilon due to learning rate schedule + assert_almost_equal(clf.coef_, clf_weighted.coef_, decimal=2) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_wrong_class_weight_label(klass): + # ValueError due to not existing class label. + clf = klass(alpha=0.1, max_iter=1000, class_weight={0: 0.5}) + with pytest.raises(ValueError): + clf.fit(X, Y) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_weights_multiplied(klass): + # Tests that class_weight and sample_weight are multiplicative + class_weights = {1: 0.6, 2: 0.3} + rng = np.random.RandomState(0) + sample_weights = rng.random_sample(Y4.shape[0]) + multiplied_together = np.copy(sample_weights) + multiplied_together[Y4 == 1] *= class_weights[1] + multiplied_together[Y4 == 2] *= class_weights[2] + + clf1 = klass(alpha=0.1, max_iter=20, class_weight=class_weights) + clf2 = klass(alpha=0.1, max_iter=20) + + clf1.fit(X4, Y4, sample_weight=sample_weights) + clf2.fit(X4, Y4, sample_weight=multiplied_together) + + assert_almost_equal(clf1.coef_, clf2.coef_) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_balanced_weight(klass): + # Test class weights for imbalanced data""" + # compute reference metrics on iris dataset that is quite balanced by + # default + X, y = iris.data, iris.target + X = scale(X) + idx = np.arange(X.shape[0]) + rng = np.random.RandomState(6) + rng.shuffle(idx) + X = X[idx] + y = y[idx] + clf = klass(alpha=0.0001, max_iter=1000, class_weight=None, shuffle=False).fit(X, y) + f1 = metrics.f1_score(y, clf.predict(X), average="weighted") + assert_almost_equal(f1, 0.96, decimal=1) + + # make the same prediction using balanced class_weight + clf_balanced = klass( + alpha=0.0001, max_iter=1000, class_weight="balanced", shuffle=False + ).fit(X, y) + f1 = metrics.f1_score(y, clf_balanced.predict(X), average="weighted") + assert_almost_equal(f1, 0.96, decimal=1) + + # Make sure that in the balanced case it does not change anything + # to use "balanced" + assert_array_almost_equal(clf.coef_, clf_balanced.coef_, 6) + + # build an very very imbalanced dataset out of iris data + X_0 = X[y == 0, :] + y_0 = y[y == 0] + + X_imbalanced = np.vstack([X] + [X_0] * 10) + y_imbalanced = np.concatenate([y] + [y_0] * 10) + + # fit a model on the imbalanced data without class weight info + clf = klass(max_iter=1000, class_weight=None, shuffle=False) + clf.fit(X_imbalanced, y_imbalanced) + y_pred = clf.predict(X) + assert metrics.f1_score(y, y_pred, average="weighted") < 0.96 + + # fit a model with balanced class_weight enabled + clf = klass(max_iter=1000, class_weight="balanced", shuffle=False) + clf.fit(X_imbalanced, y_imbalanced) + y_pred = clf.predict(X) + assert metrics.f1_score(y, y_pred, average="weighted") > 0.96 + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_sample_weights(klass): + # Test weights on individual samples + 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] + + clf = klass(alpha=0.1, max_iter=1000, fit_intercept=False) + clf.fit(X, y) + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([1])) + + # we give a small weights to class 1 + clf.fit(X, y, sample_weight=[0.001] * 3 + [1] * 2) + + # now the hyperplane should rotate clock-wise and + # the prediction on this point should shift + assert_array_equal(clf.predict([[0.2, -1.0]]), np.array([-1])) + + +@pytest.mark.parametrize( + "klass", [SGDClassifier, SparseSGDClassifier, SGDOneClassSVM, SparseSGDOneClassSVM] +) +def test_wrong_sample_weights(klass): + # Test if ValueError is raised if sample_weight has wrong shape + 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)) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_partial_fit_exception(klass): + clf = klass(alpha=0.01) + # classes was not specified + with pytest.raises(ValueError): + clf.partial_fit(X3, Y3) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_partial_fit_binary(klass): + third = X.shape[0] // 3 + clf = klass(alpha=0.01) + classes = np.unique(Y) + + clf.partial_fit(X[:third], Y[:third], classes=classes) + assert clf.coef_.shape == (1, X.shape[1]) + assert clf.intercept_.shape == (1,) + assert clf.decision_function([[0, 0]]).shape == (1,) + id1 = id(clf.coef_.data) + + clf.partial_fit(X[third:], Y[third:]) + id2 = id(clf.coef_.data) + # check that coef_ haven't been re-allocated + assert id1, id2 + + y_pred = clf.predict(T) + assert_array_equal(y_pred, true_result) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_partial_fit_multiclass(klass): + third = X2.shape[0] // 3 + clf = klass(alpha=0.01) + classes = np.unique(Y2) + + clf.partial_fit(X2[:third], Y2[:third], classes=classes) + assert clf.coef_.shape == (3, X2.shape[1]) + assert clf.intercept_.shape == (3,) + assert clf.decision_function([[0, 0]]).shape == (1, 3) + id1 = id(clf.coef_.data) + + clf.partial_fit(X2[third:], Y2[third:]) + id2 = id(clf.coef_.data) + # check that coef_ haven't been re-allocated + assert id1, id2 + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_partial_fit_multiclass_average(klass): + third = X2.shape[0] // 3 + clf = klass(alpha=0.01, average=X2.shape[0]) + classes = np.unique(Y2) + + clf.partial_fit(X2[:third], Y2[:third], classes=classes) + assert clf.coef_.shape == (3, X2.shape[1]) + assert clf.intercept_.shape == (3,) + + clf.partial_fit(X2[third:], Y2[third:]) + assert clf.coef_.shape == (3, X2.shape[1]) + assert clf.intercept_.shape == (3,) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_fit_then_partial_fit(klass): + # Partial_fit should work after initial fit in the multiclass case. + # Non-regression test for #2496; fit would previously produce a + # Fortran-ordered coef_ that subsequent partial_fit couldn't handle. + clf = klass() + clf.fit(X2, Y2) + clf.partial_fit(X2, Y2) # no exception here + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +@pytest.mark.parametrize("lr", ["constant", "optimal", "invscaling", "adaptive"]) +def test_partial_fit_equal_fit_classif(klass, lr): + for X_, Y_, T_ in ((X, Y, T), (X2, Y2, T2)): + clf = klass(alpha=0.01, eta0=0.01, max_iter=2, learning_rate=lr, shuffle=False) + clf.fit(X_, Y_) + y_pred = clf.decision_function(T_) + t = clf.t_ + + classes = np.unique(Y_) + clf = klass(alpha=0.01, eta0=0.01, learning_rate=lr, shuffle=False) + for i in range(2): + clf.partial_fit(X_, Y_, classes=classes) + y_pred2 = clf.decision_function(T_) + + assert clf.t_ == t + assert_array_almost_equal(y_pred, y_pred2, decimal=2) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_regression_losses(klass): + random_state = np.random.RandomState(1) + clf = klass( + alpha=0.01, + learning_rate="constant", + eta0=0.1, + loss="epsilon_insensitive", + random_state=random_state, + ) + clf.fit(X, Y) + assert 1.0 == np.mean(clf.predict(X) == Y) + + clf = klass( + alpha=0.01, + learning_rate="constant", + eta0=0.1, + loss="squared_epsilon_insensitive", + random_state=random_state, + ) + clf.fit(X, Y) + assert 1.0 == np.mean(clf.predict(X) == Y) + + clf = klass(alpha=0.01, loss="huber", random_state=random_state) + clf.fit(X, Y) + assert 1.0 == np.mean(clf.predict(X) == Y) + + clf = klass( + alpha=0.01, + learning_rate="constant", + eta0=0.01, + loss="squared_error", + random_state=random_state, + ) + clf.fit(X, Y) + assert 1.0 == np.mean(clf.predict(X) == Y) + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_warm_start_multiclass(klass): + _test_warm_start(klass, X2, Y2, "optimal") + + +@pytest.mark.parametrize("klass", [SGDClassifier, SparseSGDClassifier]) +def test_multiple_fit(klass): + # Test multiple calls of fit w/ different shaped inputs. + clf = klass(alpha=0.01, shuffle=False) + clf.fit(X, Y) + assert hasattr(clf, "coef_") + + # Non-regression test: try fitting with a different label set. + y = [["ham", "spam"][i] for i in LabelEncoder().fit_transform(Y)] + clf.fit(X[:, :-1], y) + + +############################################################################### +# Regression Test Case + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_reg(klass): + # Check that SGD gives any results. + clf = klass(alpha=0.1, max_iter=2, fit_intercept=False) + clf.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2]) + assert clf.coef_[0] == clf.coef_[1] + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_averaged_computed_correctly(klass): + # Tests the average regressor matches the naive implementation + + eta = 0.001 + alpha = 0.01 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + # simple linear function without noise + y = np.dot(X, w) + + clf = klass( + loss="squared_error", + learning_rate="constant", + eta0=eta, + alpha=alpha, + fit_intercept=True, + max_iter=1, + average=True, + shuffle=False, + ) + + clf.fit(X, y) + average_weights, average_intercept = asgd(klass, X, y, eta, alpha) + + assert_array_almost_equal(clf.coef_, average_weights, decimal=16) + assert_almost_equal(clf.intercept_, average_intercept, decimal=16) + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_averaged_partial_fit(klass): + # Tests whether the partial fit yields the same average as the fit + eta = 0.001 + alpha = 0.01 + n_samples = 20 + n_features = 10 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, n_features)) + w = rng.normal(size=n_features) + + # simple linear function without noise + y = np.dot(X, w) + + clf = klass( + loss="squared_error", + learning_rate="constant", + eta0=eta, + alpha=alpha, + fit_intercept=True, + max_iter=1, + average=True, + shuffle=False, + ) + + clf.partial_fit(X[: int(n_samples / 2)][:], y[: int(n_samples / 2)]) + clf.partial_fit(X[int(n_samples / 2) :][:], y[int(n_samples / 2) :]) + average_weights, average_intercept = asgd(klass, X, y, eta, alpha) + + assert_array_almost_equal(clf.coef_, average_weights, decimal=16) + assert_almost_equal(clf.intercept_[0], average_intercept, decimal=16) + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_average_sparse(klass): + # Checks the average weights on data with 0s + + eta = 0.001 + alpha = 0.01 + clf = klass( + loss="squared_error", + learning_rate="constant", + eta0=eta, + alpha=alpha, + fit_intercept=True, + max_iter=1, + average=True, + shuffle=False, + ) + + n_samples = Y3.shape[0] + + clf.partial_fit(X3[: int(n_samples / 2)][:], Y3[: int(n_samples / 2)]) + clf.partial_fit(X3[int(n_samples / 2) :][:], Y3[int(n_samples / 2) :]) + average_weights, average_intercept = asgd(klass, X3, Y3, eta, alpha) + + assert_array_almost_equal(clf.coef_, average_weights, decimal=16) + assert_almost_equal(clf.intercept_, average_intercept, decimal=16) + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_least_squares_fit(klass): + xmin, xmax = -5, 5 + n_samples = 100 + rng = np.random.RandomState(0) + X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1) + + # simple linear function without noise + y = 0.5 * X.ravel() + + clf = klass(loss="squared_error", alpha=0.1, max_iter=20, fit_intercept=False) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.99 + + # simple linear function with noise + y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel() + + clf = klass(loss="squared_error", alpha=0.1, max_iter=20, fit_intercept=False) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.5 + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_epsilon_insensitive(klass): + xmin, xmax = -5, 5 + n_samples = 100 + rng = np.random.RandomState(0) + X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1) + + # simple linear function without noise + y = 0.5 * X.ravel() + + clf = klass( + loss="epsilon_insensitive", + epsilon=0.01, + alpha=0.1, + max_iter=20, + fit_intercept=False, + ) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.99 + + # simple linear function with noise + y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel() + + clf = klass( + loss="epsilon_insensitive", + epsilon=0.01, + alpha=0.1, + max_iter=20, + fit_intercept=False, + ) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.5 + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_sgd_huber_fit(klass): + xmin, xmax = -5, 5 + n_samples = 100 + rng = np.random.RandomState(0) + X = np.linspace(xmin, xmax, n_samples).reshape(n_samples, 1) + + # simple linear function without noise + y = 0.5 * X.ravel() + + clf = klass(loss="huber", epsilon=0.1, alpha=0.1, max_iter=20, fit_intercept=False) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.99 + + # simple linear function with noise + y = 0.5 * X.ravel() + rng.randn(n_samples, 1).ravel() + + clf = klass(loss="huber", epsilon=0.1, alpha=0.1, max_iter=20, fit_intercept=False) + clf.fit(X, y) + score = clf.score(X, y) + assert score > 0.5 + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_elasticnet_convergence(klass): + # Check that the SGD output is consistent with coordinate descent + + n_samples, n_features = 1000, 5 + rng = np.random.RandomState(0) + X = rng.randn(n_samples, n_features) + # ground_truth linear model that generate y from X and to which the + # models should converge if the regularizer would be set to 0.0 + ground_truth_coef = rng.randn(n_features) + y = np.dot(X, ground_truth_coef) + + # XXX: alpha = 0.1 seems to cause convergence problems + for alpha in [0.01, 0.001]: + for l1_ratio in [0.5, 0.8, 1.0]: + cd = linear_model.ElasticNet( + alpha=alpha, l1_ratio=l1_ratio, fit_intercept=False + ) + cd.fit(X, y) + sgd = klass( + penalty="elasticnet", + max_iter=50, + alpha=alpha, + l1_ratio=l1_ratio, + fit_intercept=False, + ) + sgd.fit(X, y) + err_msg = ( + "cd and sgd did not converge to comparable " + "results for alpha=%f and l1_ratio=%f" % (alpha, l1_ratio) + ) + assert_almost_equal(cd.coef_, sgd.coef_, decimal=2, err_msg=err_msg) + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_partial_fit(klass): + third = X.shape[0] // 3 + clf = klass(alpha=0.01) + + clf.partial_fit(X[:third], Y[:third]) + assert clf.coef_.shape == (X.shape[1],) + assert clf.intercept_.shape == (1,) + assert clf.predict([[0, 0]]).shape == (1,) + id1 = id(clf.coef_.data) + + clf.partial_fit(X[third:], Y[third:]) + id2 = id(clf.coef_.data) + # check that coef_ haven't been re-allocated + assert id1, id2 + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +@pytest.mark.parametrize("lr", ["constant", "optimal", "invscaling", "adaptive"]) +def test_partial_fit_equal_fit(klass, lr): + clf = klass(alpha=0.01, max_iter=2, eta0=0.01, learning_rate=lr, shuffle=False) + clf.fit(X, Y) + y_pred = clf.predict(T) + t = clf.t_ + + clf = klass(alpha=0.01, eta0=0.01, learning_rate=lr, shuffle=False) + for i in range(2): + clf.partial_fit(X, Y) + y_pred2 = clf.predict(T) + + assert clf.t_ == t + assert_array_almost_equal(y_pred, y_pred2, decimal=2) + + +@pytest.mark.parametrize("klass", [SGDRegressor, SparseSGDRegressor]) +def test_loss_function_epsilon(klass): + clf = klass(epsilon=0.9) + clf.set_params(epsilon=0.1) + 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 = 0.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 + + +@pytest.mark.parametrize("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_) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +@pytest.mark.parametrize("lr", ["constant", "optimal", "invscaling", "adaptive"]) +def test_warm_start_oneclass(klass, lr): + _test_warm_start_oneclass(klass, X, lr) + + +@pytest.mark.parametrize("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_) + + +@pytest.mark.parametrize("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,) + previous_coefs = clf.coef_ + + clf.partial_fit(X[third:]) + # check that coef_ haven't been re-allocated + assert clf.coef_ is previous_coefs + + # raises ValueError if number of features does not match previous data + with pytest.raises(ValueError): + clf.partial_fit(X[:, 1]) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_late_onset_averaging_reached_oneclass(klass): + # Test average + eta0 = 0.001 + nu = 0.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=False, + 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) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_sgd_averaged_computed_correctly_oneclass(klass): + # Tests the average SGD One-Class SVM matches the naive implementation + eta = 0.001 + nu = 0.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) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_sgd_averaged_partial_fit_oneclass(klass): + # Tests whether the partial fit yields the same average as the fit + eta = 0.001 + nu = 0.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) + + +@pytest.mark.parametrize("klass", [SGDOneClassSVM, SparseSGDOneClassSVM]) +def test_average_sparse_oneclass(klass): + # Checks the average coef on data with 0s + eta = 0.001 + nu = 0.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.0 + 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=None, + ) + 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, n_features=100, n_informative=20, random_state=1234 + ) + + # test if elasticnet with l1_ratio near 1 gives same result as pure l1 + est_en = SGDClassifier( + alpha=0.001, + penalty="elasticnet", + tol=None, + max_iter=6, + l1_ratio=0.9999999999, + random_state=42, + ).fit(X, y) + est_l1 = SGDClassifier( + alpha=0.001, penalty="l1", max_iter=6, random_state=42, tol=None + ).fit(X, y) + assert_array_almost_equal(est_en.coef_, est_l1.coef_) + + # test if elasticnet with l1_ratio near 0 gives same result as pure l2 + est_en = SGDClassifier( + alpha=0.001, + penalty="elasticnet", + tol=None, + max_iter=6, + l1_ratio=0.0000000001, + random_state=42, + ).fit(X, y) + est_l2 = SGDClassifier( + alpha=0.001, penalty="l2", max_iter=6, random_state=42, tol=None + ).fit(X, y) + assert_array_almost_equal(est_en.coef_, est_l2.coef_) + + +def test_underflow_or_overlow(): + with np.errstate(all="raise"): + # Generate some weird data with hugely unscaled features + rng = np.random.RandomState(0) + n_samples = 100 + n_features = 10 + + X = rng.normal(size=(n_samples, n_features)) + X[:, :2] *= 1e300 + assert np.isfinite(X).all() + + # Use MinMaxScaler to scale the data without introducing a numerical + # instability (computing the standard deviation naively is not possible + # on this data) + X_scaled = MinMaxScaler().fit_transform(X) + assert np.isfinite(X_scaled).all() + + # Define a ground truth on the scaled data + ground_truth = rng.normal(size=n_features) + y = (np.dot(X_scaled, ground_truth) > 0.0).astype(np.int32) + assert_array_equal(np.unique(y), [0, 1]) + + model = SGDClassifier(alpha=0.1, loss="squared_hinge", max_iter=500) + + # smoke test: model is stable on scaled data + model.fit(X_scaled, y) + assert np.isfinite(model.coef_).all() + + # model is numerically unstable on unscaled data + msg_regxp = ( + r"Floating-point under-/overflow occurred at epoch #.*" + " Scaling input data with StandardScaler or MinMaxScaler" + " might help." + ) + with pytest.raises(ValueError, match=msg_regxp): + model.fit(X, y) + + +def test_numerical_stability_large_gradient(): + # Non regression test case for numerical stability on scaled problems + # where the gradient can still explode with some losses + model = SGDClassifier( + loss="squared_hinge", + max_iter=10, + shuffle=True, + penalty="elasticnet", + l1_ratio=0.3, + alpha=0.01, + eta0=0.001, + random_state=0, + tol=None, + ) + with np.errstate(all="raise"): + model.fit(iris.data, iris.target) + assert np.isfinite(model.coef_).all() + + +@pytest.mark.parametrize("penalty", ["l2", "l1", "elasticnet"]) +def test_large_regularization(penalty): + # Non regression tests for numerical stability issues caused by large + # regularization parameters + model = SGDClassifier( + alpha=1e5, + learning_rate="constant", + eta0=0.1, + penalty=penalty, + shuffle=False, + tol=None, + max_iter=6, + ) + with np.errstate(all="raise"): + model.fit(iris.data, iris.target) + assert_array_almost_equal(model.coef_, np.zeros_like(model.coef_)) + + +def test_tol_parameter(): + # Test that the tol parameter behaves as expected + X = StandardScaler().fit_transform(iris.data) + y = iris.target == 1 + + # With tol is None, the number of iteration should be equal to max_iter + max_iter = 42 + model_0 = SGDClassifier(tol=None, random_state=0, max_iter=max_iter) + model_0.fit(X, y) + assert max_iter == model_0.n_iter_ + + # If tol is not None, the number of iteration should be less than max_iter + max_iter = 2000 + model_1 = SGDClassifier(tol=0, random_state=0, max_iter=max_iter) + model_1.fit(X, y) + assert max_iter > model_1.n_iter_ + assert model_1.n_iter_ > 5 + + # A larger tol should yield a smaller number of iteration + model_2 = SGDClassifier(tol=0.1, random_state=0, max_iter=max_iter) + model_2.fit(X, y) + assert model_1.n_iter_ > model_2.n_iter_ + assert model_2.n_iter_ > 3 + + # Strict tolerance and small max_iter should trigger a warning + model_3 = SGDClassifier(max_iter=3, tol=1e-3, random_state=0) + warning_message = ( + "Maximum number of iteration reached before " + "convergence. Consider increasing max_iter to " + "improve the fit." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + model_3.fit(X, y) + assert model_3.n_iter_ == 3 + + +def _test_loss_common(loss_function, cases): + # Test the different loss functions + # cases is a list of (p, y, expected) + for p, y, expected_loss, expected_dloss in cases: + assert_almost_equal(loss_function.py_loss(p, y), expected_loss) + assert_almost_equal(loss_function.py_dloss(p, y), expected_dloss) + + +def test_loss_hinge(): + # Test Hinge (hinge / perceptron) + # hinge + loss = sgd_fast.Hinge(1.0) + cases = [ + # (p, y, expected_loss, expected_dloss) + (1.1, 1.0, 0.0, 0.0), + (-2.0, -1.0, 0.0, 0.0), + (1.0, 1.0, 0.0, -1.0), + (-1.0, -1.0, 0.0, 1.0), + (0.5, 1.0, 0.5, -1.0), + (2.0, -1.0, 3.0, 1.0), + (-0.5, -1.0, 0.5, 1.0), + (0.0, 1.0, 1, -1.0), + ] + _test_loss_common(loss, cases) + + # perceptron + loss = sgd_fast.Hinge(0.0) + cases = [ + # (p, y, expected_loss, expected_dloss) + (1.0, 1.0, 0.0, 0.0), + (-0.1, -1.0, 0.0, 0.0), + (0.0, 1.0, 0.0, -1.0), + (0.0, -1.0, 0.0, 1.0), + (0.5, -1.0, 0.5, 1.0), + (2.0, -1.0, 2.0, 1.0), + (-0.5, 1.0, 0.5, -1.0), + (-1.0, 1.0, 1.0, -1.0), + ] + _test_loss_common(loss, cases) + + +def test_gradient_squared_hinge(): + # Test SquaredHinge + loss = sgd_fast.SquaredHinge(1.0) + cases = [ + # (p, y, expected_loss, expected_dloss) + (1.0, 1.0, 0.0, 0.0), + (-2.0, -1.0, 0.0, 0.0), + (1.0, -1.0, 4.0, 4.0), + (-1.0, 1.0, 4.0, -4.0), + (0.5, 1.0, 0.25, -1.0), + (0.5, -1.0, 2.25, 3.0), + ] + _test_loss_common(loss, cases) + + +def test_loss_modified_huber(): + # (p, y, expected_loss, expected_dloss) + loss = sgd_fast.ModifiedHuber() + cases = [ + # (p, y, expected_loss, expected_dloss) + (1.0, 1.0, 0.0, 0.0), + (-1.0, -1.0, 0.0, 0.0), + (2.0, 1.0, 0.0, 0.0), + (0.0, 1.0, 1.0, -2.0), + (-1.0, 1.0, 4.0, -4.0), + (0.5, -1.0, 2.25, 3.0), + (-2.0, 1.0, 8, -4.0), + (-3.0, 1.0, 12, -4.0), + ] + _test_loss_common(loss, cases) + + +def test_loss_epsilon_insensitive(): + # Test EpsilonInsensitive + loss = sgd_fast.EpsilonInsensitive(0.1) + cases = [ + # (p, y, expected_loss, expected_dloss) + (0.0, 0.0, 0.0, 0.0), + (0.1, 0.0, 0.0, 0.0), + (-2.05, -2.0, 0.0, 0.0), + (3.05, 3.0, 0.0, 0.0), + (2.2, 2.0, 0.1, 1.0), + (2.0, -1.0, 2.9, 1.0), + (2.0, 2.2, 0.1, -1.0), + (-2.0, 1.0, 2.9, -1.0), + ] + _test_loss_common(loss, cases) + + +def test_loss_squared_epsilon_insensitive(): + # Test SquaredEpsilonInsensitive + loss = sgd_fast.SquaredEpsilonInsensitive(0.1) + cases = [ + # (p, y, expected_loss, expected_dloss) + (0.0, 0.0, 0.0, 0.0), + (0.1, 0.0, 0.0, 0.0), + (-2.05, -2.0, 0.0, 0.0), + (3.05, 3.0, 0.0, 0.0), + (2.2, 2.0, 0.01, 0.2), + (2.0, -1.0, 8.41, 5.8), + (2.0, 2.2, 0.01, -0.2), + (-2.0, 1.0, 8.41, -5.8), + ] + _test_loss_common(loss, cases) + + +def test_multi_thread_multi_class_and_early_stopping(): + # This is a non-regression test for a bad interaction between + # early stopping internal attribute and thread-based parallelism. + clf = SGDClassifier( + alpha=1e-3, + tol=1e-3, + max_iter=1000, + early_stopping=True, + n_iter_no_change=100, + random_state=0, + n_jobs=2, + ) + clf.fit(iris.data, iris.target) + assert clf.n_iter_ > clf.n_iter_no_change + assert clf.n_iter_ < clf.n_iter_no_change + 20 + assert clf.score(iris.data, iris.target) > 0.8 + + +def test_multi_core_gridsearch_and_early_stopping(): + # This is a non-regression test for a bad interaction between + # early stopping internal attribute and process-based multi-core + # parallelism. + param_grid = { + "alpha": np.logspace(-4, 4, 9), + "n_iter_no_change": [5, 10, 50], + } + + clf = SGDClassifier(tol=1e-2, max_iter=1000, early_stopping=True, random_state=0) + search = RandomizedSearchCV(clf, param_grid, n_iter=5, n_jobs=2, random_state=0) + search.fit(iris.data, iris.target) + assert search.best_score_ > 0.8 + + +@pytest.mark.parametrize("backend", ["loky", "multiprocessing", "threading"]) +def test_SGDClassifier_fit_for_all_backends(backend): + # This is a non-regression smoke test. In the multi-class case, + # SGDClassifier.fit fits each class in a one-versus-all fashion using + # joblib.Parallel. However, each OvA step updates the coef_ attribute of + # the estimator in-place. Internally, SGDClassifier calls Parallel using + # require='sharedmem'. This test makes sure SGDClassifier.fit works + # consistently even when the user asks for a backend that does not provide + # sharedmem semantics. + + # We further test a case where memmapping would have been used if + # SGDClassifier.fit was called from a loky or multiprocessing backend. In + # this specific case, in-place modification of clf.coef_ would have caused + # a segmentation fault when trying to write in a readonly memory mapped + # buffer. + + random_state = np.random.RandomState(42) + + # Create a classification problem with 50000 features and 20 classes. Using + # loky or multiprocessing this make the clf.coef_ exceed the threshold + # above which memmaping is used in joblib and loky (1MB as of 2018/11/1). + X = sp.random(500, 2000, density=0.02, format="csr", random_state=random_state) + y = random_state.choice(20, 500) + + # Begin by fitting a SGD classifier sequentially + clf_sequential = SGDClassifier(max_iter=1000, n_jobs=1, random_state=42) + clf_sequential.fit(X, y) + + # Fit a SGDClassifier using the specified backend, and make sure the + # coefficients are equal to those obtained using a sequential fit + clf_parallel = SGDClassifier(max_iter=1000, n_jobs=4, random_state=42) + with joblib.parallel_backend(backend=backend): + clf_parallel.fit(X, y) + assert_array_almost_equal(clf_sequential.coef_, clf_parallel.coef_) + + +@pytest.mark.parametrize( + "Estimator", [linear_model.SGDClassifier, linear_model.SGDRegressor] +) +def test_sgd_random_state(Estimator, global_random_seed): + # Train the same model on the same data without converging and check that we + # get reproducible results by fixing the random seed. + if Estimator == linear_model.SGDRegressor: + X, y = datasets.make_regression(random_state=global_random_seed) + else: + X, y = datasets.make_classification(random_state=global_random_seed) + + # Fitting twice a model with the same hyper-parameters on the same training + # set with the same seed leads to the same results deterministically. + + est = Estimator(random_state=global_random_seed, max_iter=1) + with pytest.warns(ConvergenceWarning): + coef_same_seed_a = est.fit(X, y).coef_ + assert est.n_iter_ == 1 + + est = Estimator(random_state=global_random_seed, max_iter=1) + with pytest.warns(ConvergenceWarning): + coef_same_seed_b = est.fit(X, y).coef_ + assert est.n_iter_ == 1 + + assert_allclose(coef_same_seed_a, coef_same_seed_b) + + # Fitting twice a model with the same hyper-parameters on the same training + # set but with different random seed leads to different results after one + # epoch because of the random shuffling of the dataset. + + est = Estimator(random_state=global_random_seed + 1, max_iter=1) + with pytest.warns(ConvergenceWarning): + coef_other_seed = est.fit(X, y).coef_ + assert est.n_iter_ == 1 + + assert np.abs(coef_same_seed_a - coef_other_seed).max() > 1.0 + + +def test_validation_mask_correctly_subsets(monkeypatch): + """Test that data passed to validation callback correctly subsets. + + Non-regression test for #23255. + """ + X, Y = iris.data, iris.target + n_samples = X.shape[0] + validation_fraction = 0.2 + clf = linear_model.SGDClassifier( + early_stopping=True, + tol=1e-3, + max_iter=1000, + validation_fraction=validation_fraction, + ) + + mock = Mock(side_effect=_stochastic_gradient._ValidationScoreCallback) + monkeypatch.setattr(_stochastic_gradient, "_ValidationScoreCallback", mock) + clf.fit(X, Y) + + X_val, y_val = mock.call_args[0][1:3] + assert X_val.shape[0] == int(n_samples * validation_fraction) + assert y_val.shape[0] == int(n_samples * validation_fraction) + + +def test_sgd_error_on_zero_validation_weight(): + # Test that SGDClassifier raises error when all the validation samples + # have zero sample_weight. Non-regression test for #17229. + X, Y = iris.data, iris.target + sample_weight = np.zeros_like(Y) + validation_fraction = 0.4 + + clf = linear_model.SGDClassifier( + early_stopping=True, validation_fraction=validation_fraction, random_state=0 + ) + + error_message = ( + "The sample weights for validation set are all zero, consider using a" + " different random state." + ) + with pytest.raises(ValueError, match=error_message): + clf.fit(X, Y, sample_weight=sample_weight) + + +@pytest.mark.parametrize("Estimator", [SGDClassifier, SGDRegressor]) +def test_sgd_verbose(Estimator): + """non-regression test for gh #25249""" + Estimator(verbose=1).fit(X, Y) + + +@pytest.mark.parametrize( + "SGDEstimator", + [ + SGDClassifier, + SparseSGDClassifier, + SGDRegressor, + SparseSGDRegressor, + SGDOneClassSVM, + SparseSGDOneClassSVM, + ], +) +@pytest.mark.parametrize("data_type", (np.float32, np.float64)) +def test_sgd_dtype_match(SGDEstimator, data_type): + _X = X.astype(data_type) + _Y = np.array(Y, dtype=data_type) + sgd_model = SGDEstimator() + sgd_model.fit(_X, _Y) + assert sgd_model.coef_.dtype == data_type + + +@pytest.mark.parametrize( + "SGDEstimator", + [ + SGDClassifier, + SparseSGDClassifier, + SGDRegressor, + SparseSGDRegressor, + SGDOneClassSVM, + SparseSGDOneClassSVM, + ], +) +def test_sgd_numerical_consistency(SGDEstimator): + X_64 = X.astype(dtype=np.float64) + Y_64 = np.array(Y, dtype=np.float64) + + X_32 = X.astype(dtype=np.float32) + Y_32 = np.array(Y, dtype=np.float32) + + sgd_64 = SGDEstimator(max_iter=20) + sgd_64.fit(X_64, Y_64) + + sgd_32 = SGDEstimator(max_iter=20) + sgd_32.fit(X_32, Y_32) + + assert_allclose(sgd_64.coef_, sgd_32.coef_) + + +def test_sgd_one_class_svm_estimator_type(): + """Check that SGDOneClassSVM has the correct estimator type. + + Non-regression test for if the mixin was not on the left. + """ + sgd_ocsvm = SGDOneClassSVM() + assert get_tags(sgd_ocsvm).estimator_type == "outlier_detector" diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sparse_coordinate_descent.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sparse_coordinate_descent.py new file mode 100644 index 0000000000000000000000000000000000000000..1aab9babeeb40fcc3eac3f443c1ba7a9e1bdf9d4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_sparse_coordinate_descent.py @@ -0,0 +1,384 @@ +import numpy as np +import pytest +import scipy.sparse as sp +from numpy.testing import assert_allclose + +from sklearn.datasets import make_regression +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import ElasticNet, ElasticNetCV, Lasso, LassoCV +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + create_memmap_backed_data, + ignore_warnings, +) +from sklearn.utils.fixes import COO_CONTAINERS, CSC_CONTAINERS, LIL_CONTAINERS + + +def test_sparse_coef(): + # Check that the sparse_coef property works + clf = ElasticNet() + clf.coef_ = [1, 2, 3] + + assert sp.issparse(clf.sparse_coef_) + assert clf.sparse_coef_.toarray().tolist()[0] == clf.coef_ + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_lasso_zero(csc_container): + # Check that the sparse lasso can handle zero data without crashing + X = csc_container((3, 1)) + y = [0, 0, 0] + T = np.array([[1], [2], [3]]) + clf = Lasso().fit(X, y) + pred = clf.predict(T) + assert_array_almost_equal(clf.coef_, [0]) + assert_array_almost_equal(pred, [0, 0, 0]) + assert_almost_equal(clf.dual_gap_, 0) + + +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_enet_toy_list_input(with_sample_weight, csc_container): + # Test ElasticNet for various values of alpha and l1_ratio with list X + + X = np.array([[-1], [0], [1]]) + X = csc_container(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, 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, 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, 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) + assert_almost_equal(clf.dual_gap_, 0) + + +@pytest.mark.parametrize("lil_container", LIL_CONTAINERS) +def test_enet_toy_explicit_sparse_input(lil_container): + # Test ElasticNet for various values of alpha and l1_ratio with sparse X + f = ignore_warnings + # training samples + X = lil_container((3, 1)) + X[0, 0] = -1 + # X[1, 0] = 0 + X[2, 0] = 1 + Y = [-1, 0, 1] # just a straight line (the identity function) + + # test samples + T = lil_container((3, 1)) + T[0, 0] = 2 + T[1, 0] = 3 + T[2, 0] = 4 + + # this should be the same as lasso + clf = ElasticNet(alpha=0, l1_ratio=1.0) + f(clf.fit)(X, Y) + 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) + 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) + 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) + assert_almost_equal(clf.dual_gap_, 0) + + +def make_sparse_data( + sparse_container, + n_samples=100, + n_features=100, + n_informative=10, + seed=42, + positive=False, + n_targets=1, +): + random_state = np.random.RandomState(seed) + + # build an ill-posed linear regression problem with many noisy features and + # comparatively few samples + + # generate a ground truth model + w = random_state.randn(n_features, n_targets) + w[n_informative:] = 0.0 # only the top features are impacting the model + if positive: + w = np.abs(w) + + X = random_state.randn(n_samples, n_features) + rnd = random_state.uniform(size=(n_samples, n_features)) + X[rnd > 0.5] = 0.0 # 50% of zeros in input signal + + # generate training ground truth labels + y = np.dot(X, w) + X = sparse_container(X) + if n_targets == 1: + y = np.ravel(y) + return X, y + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +@pytest.mark.parametrize( + "alpha, fit_intercept, positive", + [(0.1, False, False), (0.1, True, False), (1e-3, False, True), (1e-3, True, True)], +) +def test_sparse_enet_not_as_toy_dataset(csc_container, alpha, fit_intercept, positive): + n_samples, n_features, max_iter = 100, 100, 1000 + n_informative = 10 + + X, y = make_sparse_data( + csc_container, n_samples, n_features, n_informative, positive=positive + ) + + X_train, X_test = X[n_samples // 2 :], X[: n_samples // 2] + y_train, y_test = y[n_samples // 2 :], y[: n_samples // 2] + + s_clf = ElasticNet( + alpha=alpha, + l1_ratio=0.8, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=1e-7, + positive=positive, + warm_start=True, + ) + s_clf.fit(X_train, y_train) + + assert_almost_equal(s_clf.dual_gap_, 0, 4) + assert s_clf.score(X_test, y_test) > 0.85 + + # check the convergence is the same as the dense version + d_clf = ElasticNet( + alpha=alpha, + l1_ratio=0.8, + fit_intercept=fit_intercept, + max_iter=max_iter, + tol=1e-7, + positive=positive, + warm_start=True, + ) + d_clf.fit(X_train.toarray(), y_train) + + assert_almost_equal(d_clf.dual_gap_, 0, 4) + assert d_clf.score(X_test, y_test) > 0.85 + + assert_almost_equal(s_clf.coef_, d_clf.coef_, 5) + assert_almost_equal(s_clf.intercept_, d_clf.intercept_, 5) + + # check that the coefs are sparse + assert np.sum(s_clf.coef_ != 0.0) < 2 * n_informative + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_sparse_lasso_not_as_toy_dataset(csc_container): + n_samples = 100 + max_iter = 1000 + n_informative = 10 + X, y = make_sparse_data( + csc_container, n_samples=n_samples, n_informative=n_informative + ) + + X_train, X_test = X[n_samples // 2 :], X[: n_samples // 2] + y_train, y_test = y[n_samples // 2 :], y[: n_samples // 2] + + s_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, tol=1e-7) + s_clf.fit(X_train, y_train) + assert_almost_equal(s_clf.dual_gap_, 0, 4) + assert s_clf.score(X_test, y_test) > 0.85 + + # check the convergence is the same as the dense version + d_clf = Lasso(alpha=0.1, fit_intercept=False, max_iter=max_iter, tol=1e-7) + d_clf.fit(X_train.toarray(), y_train) + assert_almost_equal(d_clf.dual_gap_, 0, 4) + assert d_clf.score(X_test, y_test) > 0.85 + + # check that the coefs are sparse + assert np.sum(s_clf.coef_ != 0.0) == n_informative + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_enet_multitarget(csc_container): + n_targets = 3 + X, y = make_sparse_data(csc_container, n_targets=n_targets) + + estimator = ElasticNet(alpha=0.01, precompute=False) + # XXX: There is a bug when precompute is not False! + estimator.fit(X, y) + coef, intercept, dual_gap = ( + estimator.coef_, + estimator.intercept_, + estimator.dual_gap_, + ) + + for k in range(n_targets): + estimator.fit(X, y[:, k]) + assert_array_almost_equal(coef[k, :], estimator.coef_) + assert_array_almost_equal(intercept[k], estimator.intercept_) + assert_array_almost_equal(dual_gap[k], estimator.dual_gap_) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_path_parameters(csc_container): + X, y = make_sparse_data(csc_container) + max_iter = 50 + n_alphas = 10 + clf = ElasticNetCV( + n_alphas=n_alphas, + eps=1e-3, + max_iter=max_iter, + l1_ratio=0.5, + fit_intercept=False, + ) + ignore_warnings(clf.fit)(X, y) # new params + assert_almost_equal(0.5, clf.l1_ratio) + assert n_alphas == clf.n_alphas + assert n_alphas == len(clf.alphas_) + sparse_mse_path = clf.mse_path_ + ignore_warnings(clf.fit)(X.toarray(), y) # compare with dense data + assert_almost_equal(clf.mse_path_, sparse_mse_path) + + +@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)]) +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_sparse_dense_equality( + Model, fit_intercept, n_samples, n_features, with_sample_weight, csc_container +): + X, y = make_regression( + n_samples=n_samples, + n_features=n_features, + effective_rank=n_features // 2, + n_informative=n_features // 2, + bias=4 * fit_intercept, + 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 = csc_container(X) + 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 np.average(reg_sparse.predict(X), weights=sw) == pytest.approx( + np.average(y, weights=sw) + ) + assert_allclose(reg_sparse.coef_, reg_dense.coef_) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_same_output_sparse_dense_lasso_and_enet_cv(csc_container): + X, y = make_sparse_data(csc_container, n_samples=40, n_features=10) + clfs = ElasticNetCV(max_iter=100) + clfs.fit(X, y) + clfd = ElasticNetCV(max_iter=100) + clfd.fit(X.toarray(), y) + assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) + assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) + assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) + assert_array_almost_equal(clfs.alphas_, clfd.alphas_) + + clfs = LassoCV(max_iter=100, cv=4) + clfs.fit(X, y) + clfd = LassoCV(max_iter=100, cv=4) + clfd.fit(X.toarray(), y) + assert_almost_equal(clfs.alpha_, clfd.alpha_, 7) + assert_almost_equal(clfs.intercept_, clfd.intercept_, 7) + assert_array_almost_equal(clfs.mse_path_, clfd.mse_path_) + assert_array_almost_equal(clfs.alphas_, clfd.alphas_) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_same_multiple_output_sparse_dense(coo_container): + l = ElasticNet() + X = [ + [0, 1, 2, 3, 4], + [0, 2, 5, 8, 11], + [9, 10, 11, 12, 13], + [10, 11, 12, 13, 14], + ] + y = [ + [1, 2, 3, 4, 5], + [1, 3, 6, 9, 12], + [10, 11, 12, 13, 14], + [11, 12, 13, 14, 15], + ] + l.fit(X, y) + sample = np.array([1, 2, 3, 4, 5]).reshape(1, -1) + predict_dense = l.predict(sample) + + l_sp = ElasticNet() + X_sp = coo_container(X) + l_sp.fit(X_sp, y) + sample_sparse = coo_container(sample) + predict_sparse = l_sp.predict(sample_sparse) + + assert_array_almost_equal(predict_sparse, predict_dense) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +def test_sparse_enet_coordinate_descent(csc_container): + """Test that a warning is issued if model does not converge""" + clf = Lasso(max_iter=2) + n_samples = 5 + n_features = 2 + X = csc_container((n_samples, n_features)) * 1e50 + y = np.ones(n_samples) + warning_message = ( + "Objective did not converge. You might want " + "to increase the number of iterations." + ) + with pytest.warns(ConvergenceWarning, match=warning_message): + clf.fit(X, y) + + +@pytest.mark.parametrize("copy_X", (True, False)) +def test_sparse_read_only_buffer(copy_X): + """Test that sparse coordinate descent works for read-only buffers""" + rng = np.random.RandomState(0) + + clf = ElasticNet(alpha=0.1, copy_X=copy_X, random_state=rng) + X = sp.random(100, 20, format="csc", random_state=rng) + + # Make X.data read-only + X.data = create_memmap_backed_data(X.data) + + y = rng.rand(100) + clf.fit(X, y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_theil_sen.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_theil_sen.py new file mode 100644 index 0000000000000000000000000000000000000000..216415f2ee9277e618c457afc0a7280c8a2a4b8a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/linear_model/tests/test_theil_sen.py @@ -0,0 +1,303 @@ +""" +Testing for Theil-Sen module (sklearn.linear_model.theil_sen) +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import os +import re +import sys +from contextlib import contextmanager + +import numpy as np +import pytest +from numpy.testing import ( + assert_array_almost_equal, + assert_array_equal, + assert_array_less, +) +from scipy.linalg import norm +from scipy.optimize import fmin_bfgs + +from sklearn.exceptions import ConvergenceWarning +from sklearn.linear_model import LinearRegression, TheilSenRegressor +from sklearn.linear_model._theil_sen import ( + _breakdown_point, + _modified_weiszfeld_step, + _spatial_median, +) +from sklearn.utils._testing import assert_almost_equal + + +@contextmanager +def no_stdout_stderr(): + old_stdout = sys.stdout + old_stderr = sys.stderr + with open(os.devnull, "w") as devnull: + sys.stdout = devnull + sys.stderr = devnull + yield + devnull.flush() + sys.stdout = old_stdout + sys.stderr = old_stderr + + +def gen_toy_problem_1d(intercept=True): + random_state = np.random.RandomState(0) + # Linear model y = 3*x + N(2, 0.1**2) + w = 3.0 + if intercept: + c = 2.0 + n_samples = 50 + else: + c = 0.1 + n_samples = 100 + x = random_state.normal(size=n_samples) + noise = 0.1 * random_state.normal(size=n_samples) + y = w * x + c + noise + # Add some outliers + if intercept: + x[42], y[42] = (-2, 4) + x[43], y[43] = (-2.5, 8) + x[33], y[33] = (2.5, 1) + x[49], y[49] = (2.1, 2) + else: + x[42], y[42] = (-2, 4) + x[43], y[43] = (-2.5, 8) + x[53], y[53] = (2.5, 1) + x[60], y[60] = (2.1, 2) + x[72], y[72] = (1.8, -7) + return x[:, np.newaxis], y, w, c + + +def gen_toy_problem_2d(): + random_state = np.random.RandomState(0) + n_samples = 100 + # Linear model y = 5*x_1 + 10*x_2 + N(1, 0.1**2) + X = random_state.normal(size=(n_samples, 2)) + w = np.array([5.0, 10.0]) + c = 1.0 + noise = 0.1 * random_state.normal(size=n_samples) + y = np.dot(X, w) + c + noise + # Add some outliers + n_outliers = n_samples // 10 + ix = random_state.randint(0, n_samples, size=n_outliers) + y[ix] = 50 * random_state.normal(size=n_outliers) + return X, y, w, c + + +def gen_toy_problem_4d(): + random_state = np.random.RandomState(0) + n_samples = 10000 + # Linear model y = 5*x_1 + 10*x_2 + 42*x_3 + 7*x_4 + N(1, 0.1**2) + X = random_state.normal(size=(n_samples, 4)) + w = np.array([5.0, 10.0, 42.0, 7.0]) + c = 1.0 + noise = 0.1 * random_state.normal(size=n_samples) + y = np.dot(X, w) + c + noise + # Add some outliers + n_outliers = n_samples // 10 + ix = random_state.randint(0, n_samples, size=n_outliers) + y[ix] = 50 * random_state.normal(size=n_outliers) + return X, y, w, c + + +def test_modweiszfeld_step_1d(): + X = np.array([1.0, 2.0, 3.0]).reshape(3, 1) + # Check startvalue is element of X and solution + median = 2.0 + new_y = _modified_weiszfeld_step(X, median) + assert_array_almost_equal(new_y, median) + # Check startvalue is not the solution + y = 2.5 + new_y = _modified_weiszfeld_step(X, y) + assert_array_less(median, new_y) + assert_array_less(new_y, y) + # Check startvalue is not the solution but element of X + y = 3.0 + new_y = _modified_weiszfeld_step(X, y) + assert_array_less(median, new_y) + assert_array_less(new_y, y) + # Check that a single vector is identity + X = np.array([1.0, 2.0, 3.0]).reshape(1, 3) + y = X[0] + new_y = _modified_weiszfeld_step(X, y) + assert_array_equal(y, new_y) + + +def test_modweiszfeld_step_2d(): + X = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 1.0]).reshape(3, 2) + y = np.array([0.5, 0.5]) + # Check first two iterations + new_y = _modified_weiszfeld_step(X, y) + assert_array_almost_equal(new_y, np.array([1 / 3, 2 / 3])) + new_y = _modified_weiszfeld_step(X, new_y) + assert_array_almost_equal(new_y, np.array([0.2792408, 0.7207592])) + # Check fix point + y = np.array([0.21132505, 0.78867497]) + new_y = _modified_weiszfeld_step(X, y) + assert_array_almost_equal(new_y, y) + + +def test_spatial_median_1d(): + X = np.array([1.0, 2.0, 3.0]).reshape(3, 1) + true_median = 2.0 + _, median = _spatial_median(X) + assert_array_almost_equal(median, true_median) + # Test larger problem and for exact solution in 1d case + random_state = np.random.RandomState(0) + X = random_state.randint(100, size=(1000, 1)) + true_median = np.median(X.ravel()) + _, median = _spatial_median(X) + assert_array_equal(median, true_median) + + +def test_spatial_median_2d(): + X = np.array([0.0, 0.0, 1.0, 1.0, 0.0, 1.0]).reshape(3, 2) + _, median = _spatial_median(X, max_iter=100, tol=1.0e-6) + + def cost_func(y): + dists = np.array([norm(x - y) for x in X]) + return np.sum(dists) + + # Check if median is solution of the Fermat-Weber location problem + fermat_weber = fmin_bfgs(cost_func, median, disp=False) + assert_array_almost_equal(median, fermat_weber) + # Check when maximum iteration is exceeded a warning is emitted + warning_message = "Maximum number of iterations 30 reached in spatial median." + with pytest.warns(ConvergenceWarning, match=warning_message): + _spatial_median(X, max_iter=30, tol=0.0) + + +def test_theil_sen_1d(): + X, y, w, c = gen_toy_problem_1d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert np.abs(lstq.coef_ - w) > 0.9 + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_theil_sen_1d_no_intercept(): + X, y, w, c = gen_toy_problem_1d(intercept=False) + # Check that Least Squares fails + lstq = LinearRegression(fit_intercept=False).fit(X, y) + assert np.abs(lstq.coef_ - w - c) > 0.5 + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(fit_intercept=False, random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w + c, 1) + assert_almost_equal(theil_sen.intercept_, 0.0) + + # non-regression test for #18104 + theil_sen.score(X, y) + + +def test_theil_sen_2d(): + X, y, w, c = gen_toy_problem_2d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert norm(lstq.coef_ - w) > 1.0 + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(max_subpopulation=1e3, random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_calc_breakdown_point(): + bp = _breakdown_point(1e10, 2) + assert np.abs(bp - 1 + 1 / (np.sqrt(2))) < 1.0e-6 + + +@pytest.mark.parametrize( + "param, ExceptionCls, match", + [ + ( + {"n_subsamples": 1}, + ValueError, + re.escape("Invalid parameter since n_features+1 > n_subsamples (2 > 1)"), + ), + ( + {"n_subsamples": 101}, + ValueError, + re.escape("Invalid parameter since n_subsamples > n_samples (101 > 50)"), + ), + ], +) +def test_checksubparams_invalid_input(param, ExceptionCls, match): + X, y, w, c = gen_toy_problem_1d() + theil_sen = TheilSenRegressor(**param, random_state=0) + with pytest.raises(ExceptionCls, match=match): + theil_sen.fit(X, y) + + +def test_checksubparams_n_subsamples_if_less_samples_than_features(): + random_state = np.random.RandomState(0) + n_samples, n_features = 10, 20 + X = random_state.normal(size=(n_samples, n_features)) + y = random_state.normal(size=n_samples) + theil_sen = TheilSenRegressor(n_subsamples=9, random_state=0) + with pytest.raises(ValueError): + theil_sen.fit(X, y) + + +def test_subpopulation(): + X, y, w, c = gen_toy_problem_4d() + theil_sen = TheilSenRegressor(max_subpopulation=250, random_state=0).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_subsamples(): + X, y, w, c = gen_toy_problem_4d() + theil_sen = TheilSenRegressor(n_subsamples=X.shape[0], random_state=0).fit(X, y) + lstq = LinearRegression().fit(X, y) + # Check for exact the same results as Least Squares + assert_array_almost_equal(theil_sen.coef_, lstq.coef_, 9) + + +def test_verbosity(): + X, y, w, c = gen_toy_problem_1d() + # Check that Theil-Sen can be verbose + with no_stdout_stderr(): + TheilSenRegressor(verbose=True, random_state=0).fit(X, y) + TheilSenRegressor(verbose=True, max_subpopulation=10, random_state=0).fit(X, y) + + +def test_theil_sen_parallel(): + X, y, w, c = gen_toy_problem_2d() + # Check that Least Squares fails + lstq = LinearRegression().fit(X, y) + assert norm(lstq.coef_ - w) > 1.0 + # Check that Theil-Sen works + theil_sen = TheilSenRegressor(n_jobs=2, random_state=0, max_subpopulation=2e3).fit( + X, y + ) + assert_array_almost_equal(theil_sen.coef_, w, 1) + assert_array_almost_equal(theil_sen.intercept_, c, 1) + + +def test_less_samples_than_features(): + random_state = np.random.RandomState(0) + n_samples, n_features = 10, 20 + X = random_state.normal(size=(n_samples, n_features)) + y = random_state.normal(size=n_samples) + # Check that Theil-Sen falls back to Least Squares if fit_intercept=False + theil_sen = TheilSenRegressor(fit_intercept=False, random_state=0).fit(X, y) + lstq = LinearRegression(fit_intercept=False).fit(X, y) + assert_array_almost_equal(theil_sen.coef_, lstq.coef_, 12) + # Check fit_intercept=True case. This will not be equal to the Least + # Squares solution since the intercept is calculated differently. + theil_sen = TheilSenRegressor(fit_intercept=True, random_state=0).fit(X, y) + y_pred = theil_sen.predict(X) + assert_array_almost_equal(y_pred, y, 12) + + +# TODO(1.8): Remove +def test_copy_X_deprecated(): + X, y, _, _ = gen_toy_problem_1d() + theil_sen = TheilSenRegressor(copy_X=True, random_state=0) + with pytest.warns(FutureWarning, match="`copy_X` was deprecated"): + theil_sen.fit(X, y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..349f7c1a4a7c41a053e3ae35228dc654dc6b63fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/__init__.py @@ -0,0 +1,22 @@ +"""Data embedding techniques.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._isomap import Isomap +from ._locally_linear import LocallyLinearEmbedding, locally_linear_embedding +from ._mds import MDS, smacof +from ._spectral_embedding import SpectralEmbedding, spectral_embedding +from ._t_sne import TSNE, trustworthiness + +__all__ = [ + "MDS", + "TSNE", + "Isomap", + "LocallyLinearEmbedding", + "SpectralEmbedding", + "locally_linear_embedding", + "smacof", + "spectral_embedding", + "trustworthiness", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_barnes_hut_tsne.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_barnes_hut_tsne.pyx new file mode 100644 index 0000000000000000000000000000000000000000..e84df4a9074b220d2a5dc01b203559d4a0945e6c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_barnes_hut_tsne.pyx @@ -0,0 +1,295 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# See http://homepage.tudelft.nl/19j49/t-SNE.html for reference +# implementations and papers describing the technique + + +import numpy as np +cimport numpy as cnp +from libc.stdio cimport printf +from libc.math cimport log +from libc.stdlib cimport malloc, free +from libc.time cimport clock, clock_t +from cython.parallel cimport prange, parallel + +from ..neighbors._quad_tree cimport _QuadTree + +cnp.import_array() + + +cdef char* EMPTY_STRING = "" + +# Smallest strictly positive value that can be represented by floating +# point numbers for different precision levels. This is useful to avoid +# taking the log of zero when computing the KL divergence. +cdef float FLOAT32_TINY = np.finfo(np.float32).tiny + +# Useful to void division by zero or divergence to +inf. +cdef float FLOAT64_EPS = np.finfo(np.float64).eps + +# This is effectively an ifdef statement in Cython +# It allows us to write printf debugging lines +# and remove them at compile time +cdef enum: + DEBUGFLAG = 0 + +cdef float compute_gradient(float[:] val_P, + float[:, :] pos_reference, + cnp.int64_t[:] neighbors, + cnp.int64_t[:] indptr, + float[:, :] tot_force, + _QuadTree qt, + float theta, + int dof, + long start, + bint compute_error, + int num_threads) noexcept nogil: + # Having created the tree, calculate the gradient + # in two components, the positive and negative forces + cdef: + long i, coord + int ax + long n_samples = pos_reference.shape[0] + int n_dimensions = qt.n_dimensions + clock_t t1 = 0, t2 = 0 + double sQ + float error + int take_timing = 1 if qt.verbose > 15 else 0 + + if qt.verbose > 11: + printf("[t-SNE] Allocating %li elements in force arrays\n", + n_samples * n_dimensions * 2) + cdef float* neg_f = malloc(sizeof(float) * n_samples * n_dimensions) + cdef float* pos_f = malloc(sizeof(float) * n_samples * n_dimensions) + + if take_timing: + t1 = clock() + sQ = compute_gradient_negative(pos_reference, neg_f, qt, dof, theta, start, + num_threads) + if take_timing: + t2 = clock() + printf("[t-SNE] Computing negative gradient: %e ticks\n", ((float) (t2 - t1))) + + if take_timing: + t1 = clock() + error = compute_gradient_positive(val_P, pos_reference, neighbors, indptr, + pos_f, n_dimensions, dof, sQ, start, + qt.verbose, compute_error, num_threads) + if take_timing: + t2 = clock() + printf("[t-SNE] Computing positive gradient: %e ticks\n", + ((float) (t2 - t1))) + for i in prange(start, n_samples, nogil=True, num_threads=num_threads, + schedule='static'): + for ax in range(n_dimensions): + coord = i * n_dimensions + ax + tot_force[i, ax] = pos_f[coord] - (neg_f[coord] / sQ) + + free(neg_f) + free(pos_f) + return error + + +cdef float compute_gradient_positive(float[:] val_P, + float[:, :] pos_reference, + cnp.int64_t[:] neighbors, + cnp.int64_t[:] indptr, + float* pos_f, + int n_dimensions, + int dof, + double sum_Q, + cnp.int64_t start, + int verbose, + bint compute_error, + int num_threads) noexcept nogil: + # Sum over the following expression for i not equal to j + # grad_i = p_ij (1 + ||y_i - y_j||^2)^-1 (y_i - y_j) + # This is equivalent to compute_edge_forces in the authors' code + # It just goes over the nearest neighbors instead of all the data points + # (unlike the non-nearest neighbors version of `compute_gradient_positive') + cdef: + int ax + long i, j, k + long n_samples = indptr.shape[0] - 1 + float C = 0.0 + float dij, qij, pij + float exponent = (dof + 1.0) / 2.0 + float float_dof = (float) (dof) + float* buff + clock_t t1 = 0, t2 = 0 + float dt + + if verbose > 10: + t1 = clock() + + with nogil, parallel(num_threads=num_threads): + # Define private buffer variables + buff = malloc(sizeof(float) * n_dimensions) + + for i in prange(start, n_samples, schedule='static'): + # Init the gradient vector + for ax in range(n_dimensions): + pos_f[i * n_dimensions + ax] = 0.0 + # Compute the positive interaction for the nearest neighbors + for k in range(indptr[i], indptr[i+1]): + j = neighbors[k] + dij = 0.0 + pij = val_P[k] + for ax in range(n_dimensions): + buff[ax] = pos_reference[i, ax] - pos_reference[j, ax] + dij += buff[ax] * buff[ax] + qij = float_dof / (float_dof + dij) + if dof != 1: # i.e. exponent != 1 + qij = qij ** exponent + dij = pij * qij + + # only compute the error when needed + if compute_error: + qij = qij / sum_Q + C += pij * log(max(pij, FLOAT32_TINY) / max(qij, FLOAT32_TINY)) + for ax in range(n_dimensions): + pos_f[i * n_dimensions + ax] += dij * buff[ax] + + free(buff) + if verbose > 10: + t2 = clock() + dt = ((float) (t2 - t1)) + printf("[t-SNE] Computed error=%1.4f in %1.1e ticks\n", C, dt) + return C + + +cdef double compute_gradient_negative(float[:, :] pos_reference, + float* neg_f, + _QuadTree qt, + int dof, + float theta, + long start, + int num_threads) noexcept nogil: + cdef: + int ax + int n_dimensions = qt.n_dimensions + int offset = n_dimensions + 2 + long i, j, idx + long n_samples = pos_reference.shape[0] + long n = n_samples - start + long dta = 0 + long dtb = 0 + float size, dist2s, mult + float exponent = (dof + 1.0) / 2.0 + float float_dof = (float) (dof) + double qijZ, sum_Q = 0.0 + float* force + float* neg_force + float* pos + clock_t t1 = 0, t2 = 0, t3 = 0 + int take_timing = 1 if qt.verbose > 20 else 0 + + with nogil, parallel(num_threads=num_threads): + # Define thread-local buffers + summary = malloc(sizeof(float) * n * offset) + pos = malloc(sizeof(float) * n_dimensions) + force = malloc(sizeof(float) * n_dimensions) + neg_force = malloc(sizeof(float) * n_dimensions) + + for i in prange(start, n_samples, schedule='static'): + # Clear the arrays + for ax in range(n_dimensions): + force[ax] = 0.0 + neg_force[ax] = 0.0 + pos[ax] = pos_reference[i, ax] + + # Find which nodes are summarizing and collect their centers of mass + # deltas, and sizes, into vectorized arrays + if take_timing: + t1 = clock() + idx = qt.summarize(pos, summary, theta*theta) + if take_timing: + t2 = clock() + # Compute the t-SNE negative force + # for the digits dataset, walking the tree + # is about 10-15x more expensive than the + # following for loop + for j in range(idx // offset): + + dist2s = summary[j * offset + n_dimensions] + size = summary[j * offset + n_dimensions + 1] + qijZ = float_dof / (float_dof + dist2s) # 1/(1+dist) + if dof != 1: # i.e. exponent != 1 + qijZ = qijZ ** exponent + + sum_Q += size * qijZ # size of the node * q + mult = size * qijZ * qijZ + for ax in range(n_dimensions): + neg_force[ax] += mult * summary[j * offset + ax] + if take_timing: + t3 = clock() + for ax in range(n_dimensions): + neg_f[i * n_dimensions + ax] = neg_force[ax] + if take_timing: + dta += t2 - t1 + dtb += t3 - t2 + free(pos) + free(force) + free(neg_force) + free(summary) + if take_timing: + printf("[t-SNE] Tree: %li clock ticks | ", dta) + printf("Force computation: %li clock ticks\n", dtb) + + # Put sum_Q to machine EPSILON to avoid divisions by 0 + sum_Q = max(sum_Q, FLOAT64_EPS) + return sum_Q + + +def gradient(float[:] val_P, + float[:, :] pos_output, + cnp.int64_t[:] neighbors, + cnp.int64_t[:] indptr, + float[:, :] forces, + float theta, + int n_dimensions, + int verbose, + int dof=1, + long skip_num_points=0, + bint compute_error=1, + int num_threads=1): + # This function is designed to be called from external Python + # it passes the 'forces' array by reference and fills that's array + # up in-place + cdef float C + cdef int n + n = pos_output.shape[0] + assert val_P.itemsize == 4 + assert pos_output.itemsize == 4 + assert forces.itemsize == 4 + m = "Forces array and pos_output shapes are incompatible" + assert n == forces.shape[0], m + m = "Pij and pos_output shapes are incompatible" + assert n == indptr.shape[0] - 1, m + if verbose > 10: + printf("[t-SNE] Initializing tree of n_dimensions %i\n", n_dimensions) + cdef _QuadTree qt = _QuadTree(pos_output.shape[1], verbose) + if verbose > 10: + printf("[t-SNE] Inserting %li points\n", pos_output.shape[0]) + qt.build_tree(pos_output) + if verbose > 10: + # XXX: format hack to workaround lack of `const char *` type + # in the generated C code that triggers error with gcc 4.9 + # and -Werror=format-security + printf("[t-SNE] Computing gradient\n%s", EMPTY_STRING) + + C = compute_gradient(val_P, pos_output, neighbors, indptr, forces, + qt, theta, dof, skip_num_points, compute_error, + num_threads) + + if verbose > 10: + # XXX: format hack to workaround lack of `const char *` type + # in the generated C code + # and -Werror=format-security + printf("[t-SNE] Checking tree consistency\n%s", EMPTY_STRING) + m = "Tree consistency failed: unexpected number of points on the tree" + assert qt.cells[0].cumulative_size == qt.n_points, m + if not compute_error: + C = np.nan + return C diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_isomap.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_isomap.py new file mode 100644 index 0000000000000000000000000000000000000000..90154470c18a486a250ea112cb31e57167d2eb43 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_isomap.py @@ -0,0 +1,442 @@ +"""Isomap for manifold learning""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy.sparse import issparse +from scipy.sparse.csgraph import connected_components, shortest_path + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..decomposition import KernelPCA +from ..metrics.pairwise import _VALID_METRICS +from ..neighbors import NearestNeighbors, kneighbors_graph, radius_neighbors_graph +from ..preprocessing import KernelCenterer +from ..utils._param_validation import Interval, StrOptions +from ..utils.graph import _fix_connected_components +from ..utils.validation import check_is_fitted + + +class Isomap(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """Isomap Embedding. + + Non-linear dimensionality reduction through Isometric Mapping + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + 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. + + eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' + 'auto' : Attempt to choose the most efficient solver + for the given problem. + + 'arpack' : Use Arnoldi decomposition to find the eigenvalues + and eigenvectors. + + 'dense' : Use a direct solver (i.e. LAPACK) + for the eigenvalue decomposition. + + tol : float, default=0 + Convergence tolerance passed to arpack or lobpcg. + not used if eigen_solver == 'dense'. + + max_iter : int, default=None + Maximum number of iterations for the arpack solver. + not used if eigen_solver == 'dense'. + + path_method : {'auto', 'FW', 'D'}, default='auto' + Method to use in finding shortest path. + + 'auto' : attempt to choose the best algorithm automatically. + + 'FW' : Floyd-Warshall algorithm. + + 'D' : Dijkstra's algorithm. + + neighbors_algorithm : {'auto', 'brute', 'kd_tree', 'ball_tree'}, \ + default='auto' + Algorithm to use for nearest neighbors search, + passed to neighbors.NearestNeighbors instance. + + n_jobs : int or None, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + metric : str, or callable, default="minkowski" + The metric to use when calculating distance between instances in a + feature array. If metric is a string or callable, it must be one of + the options allowed by :func:`sklearn.metrics.pairwise_distances` for + its metric parameter. + If metric is "precomputed", X is assumed to be a distance matrix and + must be square. X may be a :term:`Glossary `. + + .. versionadded:: 0.22 + + p : float, default=2 + Parameter for the Minkowski metric from + sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + .. versionadded:: 0.22 + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 0.22 + + Attributes + ---------- + embedding_ : array-like, shape (n_samples, n_components) + Stores the embedding vectors. + + kernel_pca_ : object + :class:`~sklearn.decomposition.KernelPCA` object used to implement the + embedding. + + nbrs_ : sklearn.neighbors.NearestNeighbors instance + Stores nearest neighbors instance, including BallTree or KDtree + if applicable. + + dist_matrix_ : array-like, shape (n_samples, n_samples) + Stores the geodesic distance matrix of training data. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.decomposition.PCA : Principal component analysis that is a linear + dimensionality reduction method. + sklearn.decomposition.KernelPCA : Non-linear dimensionality reduction using + kernels and PCA. + MDS : Manifold learning using multidimensional scaling. + TSNE : T-distributed Stochastic Neighbor Embedding. + LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding. + SpectralEmbedding : Spectral embedding for non-linear dimensionality. + + References + ---------- + + .. [1] Tenenbaum, J.B.; De Silva, V.; & Langford, J.C. A global geometric + framework for nonlinear dimensionality reduction. Science 290 (5500) + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.manifold import Isomap + >>> X, _ = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> embedding = Isomap(n_components=2) + >>> X_transformed = embedding.fit_transform(X[:100]) + >>> X_transformed.shape + (100, 2) + """ + + _parameter_constraints: dict = { + "n_neighbors": [Interval(Integral, 1, None, closed="left"), None], + "radius": [Interval(Real, 0, None, closed="both"), None], + "n_components": [Interval(Integral, 1, None, closed="left")], + "eigen_solver": [StrOptions({"auto", "arpack", "dense"})], + "tol": [Interval(Real, 0, None, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left"), None], + "path_method": [StrOptions({"auto", "FW", "D"})], + "neighbors_algorithm": [StrOptions({"auto", "brute", "kd_tree", "ball_tree"})], + "n_jobs": [Integral, None], + "p": [Interval(Real, 1, None, closed="left")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "metric_params": [dict, None], + } + + def __init__( + self, + *, + n_neighbors=5, + radius=None, + n_components=2, + eigen_solver="auto", + tol=0, + max_iter=None, + path_method="auto", + neighbors_algorithm="auto", + n_jobs=None, + metric="minkowski", + p=2, + metric_params=None, + ): + self.n_neighbors = n_neighbors + self.radius = radius + self.n_components = n_components + self.eigen_solver = eigen_solver + self.tol = tol + self.max_iter = max_iter + self.path_method = path_method + self.neighbors_algorithm = neighbors_algorithm + self.n_jobs = n_jobs + self.metric = metric + self.p = p + 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, + metric_params=self.metric_params, + n_jobs=self.n_jobs, + ) + self.nbrs_.fit(X) + self.n_features_in_ = self.nbrs_.n_features_in_ + if hasattr(self.nbrs_, "feature_names_in_"): + self.feature_names_in_ = self.nbrs_.feature_names_in_ + + self.kernel_pca_ = KernelPCA( + n_components=self.n_components, + kernel="precomputed", + eigen_solver=self.eigen_solver, + tol=self.tol, + max_iter=self.max_iter, + n_jobs=self.n_jobs, + ).set_output(transform="default") + + 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(nbg) + if n_connected_components > 1: + if self.metric == "precomputed" and issparse(X): + raise RuntimeError( + "The number of connected components of the neighbors graph" + f" is {n_connected_components} > 1. The graph cannot be " + "completed with metric='precomputed', and Isomap cannot be" + "fitted. Increase the number of neighbors to avoid this " + "issue, or precompute the full distance matrix instead " + "of passing a sparse neighbors graph." + ) + warnings.warn( + ( + "The number of connected components of the neighbors graph " + f"is {n_connected_components} > 1. Completing the graph to fit" + " Isomap might be slow. Increase the number of neighbors to " + "avoid this issue." + ), + stacklevel=2, + ) + + # use array validated by NearestNeighbors + nbg = _fix_connected_components( + X=self.nbrs_._fit_X, + graph=nbg, + n_connected_components=n_connected_components, + component_labels=labels, + mode="distance", + metric=self.nbrs_.effective_metric_, + **self.nbrs_.effective_metric_params_, + ) + + self.dist_matrix_ = shortest_path(nbg, method=self.path_method, directed=False) + + if self.nbrs_._fit_X.dtype == np.float32: + self.dist_matrix_ = self.dist_matrix_.astype( + self.nbrs_._fit_X.dtype, copy=False + ) + + G = self.dist_matrix_**2 + 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. + + Returns + ------- + reconstruction_error : float + Reconstruction error. + + Notes + ----- + The cost function of an isomap embedding is + + ``E = frobenius_norm[K(D) - K(D_fit)] / n_samples`` + + Where D is the matrix of distances for the input data X, + D_fit is the matrix of distances for the output embedding X_fit, + and K is the isomap kernel: + + ``K(D) = -0.5 * (I - 1/n_samples) * D^2 * (I - 1/n_samples)`` + """ + G = -0.5 * self.dist_matrix_**2 + G_center = KernelCenterer().fit_transform(G) + evals = self.kernel_pca_.eigenvalues_ + return np.sqrt(np.sum(G_center**2) - np.sum(evals**2)) / G.shape[0] + + @_fit_context( + # Isomap.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Compute the embedding vectors for data X. + + Parameters + ---------- + X : {array-like, sparse matrix, BallTree, KDTree, NearestNeighbors} + Sample data, shape = (n_samples, n_features), in the form of a + numpy array, sparse matrix, precomputed tree, or NearestNeighbors + object. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Returns a fitted instance of self. + """ + self._fit_transform(X) + return self + + @_fit_context( + # Isomap.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit_transform(self, X, y=None): + """Fit the model from data in X and transform X. + + Parameters + ---------- + X : {array-like, sparse matrix, BallTree, KDTree} + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + X transformed in the new space. + """ + self._fit_transform(X) + return self.embedding_ + + def transform(self, X): + """Transform X. + + This is implemented by linking the points X into the graph of geodesic + distances of the training data. First the `n_neighbors` nearest + neighbors of X are found in the training data, and from these the + shortest geodesic distances from each point in X to each point in + the training data are computed in order to construct the kernel. + The embedding of X is the projection of this kernel onto the + embedding vectors of the training set. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_queries, n_features) + If neighbors_algorithm='precomputed', X is assumed to be a + distance matrix or a sparse graph of shape + (n_queries, n_samples_fit). + + Returns + ------- + X_new : array-like, shape (n_queries, n_components) + X transformed in the new space. + """ + check_is_fitted(self) + 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. + # This can be done as a single array operation, but it potentially + # takes a lot of memory. To avoid that, use a loop: + + n_samples_fit = self.nbrs_.n_samples_fit_ + n_queries = distances.shape[0] + + if hasattr(X, "dtype") and X.dtype == np.float32: + dtype = np.float32 + else: + dtype = np.float64 + + G_X = np.zeros((n_queries, n_samples_fit), dtype) + for i in range(n_queries): + G_X[i] = np.min(self.dist_matrix_[indices[i]] + distances[i][:, None], 0) + + G_X **= 2 + G_X *= -0.5 + + return self.kernel_pca_.transform(G_X) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.transformer_tags.preserves_dtype = ["float64", "float32"] + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_locally_linear.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_locally_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..7e3f456f7ca57e0a5ef4ba3aaf847475aacadfab --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_locally_linear.py @@ -0,0 +1,879 @@ +"""Locally Linear Embedding""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from numbers import Integral, Real + +import numpy as np +from scipy.linalg import eigh, qr, solve, svd +from scipy.sparse import csr_matrix, eye, lil_matrix +from scipy.sparse.linalg import eigsh + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, + _UnstableArchMixin, +) +from ..neighbors import NearestNeighbors +from ..utils import check_array, check_random_state +from ..utils._arpack import _init_arpack_v0 +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import stable_cumsum +from ..utils.validation import FLOAT_DTYPES, check_is_fitted, validate_data + + +def barycenter_weights(X, Y, indices, reg=1e-3): + """Compute barycenter weights of X from Y along the first axis + + We estimate the weights to assign to each point in Y[indices] to recover + the point X[i]. The barycenter weights sum to 1. + + Parameters + ---------- + X : array-like, shape (n_samples, n_dim) + + Y : array-like, shape (n_samples, n_dim) + + indices : array-like, shape (n_samples, n_dim) + Indices of the points in Y used to compute the barycenter + + reg : float, default=1e-3 + Amount of regularization to add for the problem to be + well-posed in the case of n_neighbors > n_dim + + Returns + ------- + B : array-like, shape (n_samples, n_neighbors) + + Notes + ----- + See developers note for more information. + """ + X = check_array(X, dtype=FLOAT_DTYPES) + Y = check_array(Y, dtype=FLOAT_DTYPES) + indices = check_array(indices, dtype=int) + + n_samples, n_neighbors = indices.shape + assert X.shape[0] == n_samples + + B = np.empty((n_samples, n_neighbors), dtype=X.dtype) + v = np.ones(n_neighbors, dtype=X.dtype) + + # this might raise a LinalgError if G is singular and has trace + # zero + for i, ind in enumerate(indices): + A = Y[ind] + C = A - X[i] # broadcasting + G = np.dot(C, C.T) + trace = np.trace(G) + if trace > 0: + R = reg * trace + else: + R = reg + G.flat[:: n_neighbors + 1] += R + w = solve(G, v, assume_a="pos") + B[i, :] = w / np.sum(w) + return B + + +def barycenter_kneighbors_graph(X, n_neighbors, reg=1e-3, n_jobs=None): + """Computes the barycenter weighted graph of k-Neighbors for points in X + + Parameters + ---------- + X : {array-like, NearestNeighbors} + Sample data, shape = (n_samples, n_features), in the form of a + numpy array or a NearestNeighbors object. + + n_neighbors : int + Number of neighbors for each sample. + + reg : float, default=1e-3 + Amount of regularization when solving the least-squares + problem. Only relevant if mode='barycenter'. If None, use the + default. + + n_jobs : int or None, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + A : sparse matrix in CSR format, shape = [n_samples, n_samples] + A[i, j] is assigned the weight of edge that connects i to j. + + See Also + -------- + sklearn.neighbors.kneighbors_graph + sklearn.neighbors.radius_neighbors_graph + """ + knn = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs).fit(X) + X = knn._fit_X + n_samples = knn.n_samples_fit_ + ind = knn.kneighbors(X, return_distance=False)[:, 1:] + data = barycenter_weights(X, X, ind, reg=reg) + indptr = np.arange(0, n_samples * n_neighbors + 1, n_neighbors) + return csr_matrix((data.ravel(), ind.ravel(), indptr), shape=(n_samples, n_samples)) + + +def null_space( + M, k, k_skip=1, eigen_solver="arpack", tol=1e-6, max_iter=100, random_state=None +): + """ + Find the null space of a matrix M. + + Parameters + ---------- + M : {array, matrix, sparse matrix, LinearOperator} + Input covariance matrix: should be symmetric positive semi-definite + + k : int + Number of eigenvalues/vectors to return + + k_skip : int, default=1 + Number of low eigenvalues to skip. + + eigen_solver : {'auto', 'arpack', 'dense'}, default='arpack' + auto : algorithm will attempt to choose the best method for input data + arpack : use arnoldi iteration in shift-invert mode. + For this method, M may be a dense matrix, sparse matrix, + or general linear operator. + Warning: ARPACK can be unstable for some problems. It is + best to try several random seeds in order to check results. + dense : use standard dense matrix operations for the eigenvalue + decomposition. For this method, M must be an array + or matrix type. This method should be avoided for + large problems. + + tol : float, default=1e-6 + Tolerance for 'arpack' method. + Not used if eigen_solver=='dense'. + + max_iter : int, default=100 + Maximum number of iterations for 'arpack' method. + Not used if eigen_solver=='dense' + + random_state : int, RandomState instance, default=None + Determines the random number generator when ``solver`` == 'arpack'. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + """ + if eigen_solver == "auto": + if M.shape[0] > 200 and k + k_skip < 10: + eigen_solver = "arpack" + else: + eigen_solver = "dense" + + if eigen_solver == "arpack": + v0 = _init_arpack_v0(M.shape[0], random_state) + try: + eigen_values, eigen_vectors = eigsh( + M, k + k_skip, sigma=0.0, tol=tol, maxiter=max_iter, v0=v0 + ) + except RuntimeError as e: + raise ValueError( + "Error in determining null-space with ARPACK. Error message: " + "'%s'. Note that eigen_solver='arpack' can fail when the " + "weight matrix is singular or otherwise ill-behaved. In that " + "case, eigen_solver='dense' is recommended. See online " + "documentation for more information." % e + ) from e + + return eigen_vectors[:, k_skip:], np.sum(eigen_values[k_skip:]) + elif eigen_solver == "dense": + if hasattr(M, "toarray"): + M = M.toarray() + eigen_values, eigen_vectors = eigh( + M, subset_by_index=(k_skip, k + k_skip - 1), overwrite_a=True + ) + index = np.argsort(np.abs(eigen_values)) + return eigen_vectors[:, index], np.sum(eigen_values) + else: + raise ValueError("Unrecognized eigen_solver '%s'" % eigen_solver) + + +def _locally_linear_embedding( + X, + *, + n_neighbors, + n_components, + reg=1e-3, + eigen_solver="auto", + tol=1e-6, + max_iter=100, + method="standard", + hessian_tol=1e-4, + modified_tol=1e-12, + random_state=None, + n_jobs=None, +): + nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1, n_jobs=n_jobs) + nbrs.fit(X) + X = nbrs._fit_X + + N, d_in = X.shape + + if n_components > d_in: + raise ValueError( + "output dimension must be less than or equal to input dimension" + ) + if n_neighbors >= N: + raise ValueError( + "Expected n_neighbors < n_samples, but n_samples = %d, n_neighbors = %d" + % (N, n_neighbors) + ) + + M_sparse = eigen_solver != "dense" + M_container_constructor = lil_matrix if M_sparse else np.zeros + + if method == "standard": + W = barycenter_kneighbors_graph( + nbrs, n_neighbors=n_neighbors, reg=reg, n_jobs=n_jobs + ) + + # we'll compute M = (I-W)'(I-W) + # depending on the solver, we'll do this differently + if M_sparse: + M = eye(*W.shape, format=W.format) - W + M = M.T @ M + else: + M = (W.T @ W - W.T - W).toarray() + M.flat[:: M.shape[0] + 1] += 1 # M = W' W - W' - W + I + + elif method == "hessian": + dp = n_components * (n_components + 1) // 2 + + if n_neighbors <= n_components + dp: + raise ValueError( + "for method='hessian', n_neighbors must be " + "greater than " + "[n_components * (n_components + 3) / 2]" + ) + + neighbors = nbrs.kneighbors( + X, n_neighbors=n_neighbors + 1, return_distance=False + ) + neighbors = neighbors[:, 1:] + + Yi = np.empty((n_neighbors, 1 + n_components + dp), dtype=np.float64) + Yi[:, 0] = 1 + + M = M_container_constructor((N, N), dtype=np.float64) + + use_svd = n_neighbors > d_in + + for i in range(N): + Gi = X[neighbors[i]] + Gi -= Gi.mean(0) + + # build Hessian estimator + if use_svd: + U = svd(Gi, full_matrices=0)[0] + else: + Ci = np.dot(Gi, Gi.T) + U = eigh(Ci)[1][:, ::-1] + + Yi[:, 1 : 1 + n_components] = U[:, :n_components] + + j = 1 + n_components + for k in range(n_components): + Yi[:, j : j + n_components - k] = U[:, k : k + 1] * U[:, k:n_components] + j += n_components - k + + Q, R = qr(Yi) + + w = Q[:, n_components + 1 :] + S = w.sum(0) + + S[np.where(abs(S) < hessian_tol)] = 1 + w /= S + + nbrs_x, nbrs_y = np.meshgrid(neighbors[i], neighbors[i]) + M[nbrs_x, nbrs_y] += np.dot(w, w.T) + + elif method == "modified": + if n_neighbors < n_components: + raise ValueError("modified LLE requires n_neighbors >= n_components") + + neighbors = nbrs.kneighbors( + X, n_neighbors=n_neighbors + 1, return_distance=False + ) + neighbors = neighbors[:, 1:] + + # find the eigenvectors and eigenvalues of each local covariance + # matrix. We want V[i] to be a [n_neighbors x n_neighbors] matrix, + # where the columns are eigenvectors + V = np.zeros((N, n_neighbors, n_neighbors)) + nev = min(d_in, n_neighbors) + evals = np.zeros([N, nev]) + + # choose the most efficient way to find the eigenvectors + use_svd = n_neighbors > d_in + + if use_svd: + for i in range(N): + X_nbrs = X[neighbors[i]] - X[i] + V[i], evals[i], _ = svd(X_nbrs, full_matrices=True) + evals **= 2 + else: + for i in range(N): + X_nbrs = X[neighbors[i]] - X[i] + C_nbrs = np.dot(X_nbrs, X_nbrs.T) + evi, vi = eigh(C_nbrs) + evals[i] = evi[::-1] + V[i] = vi[:, ::-1] + + # find regularized weights: this is like normal LLE. + # because we've already computed the SVD of each covariance matrix, + # it's faster to use this rather than np.linalg.solve + reg = 1e-3 * evals.sum(1) + + tmp = np.dot(V.transpose(0, 2, 1), np.ones(n_neighbors)) + tmp[:, :nev] /= evals + reg[:, None] + tmp[:, nev:] /= reg[:, None] + + w_reg = np.zeros((N, n_neighbors)) + for i in range(N): + w_reg[i] = np.dot(V[i], tmp[i]) + w_reg /= w_reg.sum(1)[:, None] + + # calculate eta: the median of the ratio of small to large eigenvalues + # across the points. This is used to determine s_i, below + rho = evals[:, n_components:].sum(1) / evals[:, :n_components].sum(1) + eta = np.median(rho) + + # find s_i, the size of the "almost null space" for each point: + # this is the size of the largest set of eigenvalues + # such that Sum[v; v in set]/Sum[v; v not in set] < eta + s_range = np.zeros(N, dtype=int) + evals_cumsum = stable_cumsum(evals, 1) + eta_range = evals_cumsum[:, -1:] / evals_cumsum[:, :-1] - 1 + for i in range(N): + s_range[i] = np.searchsorted(eta_range[i, ::-1], eta) + s_range += n_neighbors - nev # number of zero eigenvalues + + # Now calculate M. + # This is the [N x N] matrix whose null space is the desired embedding + M = M_container_constructor((N, N), dtype=np.float64) + + for i in range(N): + s_i = s_range[i] + + # select bottom s_i eigenvectors and calculate alpha + Vi = V[i, :, n_neighbors - s_i :] + alpha_i = np.linalg.norm(Vi.sum(0)) / np.sqrt(s_i) + + # compute Householder matrix which satisfies + # Hi*Vi.T*ones(n_neighbors) = alpha_i*ones(s) + # using prescription from paper + h = np.full(s_i, alpha_i) - np.dot(Vi.T, np.ones(n_neighbors)) + + norm_h = np.linalg.norm(h) + if norm_h < modified_tol: + h *= 0 + else: + h /= norm_h + + # Householder matrix is + # >> Hi = np.identity(s_i) - 2*np.outer(h,h) + # Then the weight matrix is + # >> Wi = np.dot(Vi,Hi) + (1-alpha_i) * w_reg[i,:,None] + # We do this much more efficiently: + Wi = Vi - 2 * np.outer(np.dot(Vi, h), h) + (1 - alpha_i) * w_reg[i, :, None] + + # Update M as follows: + # >> W_hat = np.zeros( (N,s_i) ) + # >> W_hat[neighbors[i],:] = Wi + # >> W_hat[i] -= 1 + # >> M += np.dot(W_hat,W_hat.T) + # We can do this much more efficiently: + nbrs_x, nbrs_y = np.meshgrid(neighbors[i], neighbors[i]) + M[nbrs_x, nbrs_y] += np.dot(Wi, Wi.T) + Wi_sum1 = Wi.sum(1) + M[i, neighbors[i]] -= Wi_sum1 + M[neighbors[i], [i]] -= Wi_sum1 + M[i, i] += s_i + + elif method == "ltsa": + neighbors = nbrs.kneighbors( + X, n_neighbors=n_neighbors + 1, return_distance=False + ) + neighbors = neighbors[:, 1:] + + M = M_container_constructor((N, N), dtype=np.float64) + + use_svd = n_neighbors > d_in + + for i in range(N): + Xi = X[neighbors[i]] + Xi -= Xi.mean(0) + + # compute n_components largest eigenvalues of Xi @ Xi^T + if use_svd: + v = svd(Xi, full_matrices=True)[0] + else: + Ci = np.dot(Xi, Xi.T) + v = eigh(Ci)[1][:, ::-1] + + Gi = np.zeros((n_neighbors, n_components + 1)) + Gi[:, 1:] = v[:, :n_components] + Gi[:, 0] = 1.0 / np.sqrt(n_neighbors) + + GiGiT = np.dot(Gi, Gi.T) + + nbrs_x, nbrs_y = np.meshgrid(neighbors[i], neighbors[i]) + M[nbrs_x, nbrs_y] -= GiGiT + + M[neighbors[i], neighbors[i]] += np.ones(shape=n_neighbors) + + if M_sparse: + M = M.tocsr() + + return null_space( + M, + n_components, + k_skip=1, + eigen_solver=eigen_solver, + tol=tol, + max_iter=max_iter, + random_state=random_state, + ) + + +@validate_params( + { + "X": ["array-like", NearestNeighbors], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "n_components": [Interval(Integral, 1, None, closed="left")], + "reg": [Interval(Real, 0, None, closed="left")], + "eigen_solver": [StrOptions({"auto", "arpack", "dense"})], + "tol": [Interval(Real, 0, None, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "method": [StrOptions({"standard", "hessian", "modified", "ltsa"})], + "hessian_tol": [Interval(Real, 0, None, closed="left")], + "modified_tol": [Interval(Real, 0, None, closed="left")], + "random_state": ["random_state"], + "n_jobs": [None, Integral], + }, + prefer_skip_nested_validation=True, +) +def locally_linear_embedding( + X, + *, + n_neighbors, + n_components, + reg=1e-3, + eigen_solver="auto", + tol=1e-6, + max_iter=100, + method="standard", + hessian_tol=1e-4, + modified_tol=1e-12, + random_state=None, + n_jobs=None, +): + """Perform a Locally Linear Embedding analysis on the data. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, NearestNeighbors} + Sample data, shape = (n_samples, n_features), in the form of a + numpy array or a NearestNeighbors object. + + n_neighbors : int + Number of neighbors to consider for each point. + + n_components : int + Number of coordinates for the manifold. + + reg : float, default=1e-3 + Regularization constant, multiplies the trace of the local covariance + matrix of the distances. + + eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' + auto : algorithm will attempt to choose the best method for input data + + arpack : use arnoldi iteration in shift-invert mode. + For this method, M may be a dense matrix, sparse matrix, + or general linear operator. + Warning: ARPACK can be unstable for some problems. It is + best to try several random seeds in order to check results. + + dense : use standard dense matrix operations for the eigenvalue + decomposition. For this method, M must be an array + or matrix type. This method should be avoided for + large problems. + + tol : float, default=1e-6 + Tolerance for 'arpack' method + Not used if eigen_solver=='dense'. + + max_iter : int, default=100 + Maximum number of iterations for the arpack solver. + + method : {'standard', 'hessian', 'modified', 'ltsa'}, default='standard' + standard : use the standard locally linear embedding algorithm. + see reference [1]_ + hessian : use the Hessian eigenmap method. This method requires + n_neighbors > n_components * (1 + (n_components + 1) / 2. + see reference [2]_ + modified : use the modified locally linear embedding algorithm. + see reference [3]_ + ltsa : use local tangent space alignment algorithm + see reference [4]_ + + hessian_tol : float, default=1e-4 + Tolerance for Hessian eigenmapping method. + Only used if method == 'hessian'. + + modified_tol : float, default=1e-12 + Tolerance for modified LLE method. + Only used if method == 'modified'. + + random_state : int, RandomState instance, default=None + Determines the random number generator when ``solver`` == 'arpack'. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + n_jobs : int or None, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + Y : ndarray of shape (n_samples, n_components) + Embedding vectors. + + squared_error : float + Reconstruction error for the embedding vectors. Equivalent to + ``norm(Y - W Y, 'fro')**2``, where W are the reconstruction weights. + + References + ---------- + + .. [1] Roweis, S. & Saul, L. Nonlinear dimensionality reduction + by locally linear embedding. Science 290:2323 (2000). + .. [2] Donoho, D. & Grimes, C. Hessian eigenmaps: Locally + linear embedding techniques for high-dimensional data. + Proc Natl Acad Sci U S A. 100:5591 (2003). + .. [3] `Zhang, Z. & Wang, J. MLLE: Modified Locally Linear + Embedding Using Multiple Weights. + `_ + .. [4] Zhang, Z. & Zha, H. Principal manifolds and nonlinear + dimensionality reduction via tangent space alignment. + Journal of Shanghai Univ. 8:406 (2004) + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.manifold import locally_linear_embedding + >>> X, _ = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> embedding, _ = locally_linear_embedding(X[:100],n_neighbors=5, n_components=2) + >>> embedding.shape + (100, 2) + """ + return _locally_linear_embedding( + X=X, + n_neighbors=n_neighbors, + n_components=n_components, + reg=reg, + eigen_solver=eigen_solver, + tol=tol, + max_iter=max_iter, + method=method, + hessian_tol=hessian_tol, + modified_tol=modified_tol, + random_state=random_state, + n_jobs=n_jobs, + ) + + +class LocallyLinearEmbedding( + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _UnstableArchMixin, + BaseEstimator, +): + """Locally Linear Embedding. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_neighbors : int, default=5 + Number of neighbors to consider for each point. + + n_components : int, default=2 + Number of coordinates for the manifold. + + reg : float, default=1e-3 + Regularization constant, multiplies the trace of the local covariance + matrix of the distances. + + eigen_solver : {'auto', 'arpack', 'dense'}, default='auto' + The solver used to compute the eigenvectors. The available options are: + + - `'auto'` : algorithm will attempt to choose the best method for input + data. + - `'arpack'` : use arnoldi iteration in shift-invert mode. For this + method, M may be a dense matrix, sparse matrix, or general linear + operator. + - `'dense'` : use standard dense matrix operations for the eigenvalue + decomposition. For this method, M must be an array or matrix type. + This method should be avoided for large problems. + + .. warning:: + ARPACK can be unstable for some problems. It is best to try several + random seeds in order to check results. + + tol : float, default=1e-6 + Tolerance for 'arpack' method + Not used if eigen_solver=='dense'. + + max_iter : int, default=100 + Maximum number of iterations for the arpack solver. + Not used if eigen_solver=='dense'. + + method : {'standard', 'hessian', 'modified', 'ltsa'}, default='standard' + - `standard`: use the standard locally linear embedding algorithm. see + reference [1]_ + - `hessian`: use the Hessian eigenmap method. This method requires + ``n_neighbors > n_components * (1 + (n_components + 1) / 2``. see + reference [2]_ + - `modified`: use the modified locally linear embedding algorithm. + see reference [3]_ + - `ltsa`: use local tangent space alignment algorithm. see + reference [4]_ + + hessian_tol : float, default=1e-4 + Tolerance for Hessian eigenmapping method. + Only used if ``method == 'hessian'``. + + modified_tol : float, default=1e-12 + Tolerance for modified LLE method. + Only used if ``method == 'modified'``. + + neighbors_algorithm : {'auto', 'brute', 'kd_tree', 'ball_tree'}, \ + default='auto' + Algorithm to use for nearest neighbors search, passed to + :class:`~sklearn.neighbors.NearestNeighbors` instance. + + random_state : int, RandomState instance, default=None + Determines the random number generator when + ``eigen_solver`` == 'arpack'. Pass an int for reproducible results + across multiple function calls. See :term:`Glossary `. + + n_jobs : int or None, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + embedding_ : array-like, shape [n_samples, n_components] + Stores the embedding vectors + + reconstruction_error_ : float + Reconstruction error associated with `embedding_` + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + nbrs_ : NearestNeighbors object + Stores nearest neighbors instance, including BallTree or KDtree + if applicable. + + See Also + -------- + SpectralEmbedding : Spectral embedding for non-linear dimensionality + reduction. + TSNE : Distributed Stochastic Neighbor Embedding. + + References + ---------- + + .. [1] Roweis, S. & Saul, L. Nonlinear dimensionality reduction + by locally linear embedding. Science 290:2323 (2000). + .. [2] Donoho, D. & Grimes, C. Hessian eigenmaps: Locally + linear embedding techniques for high-dimensional data. + Proc Natl Acad Sci U S A. 100:5591 (2003). + .. [3] `Zhang, Z. & Wang, J. MLLE: Modified Locally Linear + Embedding Using Multiple Weights. + `_ + .. [4] Zhang, Z. & Zha, H. Principal manifolds and nonlinear + dimensionality reduction via tangent space alignment. + Journal of Shanghai Univ. 8:406 (2004) + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.manifold import LocallyLinearEmbedding + >>> X, _ = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> embedding = LocallyLinearEmbedding(n_components=2) + >>> X_transformed = embedding.fit_transform(X[:100]) + >>> X_transformed.shape + (100, 2) + """ + + _parameter_constraints: dict = { + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "n_components": [Interval(Integral, 1, None, closed="left")], + "reg": [Interval(Real, 0, None, closed="left")], + "eigen_solver": [StrOptions({"auto", "arpack", "dense"})], + "tol": [Interval(Real, 0, None, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "method": [StrOptions({"standard", "hessian", "modified", "ltsa"})], + "hessian_tol": [Interval(Real, 0, None, closed="left")], + "modified_tol": [Interval(Real, 0, None, closed="left")], + "neighbors_algorithm": [StrOptions({"auto", "brute", "kd_tree", "ball_tree"})], + "random_state": ["random_state"], + "n_jobs": [None, Integral], + } + + def __init__( + self, + *, + n_neighbors=5, + n_components=2, + reg=1e-3, + eigen_solver="auto", + tol=1e-6, + max_iter=100, + method="standard", + hessian_tol=1e-4, + modified_tol=1e-12, + neighbors_algorithm="auto", + random_state=None, + n_jobs=None, + ): + self.n_neighbors = n_neighbors + self.n_components = n_components + self.reg = reg + self.eigen_solver = eigen_solver + self.tol = tol + self.max_iter = max_iter + self.method = method + self.hessian_tol = hessian_tol + self.modified_tol = modified_tol + self.random_state = random_state + self.neighbors_algorithm = neighbors_algorithm + self.n_jobs = n_jobs + + def _fit_transform(self, X): + self.nbrs_ = NearestNeighbors( + n_neighbors=self.n_neighbors, + algorithm=self.neighbors_algorithm, + n_jobs=self.n_jobs, + ) + + random_state = check_random_state(self.random_state) + X = validate_data(self, X, dtype=float) + self.nbrs_.fit(X) + self.embedding_, self.reconstruction_error_ = _locally_linear_embedding( + X=self.nbrs_, + n_neighbors=self.n_neighbors, + n_components=self.n_components, + eigen_solver=self.eigen_solver, + tol=self.tol, + max_iter=self.max_iter, + method=self.method, + hessian_tol=self.hessian_tol, + modified_tol=self.modified_tol, + random_state=random_state, + reg=self.reg, + n_jobs=self.n_jobs, + ) + self._n_features_out = self.embedding_.shape[1] + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Compute the embedding vectors for data X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training set. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + self : object + Fitted `LocallyLinearEmbedding` class instance. + """ + self._fit_transform(X) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y=None): + """Compute the embedding vectors for data X and transform X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training set. + + y : Ignored + Not used, present here for API consistency by convention. + + Returns + ------- + X_new : array-like, shape (n_samples, n_components) + Returns the instance itself. + """ + self._fit_transform(X) + return self.embedding_ + + def transform(self, X): + """ + Transform new points into embedding space. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training set. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + Returns the instance itself. + + Notes + ----- + Because of scaling performed by this method, it is discouraged to use + it together with methods that are not scale-invariant (like SVMs). + """ + check_is_fitted(self) + + X = validate_data(self, X, reset=False) + ind = self.nbrs_.kneighbors( + X, n_neighbors=self.n_neighbors, return_distance=False + ) + weights = barycenter_weights(X, self.nbrs_._fit_X, ind, reg=self.reg) + X_new = np.empty((X.shape[0], self.n_components)) + for i in range(X.shape[0]): + X_new[i] = np.dot(self.embedding_[ind[i]].T, weights[i]) + return X_new diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_mds.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_mds.py new file mode 100644 index 0000000000000000000000000000000000000000..6c31c72f7ef59e782be2476971e28b7f487dd644 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_mds.py @@ -0,0 +1,714 @@ +""" +Multi-dimensional Scaling (MDS). +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs + +from ..base import BaseEstimator, _fit_context +from ..isotonic import IsotonicRegression +from ..metrics import euclidean_distances +from ..utils import check_array, check_random_state, check_symmetric +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.parallel import Parallel, delayed +from ..utils.validation import validate_data + + +def _smacof_single( + dissimilarities, + metric=True, + n_components=2, + init=None, + max_iter=300, + verbose=0, + eps=1e-6, + random_state=None, + normalized_stress=False, +): + """Computes multidimensional scaling using SMACOF algorithm. + + Parameters + ---------- + dissimilarities : ndarray of shape (n_samples, n_samples) + Pairwise dissimilarities between the points. Must be symmetric. + + metric : bool, default=True + Compute metric or nonmetric SMACOF algorithm. + When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as + missing values. + + n_components : int, default=2 + Number of dimensions in which to immerse the dissimilarities. If an + ``init`` array is provided, this option is overridden and the shape of + ``init`` is used to determine the dimensionality of the embedding + space. + + init : ndarray of shape (n_samples, n_components), default=None + Starting configuration of the embedding to initialize the algorithm. By + default, the algorithm is initialized with a randomly chosen array. + + max_iter : int, default=300 + Maximum number of iterations of the SMACOF algorithm for a single run. + + verbose : int, default=0 + Level of verbosity. + + eps : float, default=1e-6 + The tolerance with respect to stress (normalized by the sum of squared + embedding distances) at which to declare convergence. + + .. versionchanged:: 1.7 + The default value for `eps` has changed from 1e-3 to 1e-6, as a result + of a bugfix in the computation of the convergence criterion. + + random_state : int, RandomState instance or None, default=None + Determines the random number generator used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + normalized_stress : bool, default=False + Whether to return normalized stress value (Stress-1) instead of raw + stress. + + .. versionadded:: 1.2 + + .. versionchanged:: 1.7 + Normalized stress is now supported for metric MDS as well. + + Returns + ------- + X : ndarray of shape (n_samples, n_components) + Coordinates of the points in a ``n_components``-space. + + stress : float + The final value of the stress (sum of squared distance of the + disparities and the distances for all constrained points). + If `normalized_stress=True`, returns Stress-1. + A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good, + 0.1 fair, and 0.2 poor [1]_. + + n_iter : int + The number of iterations corresponding to the best stress. + + References + ---------- + .. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J. + Psychometrika, 29 (1964) + + .. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric + hypothesis" Kruskal, J. Psychometrika, 29, (1964) + + .. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; + Groenen P. Springer Series in Statistics (1997) + """ + dissimilarities = check_symmetric(dissimilarities, raise_exception=True) + + n_samples = dissimilarities.shape[0] + random_state = check_random_state(random_state) + + dissimilarities_flat = ((1 - np.tri(n_samples)) * dissimilarities).ravel() + dissimilarities_flat_w = dissimilarities_flat[dissimilarities_flat != 0] + if init is None: + # Randomly choose initial configuration + X = random_state.uniform(size=n_samples * n_components) + X = X.reshape((n_samples, n_components)) + else: + # overrides the parameter p + n_components = init.shape[1] + if n_samples != init.shape[0]: + raise ValueError( + "init matrix should be of shape (%d, %d)" % (n_samples, n_components) + ) + X = init + distances = euclidean_distances(X) + + # Out of bounds condition cannot happen because we are transforming + # the training set here, but does sometimes get triggered in + # practice due to machine precision issues. Hence "clip". + ir = IsotonicRegression(out_of_bounds="clip") + + old_stress = None + for it in range(max_iter): + # Compute distance and monotonic regression + if metric: + disparities = dissimilarities + else: + distances_flat = distances.ravel() + # dissimilarities with 0 are considered as missing values + distances_flat_w = distances_flat[dissimilarities_flat != 0] + + # Compute the disparities using isotonic regression. + # For the first SMACOF iteration, use scaled original dissimilarities. + # (This choice follows the R implementation described in this paper: + # https://www.jstatsoft.org/article/view/v102i10) + if it < 1: + disparities_flat = dissimilarities_flat_w + else: + disparities_flat = ir.fit_transform( + dissimilarities_flat_w, distances_flat_w + ) + disparities = np.zeros_like(distances_flat) + disparities[dissimilarities_flat != 0] = disparities_flat + disparities = disparities.reshape((n_samples, n_samples)) + disparities *= np.sqrt( + (n_samples * (n_samples - 1) / 2) / (disparities**2).sum() + ) + disparities = disparities + disparities.T + + # Update X using the Guttman transform + distances[distances == 0] = 1e-5 + ratio = disparities / distances + B = -ratio + B[np.arange(len(B)), np.arange(len(B))] += ratio.sum(axis=1) + X = 1.0 / n_samples * np.dot(B, X) + + # Compute stress + distances = euclidean_distances(X) + stress = ((distances.ravel() - disparities.ravel()) ** 2).sum() / 2 + + if verbose >= 2: # pragma: no cover + print(f"Iteration {it}, stress {stress:.4f}") + if old_stress is not None: + sum_squared_distances = (distances.ravel() ** 2).sum() + if ((old_stress - stress) / (sum_squared_distances / 2)) < eps: + if verbose: # pragma: no cover + print("Convergence criterion reached.") + break + old_stress = stress + + if normalized_stress: + sum_squared_distances = (distances.ravel() ** 2).sum() + stress = np.sqrt(stress / (sum_squared_distances / 2)) + + return X, stress, it + 1 + + +# TODO(1.9): change default `n_init` to 1, see PR #31117 +@validate_params( + { + "dissimilarities": ["array-like"], + "metric": ["boolean"], + "n_components": [Interval(Integral, 1, None, closed="left")], + "init": ["array-like", None], + "n_init": [Interval(Integral, 1, None, closed="left"), StrOptions({"warn"})], + "n_jobs": [Integral, None], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "verbose": ["verbose"], + "eps": [Interval(Real, 0, None, closed="left")], + "random_state": ["random_state"], + "return_n_iter": ["boolean"], + "normalized_stress": ["boolean", StrOptions({"auto"})], + }, + prefer_skip_nested_validation=True, +) +def smacof( + dissimilarities, + *, + metric=True, + n_components=2, + init=None, + n_init="warn", + n_jobs=None, + max_iter=300, + verbose=0, + eps=1e-6, + random_state=None, + return_n_iter=False, + normalized_stress="auto", +): + """Compute multidimensional scaling using the SMACOF algorithm. + + The SMACOF (Scaling by MAjorizing a COmplicated Function) algorithm is a + multidimensional scaling algorithm which minimizes an objective function + (the *stress*) using a majorization technique. Stress majorization, also + known as the Guttman Transform, guarantees a monotone convergence of + stress, and is more powerful than traditional techniques such as gradient + descent. + + The SMACOF algorithm for metric MDS can be summarized by the following + steps: + + 1. Set an initial start configuration, randomly or not. + 2. Compute the stress + 3. Compute the Guttman Transform + 4. Iterate 2 and 3 until convergence. + + The nonmetric algorithm adds a monotonic regression step before computing + the stress. + + Parameters + ---------- + dissimilarities : array-like of shape (n_samples, n_samples) + Pairwise dissimilarities between the points. Must be symmetric. + + metric : bool, default=True + Compute metric or nonmetric SMACOF algorithm. + When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as + missing values. + + n_components : int, default=2 + Number of dimensions in which to immerse the dissimilarities. If an + ``init`` array is provided, this option is overridden and the shape of + ``init`` is used to determine the dimensionality of the embedding + space. + + init : array-like of shape (n_samples, n_components), default=None + Starting configuration of the embedding to initialize the algorithm. By + default, the algorithm is initialized with a randomly chosen array. + + n_init : int, default=8 + Number of times the SMACOF algorithm will be run with different + initializations. The final results will be the best output of the runs, + determined by the run with the smallest final stress. If ``init`` is + provided, this option is overridden and a single run is performed. + + .. versionchanged:: 1.9 + The default value for `n_iter` will change from 8 to 1 in version 1.9. + + n_jobs : int, default=None + The number of jobs to use for the computation. If multiple + initializations are used (``n_init``), each run of the algorithm is + computed in parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + max_iter : int, default=300 + Maximum number of iterations of the SMACOF algorithm for a single run. + + verbose : int, default=0 + Level of verbosity. + + eps : float, default=1e-6 + The tolerance with respect to stress (normalized by the sum of squared + embedding distances) at which to declare convergence. + + .. versionchanged:: 1.7 + The default value for `eps` has changed from 1e-3 to 1e-6, as a result + of a bugfix in the computation of the convergence criterion. + + random_state : int, RandomState instance or None, default=None + Determines the random number generator used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + return_n_iter : bool, default=False + Whether or not to return the number of iterations. + + normalized_stress : bool or "auto", default="auto" + Whether to return normalized stress value (Stress-1) instead of raw + stress. By default, metric MDS returns raw stress while non-metric MDS + returns normalized stress. + + .. versionadded:: 1.2 + + .. versionchanged:: 1.4 + The default value changed from `False` to `"auto"` in version 1.4. + + .. versionchanged:: 1.7 + Normalized stress is now supported for metric MDS as well. + + Returns + ------- + X : ndarray of shape (n_samples, n_components) + Coordinates of the points in a ``n_components``-space. + + stress : float + The final value of the stress (sum of squared distance of the + disparities and the distances for all constrained points). + If `normalized_stress=True`, returns Stress-1. + A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good, + 0.1 fair, and 0.2 poor [1]_. + + n_iter : int + The number of iterations corresponding to the best stress. Returned + only if ``return_n_iter`` is set to ``True``. + + References + ---------- + .. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J. + Psychometrika, 29 (1964) + + .. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric + hypothesis" Kruskal, J. Psychometrika, 29, (1964) + + .. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; + Groenen P. Springer Series in Statistics (1997) + + Examples + -------- + >>> import numpy as np + >>> from sklearn.manifold import smacof + >>> from sklearn.metrics import euclidean_distances + >>> X = np.array([[0, 1, 2], [1, 0, 3], [2, 3, 0]]) + >>> dissimilarities = euclidean_distances(X) + >>> Z, stress = smacof( + ... dissimilarities, n_components=2, n_init=1, eps=1e-6, random_state=42 + ... ) + >>> Z.shape + (3, 2) + >>> np.round(stress, 6).item() + 3.2e-05 + """ + + if n_init == "warn": + warnings.warn( + "The default value of `n_init` will change from 8 to 1 in 1.9.", + FutureWarning, + ) + n_init = 8 + + dissimilarities = check_array(dissimilarities) + random_state = check_random_state(random_state) + + if normalized_stress == "auto": + normalized_stress = not metric + + if hasattr(init, "__array__"): + init = np.asarray(init).copy() + if not n_init == 1: + warnings.warn( + "Explicit initial positions passed: " + "performing only one init of the MDS instead of %d" % n_init + ) + n_init = 1 + + best_pos, best_stress = None, None + + if effective_n_jobs(n_jobs) == 1: + for it in range(n_init): + pos, stress, n_iter_ = _smacof_single( + dissimilarities, + metric=metric, + n_components=n_components, + init=init, + max_iter=max_iter, + verbose=verbose, + eps=eps, + random_state=random_state, + normalized_stress=normalized_stress, + ) + if best_stress is None or stress < best_stress: + best_stress = stress + best_pos = pos.copy() + best_iter = n_iter_ + else: + seeds = random_state.randint(np.iinfo(np.int32).max, size=n_init) + results = Parallel(n_jobs=n_jobs, verbose=max(verbose - 1, 0))( + delayed(_smacof_single)( + dissimilarities, + metric=metric, + n_components=n_components, + init=init, + max_iter=max_iter, + verbose=verbose, + eps=eps, + random_state=seed, + normalized_stress=normalized_stress, + ) + for seed in seeds + ) + positions, stress, n_iters = zip(*results) + best = np.argmin(stress) + best_stress = stress[best] + best_pos = positions[best] + best_iter = n_iters[best] + + if return_n_iter: + return best_pos, best_stress, best_iter + else: + return best_pos, best_stress + + +# TODO(1.9): change default `n_init` to 1, see PR #31117 +class MDS(BaseEstimator): + """Multidimensional scaling. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=2 + Number of dimensions in which to immerse the dissimilarities. + + metric : bool, default=True + If ``True``, perform metric MDS; otherwise, perform nonmetric MDS. + When ``False`` (i.e. non-metric MDS), dissimilarities with 0 are considered as + missing values. + + n_init : int, default=4 + Number of times the SMACOF algorithm will be run with different + initializations. The final results will be the best output of the runs, + determined by the run with the smallest final stress. + + .. versionchanged:: 1.9 + The default value for `n_init` will change from 4 to 1 in version 1.9. + + max_iter : int, default=300 + Maximum number of iterations of the SMACOF algorithm for a single run. + + verbose : int, default=0 + Level of verbosity. + + eps : float, default=1e-6 + The tolerance with respect to stress (normalized by the sum of squared + embedding distances) at which to declare convergence. + + .. versionchanged:: 1.7 + The default value for `eps` has changed from 1e-3 to 1e-6, as a result + of a bugfix in the computation of the convergence criterion. + + n_jobs : int, default=None + The number of jobs to use for the computation. If multiple + initializations are used (``n_init``), each run of the algorithm is + computed in parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance or None, default=None + Determines the random number generator used to initialize the centers. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + dissimilarity : {'euclidean', 'precomputed'}, default='euclidean' + Dissimilarity measure to use: + + - 'euclidean': + Pairwise Euclidean distances between points in the dataset. + + - 'precomputed': + Pre-computed dissimilarities are passed directly to ``fit`` and + ``fit_transform``. + + normalized_stress : bool or "auto" default="auto" + Whether to return normalized stress value (Stress-1) instead of raw + stress. By default, metric MDS returns raw stress while non-metric MDS + returns normalized stress. + + .. versionadded:: 1.2 + + .. versionchanged:: 1.4 + The default value changed from `False` to `"auto"` in version 1.4. + + .. versionchanged:: 1.7 + Normalized stress is now supported for metric MDS as well. + + Attributes + ---------- + embedding_ : ndarray of shape (n_samples, n_components) + Stores the position of the dataset in the embedding space. + + stress_ : float + The final value of the stress (sum of squared distance of the + disparities and the distances for all constrained points). + If `normalized_stress=True`, returns Stress-1. + A value of 0 indicates "perfect" fit, 0.025 excellent, 0.05 good, + 0.1 fair, and 0.2 poor [1]_. + + dissimilarity_matrix_ : ndarray of shape (n_samples, n_samples) + Pairwise dissimilarities between the points. Symmetric matrix that: + + - either uses a custom dissimilarity matrix by setting `dissimilarity` + to 'precomputed'; + - or constructs a dissimilarity matrix from data using + Euclidean distances. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The number of iterations corresponding to the best stress. + + See Also + -------- + sklearn.decomposition.PCA : Principal component analysis that is a linear + dimensionality reduction method. + sklearn.decomposition.KernelPCA : Non-linear dimensionality reduction using + kernels and PCA. + TSNE : T-distributed Stochastic Neighbor Embedding. + Isomap : Manifold learning based on Isometric Mapping. + LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding. + SpectralEmbedding : Spectral embedding for non-linear dimensionality. + + References + ---------- + .. [1] "Nonmetric multidimensional scaling: a numerical method" Kruskal, J. + Psychometrika, 29 (1964) + + .. [2] "Multidimensional scaling by optimizing goodness of fit to a nonmetric + hypothesis" Kruskal, J. Psychometrika, 29, (1964) + + .. [3] "Modern Multidimensional Scaling - Theory and Applications" Borg, I.; + Groenen P. Springer Series in Statistics (1997) + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.manifold import MDS + >>> X, _ = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> embedding = MDS(n_components=2, n_init=1) + >>> X_transformed = embedding.fit_transform(X[:100]) + >>> X_transformed.shape + (100, 2) + + For a more detailed example of usage, see + :ref:`sphx_glr_auto_examples_manifold_plot_mds.py`. + + For a comparison of manifold learning techniques, see + :ref:`sphx_glr_auto_examples_manifold_plot_compare_methods.py`. + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 1, None, closed="left")], + "metric": ["boolean"], + "n_init": [Interval(Integral, 1, None, closed="left"), StrOptions({"warn"})], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "verbose": ["verbose"], + "eps": [Interval(Real, 0.0, None, closed="left")], + "n_jobs": [None, Integral], + "random_state": ["random_state"], + "dissimilarity": [StrOptions({"euclidean", "precomputed"})], + "normalized_stress": ["boolean", StrOptions({"auto"})], + } + + def __init__( + self, + n_components=2, + *, + metric=True, + n_init="warn", + max_iter=300, + verbose=0, + eps=1e-6, + n_jobs=None, + random_state=None, + dissimilarity="euclidean", + normalized_stress="auto", + ): + self.n_components = n_components + self.dissimilarity = dissimilarity + self.metric = metric + self.n_init = n_init + self.max_iter = max_iter + self.eps = eps + self.verbose = verbose + self.n_jobs = n_jobs + self.random_state = random_state + self.normalized_stress = normalized_stress + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.dissimilarity == "precomputed" + return tags + + def fit(self, X, y=None, init=None): + """ + Compute the position of the points in the embedding space. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Input data. If ``dissimilarity=='precomputed'``, the input should + be the dissimilarity matrix. + + y : Ignored + Not used, present for API consistency by convention. + + init : ndarray of shape (n_samples, n_components), default=None + Starting configuration of the embedding to initialize the SMACOF + algorithm. By default, the algorithm is initialized with a randomly + chosen array. + + Returns + ------- + self : object + Fitted estimator. + """ + self.fit_transform(X, init=init) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_transform(self, X, y=None, init=None): + """ + Fit the data from `X`, and returns the embedded coordinates. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) or \ + (n_samples, n_samples) + Input data. If ``dissimilarity=='precomputed'``, the input should + be the dissimilarity matrix. + + y : Ignored + Not used, present for API consistency by convention. + + init : ndarray of shape (n_samples, n_components), default=None + Starting configuration of the embedding to initialize the SMACOF + algorithm. By default, the algorithm is initialized with a randomly + chosen array. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + X transformed in the new space. + """ + + if self.n_init == "warn": + warnings.warn( + "The default value of `n_init` will change from 4 to 1 in 1.9.", + FutureWarning, + ) + self._n_init = 4 + else: + self._n_init = self.n_init + + X = validate_data(self, X) + if X.shape[0] == X.shape[1] and self.dissimilarity != "precomputed": + warnings.warn( + "The MDS API has changed. ``fit`` now constructs a" + " dissimilarity matrix from data. To use a custom " + "dissimilarity matrix, set " + "``dissimilarity='precomputed'``." + ) + + if self.dissimilarity == "precomputed": + self.dissimilarity_matrix_ = X + elif self.dissimilarity == "euclidean": + self.dissimilarity_matrix_ = euclidean_distances(X) + + self.embedding_, self.stress_, self.n_iter_ = smacof( + self.dissimilarity_matrix_, + metric=self.metric, + n_components=self.n_components, + init=init, + n_init=self._n_init, + n_jobs=self.n_jobs, + max_iter=self.max_iter, + verbose=self.verbose, + eps=self.eps, + random_state=self.random_state, + return_n_iter=True, + normalized_stress=self.normalized_stress, + ) + + return self.embedding_ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_spectral_embedding.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_spectral_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..1a3b95e023897567bd49cc5c0e969a240a1e2afd --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_spectral_embedding.py @@ -0,0 +1,776 @@ +"""Spectral Embedding.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy import sparse +from scipy.linalg import eigh +from scipy.sparse.csgraph import connected_components +from scipy.sparse.linalg import eigsh, lobpcg + +from ..base import BaseEstimator, _fit_context +from ..metrics.pairwise import rbf_kernel +from ..neighbors import NearestNeighbors, kneighbors_graph +from ..utils import ( + check_array, + check_random_state, + check_symmetric, +) +from ..utils._arpack import _init_arpack_v0 +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import _deterministic_vector_sign_flip +from ..utils.fixes import laplacian as csgraph_laplacian +from ..utils.fixes import parse_version, sp_version +from ..utils.validation import validate_data + + +def _graph_connected_component(graph, node_id): + """Find the largest graph connected components that contains one + given node. + + Parameters + ---------- + graph : array-like of shape (n_samples, n_samples) + Adjacency matrix of the graph, non-zero weight means an edge + between the nodes. + + node_id : int + The index of the query node of the graph. + + Returns + ------- + connected_components_matrix : array-like of shape (n_samples,) + An array of bool value indicating the indexes of the nodes + belonging to the largest connected components of the given query + node. + """ + n_node = graph.shape[0] + if sparse.issparse(graph): + # speed up row-wise access to boolean connection mask + graph = graph.tocsr() + connected_nodes = np.zeros(n_node, dtype=bool) + nodes_to_explore = np.zeros(n_node, dtype=bool) + nodes_to_explore[node_id] = True + for _ in range(n_node): + last_num_component = connected_nodes.sum() + np.logical_or(connected_nodes, nodes_to_explore, out=connected_nodes) + if last_num_component >= connected_nodes.sum(): + break + indices = np.where(nodes_to_explore)[0] + nodes_to_explore.fill(False) + for i in indices: + if sparse.issparse(graph): + # scipy not yet implemented 1D sparse slices; can be changed back to + # `neighbors = graph[i].toarray().ravel()` once implemented + neighbors = graph[[i], :].toarray().ravel() + else: + neighbors = graph[i] + np.logical_or(nodes_to_explore, neighbors, out=nodes_to_explore) + return connected_nodes + + +def _graph_is_connected(graph): + """Return whether the graph is connected (True) or Not (False). + + Parameters + ---------- + graph : {array-like, sparse matrix} of shape (n_samples, n_samples) + Adjacency matrix of the graph, non-zero weight means an edge + between the nodes. + + Returns + ------- + is_connected : bool + True means the graph is fully connected and False means not. + """ + if sparse.issparse(graph): + # Before Scipy 1.11.3, `connected_components` only supports 32-bit indices. + # PR: https://github.com/scipy/scipy/pull/18913 + # First integration in 1.11.3: https://github.com/scipy/scipy/pull/19279 + # TODO(jjerphan): Once SciPy 1.11.3 is the minimum supported version, use + # `accept_large_sparse=True`. + accept_large_sparse = sp_version >= parse_version("1.11.3") + graph = check_array( + graph, accept_sparse=True, accept_large_sparse=accept_large_sparse + ) + # sparse graph, find all the connected components + n_connected_components, _ = connected_components(graph) + return n_connected_components == 1 + else: + # dense graph, find all connected components start from node 0 + return _graph_connected_component(graph, 0).sum() == graph.shape[0] + + +def _set_diag(laplacian, value, norm_laplacian): + """Set the diagonal of the laplacian matrix and convert it to a + sparse format well suited for eigenvalue decomposition. + + Parameters + ---------- + laplacian : {ndarray, sparse matrix} + The graph laplacian. + + value : float + The value of the diagonal. + + norm_laplacian : bool + Whether the value of the diagonal should be changed or not. + + Returns + ------- + laplacian : {array, sparse matrix} + An array of matrix in a form that is well suited to fast + eigenvalue decomposition, depending on the band width of the + matrix. + """ + n_nodes = laplacian.shape[0] + # We need all entries in the diagonal to values + if not sparse.issparse(laplacian): + if norm_laplacian: + laplacian.flat[:: n_nodes + 1] = value + else: + laplacian = laplacian.tocoo() + if norm_laplacian: + diag_idx = laplacian.row == laplacian.col + laplacian.data[diag_idx] = value + # If the matrix has a small number of diagonals (as in the + # case of structured matrices coming from images), the + # dia format might be best suited for matvec products: + n_diags = np.unique(laplacian.row - laplacian.col).size + if n_diags <= 7: + # 3 or less outer diagonals on each side + laplacian = laplacian.todia() + else: + # csr has the fastest matvec and is thus best suited to + # arpack + laplacian = laplacian.tocsr() + return laplacian + + +@validate_params( + { + "adjacency": ["array-like", "sparse matrix"], + "n_components": [Interval(Integral, 1, None, closed="left")], + "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None], + "random_state": ["random_state"], + "eigen_tol": [Interval(Real, 0, None, closed="left"), StrOptions({"auto"})], + "norm_laplacian": ["boolean"], + "drop_first": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def spectral_embedding( + adjacency, + *, + n_components=8, + eigen_solver=None, + random_state=None, + eigen_tol="auto", + norm_laplacian=True, + drop_first=True, +): + """Project the sample on the first eigenvectors of the graph Laplacian. + + The adjacency matrix is used to compute a normalized graph Laplacian + whose spectrum (especially the eigenvectors associated to the + smallest eigenvalues) has an interpretation in terms of minimal + number of cuts necessary to split the graph into comparably sized + components. + + This embedding can also 'work' even if the ``adjacency`` variable is + not strictly the adjacency matrix of a graph but more generally + an affinity or similarity matrix between samples (for instance the + heat kernel of a euclidean distance matrix or a k-NN matrix). + + However care must taken to always make the affinity matrix symmetric + so that the eigenvector decomposition works as expected. + + Note : Laplacian Eigenmaps is the actual algorithm implemented here. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + adjacency : {array-like, sparse graph} of shape (n_samples, n_samples) + The adjacency matrix of the graph to embed. + + n_components : int, default=8 + The dimension of the projection subspace. + + eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems, + but may also lead to instabilities. If None, then ``'arpack'`` is + used. + + random_state : int, RandomState instance or None, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigen vectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="amg"` values of `tol<1e-5` may lead + to convergence issues and should be avoided. + + .. versionadded:: 1.2 + Added 'auto' option. + + norm_laplacian : bool, default=True + If True, then compute symmetric normalized Laplacian. + + drop_first : bool, default=True + Whether to drop the first eigenvector. For spectral embedding, this + should be True as the first eigenvector should be constant vector for + connected graph, but for spectral clustering, this should be kept as + False to retain the first eigenvector. + + Returns + ------- + embedding : ndarray of shape (n_samples, n_components) + The reduced samples. + + Notes + ----- + Spectral Embedding (Laplacian Eigenmaps) is most useful when the graph + has one connected component. If there graph has many components, the first + few eigenvectors will simply uncover the connected components of the graph. + + References + ---------- + * https://en.wikipedia.org/wiki/LOBPCG + + * :doi:`"Toward the Optimal Preconditioned Eigensolver: Locally Optimal + Block Preconditioned Conjugate Gradient Method", + Andrew V. Knyazev + <10.1137/S1064827500366124>` + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.neighbors import kneighbors_graph + >>> from sklearn.manifold import spectral_embedding + >>> X, _ = load_digits(return_X_y=True) + >>> X = X[:100] + >>> affinity_matrix = kneighbors_graph( + ... X, n_neighbors=int(X.shape[0] / 10), include_self=True + ... ) + >>> # make the matrix symmetric + >>> affinity_matrix = 0.5 * (affinity_matrix + affinity_matrix.T) + >>> embedding = spectral_embedding(affinity_matrix, n_components=2, random_state=42) + >>> embedding.shape + (100, 2) + """ + random_state = check_random_state(random_state) + + return _spectral_embedding( + adjacency, + n_components=n_components, + eigen_solver=eigen_solver, + random_state=random_state, + eigen_tol=eigen_tol, + norm_laplacian=norm_laplacian, + drop_first=drop_first, + ) + + +def _spectral_embedding( + adjacency, + *, + n_components=8, + eigen_solver=None, + random_state=None, + eigen_tol="auto", + norm_laplacian=True, + drop_first=True, +): + adjacency = check_symmetric(adjacency) + + if eigen_solver == "amg": + try: + from pyamg import smoothed_aggregation_solver + except ImportError as e: + raise ValueError( + "The eigen_solver was set to 'amg', but pyamg is not available." + ) from e + + if eigen_solver is None: + eigen_solver = "arpack" + + n_nodes = adjacency.shape[0] + # Whether to drop the first eigenvector + if drop_first: + n_components = n_components + 1 + + if not _graph_is_connected(adjacency): + warnings.warn( + "Graph is not fully connected, spectral embedding may not work as expected." + ) + + laplacian, dd = csgraph_laplacian( + adjacency, normed=norm_laplacian, return_diag=True + ) + if eigen_solver == "arpack" or ( + eigen_solver != "lobpcg" + and (not sparse.issparse(laplacian) or n_nodes < 5 * n_components) + ): + # lobpcg used with eigen_solver='amg' has bugs for low number of nodes + # for details see the source code in scipy: + # https://github.com/scipy/scipy/blob/v0.11.0/scipy/sparse/linalg/eigen + # /lobpcg/lobpcg.py#L237 + # or matlab: + # https://www.mathworks.com/matlabcentral/fileexchange/48-lobpcg-m + laplacian = _set_diag(laplacian, 1, norm_laplacian) + + # Here we'll use shift-invert mode for fast eigenvalues + # (see https://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html + # for a short explanation of what this means) + # Because the normalized Laplacian has eigenvalues between 0 and 2, + # I - L has eigenvalues between -1 and 1. ARPACK is most efficient + # when finding eigenvalues of largest magnitude (keyword which='LM') + # and when these eigenvalues are very large compared to the rest. + # For very large, very sparse graphs, I - L can have many, many + # eigenvalues very near 1.0. This leads to slow convergence. So + # instead, we'll use ARPACK's shift-invert mode, asking for the + # eigenvalues near 1.0. This effectively spreads-out the spectrum + # near 1.0 and leads to much faster convergence: potentially an + # orders-of-magnitude speedup over simply using keyword which='LA' + # in standard mode. + try: + # We are computing the opposite of the laplacian inplace so as + # to spare a memory allocation of a possibly very large array + tol = 0 if eigen_tol == "auto" else eigen_tol + laplacian *= -1 + v0 = _init_arpack_v0(laplacian.shape[0], random_state) + laplacian = check_array( + laplacian, accept_sparse="csr", accept_large_sparse=False + ) + _, diffusion_map = eigsh( + laplacian, k=n_components, sigma=1.0, which="LM", tol=tol, v0=v0 + ) + embedding = diffusion_map.T[n_components::-1] + if norm_laplacian: + # recover u = D^-1/2 x from the eigenvector output x + embedding = embedding / dd + except RuntimeError: + # When submatrices are exactly singular, an LU decomposition + # in arpack fails. We fallback to lobpcg + eigen_solver = "lobpcg" + # Revert the laplacian to its opposite to have lobpcg work + laplacian *= -1 + + elif eigen_solver == "amg": + # Use AMG to get a preconditioner and speed up the eigenvalue + # problem. + if not sparse.issparse(laplacian): + warnings.warn("AMG works better for sparse matrices") + 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 + # eigenvalue, corresponding to the trivial eigenvector, which is a + # constant. Using a singular matrix for preconditioning may result in + # random failures in LOBPCG and is not supported by the existing + # theory: + # see https://doi.org/10.1007/s10208-015-9297-1 + # Shift the Laplacian so its diagononal is not all ones. The shift + # does change the eigenpairs however, so we'll feed the shifted + # matrix to the solver and afterward set it back to the original. + diag_shift = 1e-5 * sparse.eye(laplacian.shape[0]) + laplacian += diag_shift + if hasattr(sparse, "csr_array") and isinstance(laplacian, sparse.csr_array): + # `pyamg` does not work with `csr_array` and we need to convert it to a + # `csr_matrix` object. + laplacian = sparse.csr_matrix(laplacian) + ml = smoothed_aggregation_solver(check_array(laplacian, accept_sparse="csr")) + laplacian -= diag_shift + + M = ml.aspreconditioner() + # Create initial approximation X to eigenvectors + X = random_state.standard_normal(size=(laplacian.shape[0], n_components + 1)) + X[:, 0] = dd.ravel() + X = X.astype(laplacian.dtype) + + tol = None if eigen_tol == "auto" else eigen_tol + _, diffusion_map = lobpcg(laplacian, X, M=M, tol=tol, largest=False) + embedding = diffusion_map.T + if norm_laplacian: + # recover u = D^-1/2 x from the eigenvector output x + embedding = embedding / dd + if embedding.shape[0] == 1: + raise ValueError + + if eigen_solver == "lobpcg": + 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 + # lobpcg will fallback to eigh, so we short circuit it + if sparse.issparse(laplacian): + laplacian = laplacian.toarray() + _, diffusion_map = eigh(laplacian, check_finite=False) + embedding = diffusion_map.T[:n_components] + if norm_laplacian: + # recover u = D^-1/2 x from the eigenvector output x + embedding = embedding / dd + else: + laplacian = _set_diag(laplacian, 1, norm_laplacian) + # We increase the number of eigenvectors requested, as lobpcg + # doesn't behave well in low dimension and create initial + # approximation X to eigenvectors + X = random_state.standard_normal( + size=(laplacian.shape[0], n_components + 1) + ) + X[:, 0] = dd.ravel() + X = X.astype(laplacian.dtype) + tol = None if eigen_tol == "auto" else eigen_tol + _, diffusion_map = lobpcg( + laplacian, X, tol=tol, largest=False, maxiter=2000 + ) + embedding = diffusion_map.T[:n_components] + if norm_laplacian: + # recover u = D^-1/2 x from the eigenvector output x + embedding = embedding / dd + if embedding.shape[0] == 1: + raise ValueError + + embedding = _deterministic_vector_sign_flip(embedding) + if drop_first: + return embedding[1:n_components].T + else: + return embedding[:n_components].T + + +class SpectralEmbedding(BaseEstimator): + """Spectral embedding for non-linear dimensionality reduction. + + Forms an affinity matrix given by the specified function and + applies spectral decomposition to the corresponding graph laplacian. + The resulting transformation is given by the value of the + eigenvectors for each data point. + + Note : Laplacian Eigenmaps is the actual algorithm implemented here. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=2 + The dimension of the projected subspace. + + affinity : {'nearest_neighbors', 'rbf', 'precomputed', \ + 'precomputed_nearest_neighbors'} or callable, \ + default='nearest_neighbors' + How to construct the affinity matrix. + - 'nearest_neighbors' : construct the affinity matrix by computing a + graph of nearest neighbors. + - 'rbf' : construct the affinity matrix by computing a radial basis + function (RBF) kernel. + - 'precomputed' : interpret ``X`` as a precomputed affinity matrix. + - 'precomputed_nearest_neighbors' : interpret ``X`` as a sparse graph + of precomputed nearest neighbors, and constructs the affinity matrix + by selecting the ``n_neighbors`` nearest neighbors. + - callable : use passed in function as affinity + the function takes in data matrix (n_samples, n_features) + and return affinity matrix (n_samples, n_samples). + + gamma : float, default=None + Kernel coefficient for rbf kernel. If None, gamma will be set to + 1/n_features. + + random_state : int, RandomState instance or None, default=None + A pseudo random number generator used for the initialization + of the lobpcg eigen vectors decomposition when `eigen_solver == + 'amg'`, and for the K-Means initialization. Use an int to make + the results deterministic across calls (See + :term:`Glossary `). + + .. note:: + When using `eigen_solver == 'amg'`, + it is necessary to also fix the global numpy seed with + `np.random.seed(int)` to get deterministic results. See + https://github.com/pyamg/pyamg/issues/139 for further + information. + + eigen_solver : {'arpack', 'lobpcg', 'amg'}, default=None + The eigenvalue decomposition strategy to use. AMG requires pyamg + to be installed. It can be faster on very large, sparse problems. + If None, then ``'arpack'`` is used. + + eigen_tol : float, default="auto" + Stopping criterion for eigendecomposition of the Laplacian matrix. + If `eigen_tol="auto"` then the passed tolerance will depend on the + `eigen_solver`: + + - If `eigen_solver="arpack"`, then `eigen_tol=0.0`; + - If `eigen_solver="lobpcg"` or `eigen_solver="amg"`, then + `eigen_tol=None` which configures the underlying `lobpcg` solver to + automatically resolve the value according to their heuristics. See, + :func:`scipy.sparse.linalg.lobpcg` for details. + + Note that when using `eigen_solver="lobpcg"` or `eigen_solver="amg"` + values of `tol<1e-5` may lead to convergence issues and should be + avoided. + + .. versionadded:: 1.2 + + n_neighbors : int, default=None + Number of nearest neighbors for nearest_neighbors graph building. + If None, n_neighbors will be set to max(n_samples/10, 1). + + n_jobs : int, default=None + The number of parallel jobs to run. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + embedding_ : ndarray of shape (n_samples, n_components) + Spectral embedding of the training matrix. + + affinity_matrix_ : ndarray of shape (n_samples, n_samples) + Affinity_matrix constructed from samples or precomputed. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_neighbors_ : int + Number of nearest neighbors effectively used. + + See Also + -------- + Isomap : Non-linear dimensionality reduction through Isometric Mapping. + + References + ---------- + + - :doi:`A Tutorial on Spectral Clustering, 2007 + Ulrike von Luxburg + <10.1007/s11222-007-9033-z>` + + - `On Spectral Clustering: Analysis and an algorithm, 2001 + Andrew Y. Ng, Michael I. Jordan, Yair Weiss + `_ + + - :doi:`Normalized cuts and image segmentation, 2000 + Jianbo Shi, Jitendra Malik + <10.1109/34.868688>` + + Examples + -------- + >>> from sklearn.datasets import load_digits + >>> from sklearn.manifold import SpectralEmbedding + >>> X, _ = load_digits(return_X_y=True) + >>> X.shape + (1797, 64) + >>> embedding = SpectralEmbedding(n_components=2) + >>> X_transformed = embedding.fit_transform(X[:100]) + >>> X_transformed.shape + (100, 2) + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 1, None, closed="left")], + "affinity": [ + StrOptions( + { + "nearest_neighbors", + "rbf", + "precomputed", + "precomputed_nearest_neighbors", + }, + ), + callable, + ], + "gamma": [Interval(Real, 0, None, closed="left"), None], + "random_state": ["random_state"], + "eigen_solver": [StrOptions({"arpack", "lobpcg", "amg"}), None], + "eigen_tol": [Interval(Real, 0, None, closed="left"), StrOptions({"auto"})], + "n_neighbors": [Interval(Integral, 1, None, closed="left"), None], + "n_jobs": [None, Integral], + } + + def __init__( + self, + n_components=2, + *, + affinity="nearest_neighbors", + gamma=None, + random_state=None, + eigen_solver=None, + eigen_tol="auto", + n_neighbors=None, + n_jobs=None, + ): + self.n_components = n_components + self.affinity = affinity + self.gamma = gamma + self.random_state = random_state + self.eigen_solver = eigen_solver + self.eigen_tol = eigen_tol + self.n_neighbors = n_neighbors + self.n_jobs = n_jobs + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + tags.input_tags.pairwise = self.affinity in [ + "precomputed", + "precomputed_nearest_neighbors", + ] + return tags + + def _get_affinity_matrix(self, X, Y=None): + """Calculate the affinity matrix from data + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + If affinity is "precomputed" + X : array-like of shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + Y: Ignored + + Returns + ------- + affinity_matrix of shape (n_samples, n_samples) + """ + if self.affinity == "precomputed": + self.affinity_matrix_ = X + return self.affinity_matrix_ + if self.affinity == "precomputed_nearest_neighbors": + estimator = NearestNeighbors( + n_neighbors=self.n_neighbors, n_jobs=self.n_jobs, metric="precomputed" + ).fit(X) + connectivity = estimator.kneighbors_graph(X=X, mode="connectivity") + self.affinity_matrix_ = 0.5 * (connectivity + connectivity.T) + return self.affinity_matrix_ + if self.affinity == "nearest_neighbors": + if sparse.issparse(X): + warnings.warn( + "Nearest neighbors affinity currently does " + "not support sparse input, falling back to " + "rbf affinity" + ) + self.affinity = "rbf" + else: + self.n_neighbors_ = ( + self.n_neighbors + if self.n_neighbors is not None + else max(int(X.shape[0] / 10), 1) + ) + self.affinity_matrix_ = kneighbors_graph( + X, self.n_neighbors_, include_self=True, n_jobs=self.n_jobs + ) + # currently only symmetric affinity_matrix supported + self.affinity_matrix_ = 0.5 * ( + self.affinity_matrix_ + self.affinity_matrix_.T + ) + return self.affinity_matrix_ + if self.affinity == "rbf": + self.gamma_ = self.gamma if self.gamma is not None else 1.0 / X.shape[1] + self.affinity_matrix_ = rbf_kernel(X, gamma=self.gamma_) + return self.affinity_matrix_ + self.affinity_matrix_ = self.affinity(X) + return self.affinity_matrix_ + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y=None): + """Fit the model from data in X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + If affinity is "precomputed" + X : {array-like, sparse matrix}, shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + Returns the instance itself. + """ + X = validate_data(self, X, accept_sparse="csr", ensure_min_samples=2) + + random_state = check_random_state(self.random_state) + + affinity_matrix = self._get_affinity_matrix(X) + self.embedding_ = _spectral_embedding( + affinity_matrix, + n_components=self.n_components, + eigen_solver=self.eigen_solver, + eigen_tol=self.eigen_tol, + random_state=random_state, + ) + return self + + def fit_transform(self, X, y=None): + """Fit the model from data in X and transform X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples + and `n_features` is the number of features. + + If affinity is "precomputed" + X : {array-like, sparse matrix} of shape (n_samples, n_samples), + Interpret X as precomputed adjacency graph computed from + samples. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + X_new : array-like of shape (n_samples, n_components) + Spectral embedding of the training matrix. + """ + self.fit(X) + return self.embedding_ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_t_sne.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_t_sne.py new file mode 100644 index 0000000000000000000000000000000000000000..51882a5b38abdec7b60c26c1794dafedeef4f666 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_t_sne.py @@ -0,0 +1,1184 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# This is the exact and Barnes-Hut t-SNE implementation. There are other +# modifications of the algorithm: +# * Fast Optimization for t-SNE: +# https://cseweb.ucsd.edu/~lvdmaaten/workshops/nips2010/papers/vandermaaten.pdf + +from numbers import Integral, Real +from time import time + +import numpy as np +from scipy import linalg +from scipy.sparse import csr_matrix, issparse +from scipy.spatial.distance import pdist, squareform + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..decomposition import PCA +from ..metrics.pairwise import _VALID_METRICS, pairwise_distances +from ..neighbors import NearestNeighbors +from ..utils import check_random_state +from ..utils._openmp_helpers import _openmp_effective_n_threads +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.validation import _num_samples, check_non_negative, validate_data + +# mypy error: Module 'sklearn.manifold' has no attribute '_utils' +# mypy error: Module 'sklearn.manifold' has no attribute '_barnes_hut_tsne' +from . import _barnes_hut_tsne, _utils # type: ignore[attr-defined] + +MACHINE_EPSILON = np.finfo(np.double).eps + + +def _joint_probabilities(distances, desired_perplexity, verbose): + """Compute joint probabilities p_ij from distances. + + Parameters + ---------- + distances : ndarray of shape (n_samples * (n_samples-1) / 2,) + Distances of samples are stored as condensed matrices, i.e. + we omit the diagonal and duplicate entries and store everything + in a one-dimensional array. + + desired_perplexity : float + Desired perplexity of the joint probability distributions. + + verbose : int + Verbosity level. + + Returns + ------- + P : ndarray of shape (n_samples * (n_samples-1) / 2,) + Condensed joint probability matrix. + """ + # Compute conditional probabilities such that they approximately match + # the desired perplexity + distances = distances.astype(np.float32, copy=False) + conditional_P = _utils._binary_search_perplexity( + distances, desired_perplexity, verbose + ) + P = conditional_P + conditional_P.T + sum_P = np.maximum(np.sum(P), MACHINE_EPSILON) + P = np.maximum(squareform(P) / sum_P, MACHINE_EPSILON) + return P + + +def _joint_probabilities_nn(distances, desired_perplexity, verbose): + """Compute joint probabilities p_ij from distances using just nearest + neighbors. + + This method is approximately equal to _joint_probabilities. The latter + is O(N), but limiting the joint probability to nearest neighbors improves + this substantially to O(uN). + + Parameters + ---------- + distances : sparse matrix of shape (n_samples, n_samples) + Distances of samples to its n_neighbors nearest neighbors. All other + distances are left to zero (and are not materialized in memory). + Matrix should be of CSR format. + + desired_perplexity : float + Desired perplexity of the joint probability distributions. + + verbose : int + Verbosity level. + + Returns + ------- + P : sparse matrix of shape (n_samples, n_samples) + Condensed joint probability matrix with only nearest neighbors. Matrix + will be of CSR format. + """ + t0 = time() + # Compute conditional probabilities such that they approximately match + # the desired perplexity + distances.sort_indices() + n_samples = distances.shape[0] + distances_data = distances.data.reshape(n_samples, -1) + distances_data = distances_data.astype(np.float32, copy=False) + conditional_P = _utils._binary_search_perplexity( + distances_data, desired_perplexity, verbose + ) + assert np.all(np.isfinite(conditional_P)), "All probabilities should be finite" + + # Symmetrize the joint probability distribution using sparse operations + P = csr_matrix( + (conditional_P.ravel(), distances.indices, distances.indptr), + shape=(n_samples, n_samples), + ) + P = P + P.T + + # Normalize the joint probability distribution + sum_P = np.maximum(P.sum(), MACHINE_EPSILON) + P /= sum_P + + assert np.all(np.abs(P.data) <= 1.0) + if verbose >= 2: + duration = time() - t0 + print("[t-SNE] Computed conditional probabilities in {:.3f}s".format(duration)) + return P + + +def _kl_divergence( + params, + P, + degrees_of_freedom, + n_samples, + n_components, + skip_num_points=0, + compute_error=True, +): + """t-SNE objective function: gradient of the KL divergence + of p_ijs and q_ijs and the absolute error. + + Parameters + ---------- + params : ndarray of shape (n_params,) + Unraveled embedding. + + P : ndarray of shape (n_samples * (n_samples-1) / 2,) + Condensed joint probability matrix. + + degrees_of_freedom : int + Degrees of freedom of the Student's-t distribution. + + n_samples : int + Number of samples. + + n_components : int + Dimension of the embedded space. + + skip_num_points : int, default=0 + This does not compute the gradient for points with indices below + `skip_num_points`. This is useful when computing transforms of new + data where you'd like to keep the old data fixed. + + compute_error: bool, default=True + If False, the kl_divergence is not computed and returns NaN. + + Returns + ------- + kl_divergence : float + Kullback-Leibler divergence of p_ij and q_ij. + + grad : ndarray of shape (n_params,) + Unraveled gradient of the Kullback-Leibler divergence with respect to + the embedding. + """ + X_embedded = params.reshape(n_samples, n_components) + + # Q is a heavy-tailed distribution: Student's t-distribution + dist = pdist(X_embedded, "sqeuclidean") + dist /= degrees_of_freedom + dist += 1.0 + dist **= (degrees_of_freedom + 1.0) / -2.0 + Q = np.maximum(dist / (2.0 * np.sum(dist)), MACHINE_EPSILON) + + # Optimization trick below: np.dot(x, y) is faster than + # np.sum(x * y) because it calls BLAS + + # Objective: C (Kullback-Leibler divergence of P and Q) + if compute_error: + kl_divergence = 2.0 * np.dot(P, np.log(np.maximum(P, MACHINE_EPSILON) / Q)) + else: + kl_divergence = np.nan + + # Gradient: dC/dY + # pdist always returns double precision distances. Thus we need to take + grad = np.ndarray((n_samples, n_components), dtype=params.dtype) + PQd = squareform((P - Q) * dist) + for i in range(skip_num_points, n_samples): + grad[i] = np.dot(np.ravel(PQd[i], order="K"), X_embedded[i] - X_embedded) + grad = grad.ravel() + c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom + grad *= c + + return kl_divergence, grad + + +def _kl_divergence_bh( + params, + P, + degrees_of_freedom, + n_samples, + n_components, + angle=0.5, + skip_num_points=0, + verbose=False, + compute_error=True, + num_threads=1, +): + """t-SNE objective function: KL divergence of p_ijs and q_ijs. + + Uses Barnes-Hut tree methods to calculate the gradient that + runs in O(NlogN) instead of O(N^2). + + Parameters + ---------- + params : ndarray of shape (n_params,) + Unraveled embedding. + + P : sparse matrix of shape (n_samples, n_sample) + Sparse approximate joint probability matrix, computed only for the + k nearest-neighbors and symmetrized. Matrix should be of CSR format. + + degrees_of_freedom : int + Degrees of freedom of the Student's-t distribution. + + n_samples : int + Number of samples. + + n_components : int + Dimension of the embedded space. + + angle : float, default=0.5 + This is the trade-off between speed and accuracy for Barnes-Hut T-SNE. + 'angle' is the angular size (referred to as theta in [3]) of a distant + node as measured from a point. If this size is below 'angle' then it is + used as a summary node of all points contained within it. + This method is not very sensitive to changes in this parameter + in the range of 0.2 - 0.8. Angle less than 0.2 has quickly increasing + computation time and angle greater 0.8 has quickly increasing error. + + skip_num_points : int, default=0 + This does not compute the gradient for points with indices below + `skip_num_points`. This is useful when computing transforms of new + data where you'd like to keep the old data fixed. + + verbose : int, default=False + Verbosity level. + + compute_error: bool, default=True + If False, the kl_divergence is not computed and returns NaN. + + num_threads : int, default=1 + Number of threads used to compute the gradient. This is set here to + avoid calling _openmp_effective_n_threads for each gradient step. + + Returns + ------- + kl_divergence : float + Kullback-Leibler divergence of p_ij and q_ij. + + grad : ndarray of shape (n_params,) + Unraveled gradient of the Kullback-Leibler divergence with respect to + the embedding. + """ + params = params.astype(np.float32, copy=False) + X_embedded = params.reshape(n_samples, n_components) + + val_P = P.data.astype(np.float32, copy=False) + neighbors = P.indices.astype(np.int64, copy=False) + indptr = P.indptr.astype(np.int64, copy=False) + + grad = np.zeros(X_embedded.shape, dtype=np.float32) + error = _barnes_hut_tsne.gradient( + val_P, + X_embedded, + neighbors, + indptr, + grad, + angle, + n_components, + verbose, + dof=degrees_of_freedom, + compute_error=compute_error, + num_threads=num_threads, + ) + c = 2.0 * (degrees_of_freedom + 1.0) / degrees_of_freedom + grad = grad.ravel() + grad *= c + + return error, grad + + +def _gradient_descent( + objective, + p0, + it, + max_iter, + n_iter_check=1, + n_iter_without_progress=300, + momentum=0.8, + learning_rate=200.0, + min_gain=0.01, + min_grad_norm=1e-7, + verbose=0, + args=None, + kwargs=None, +): + """Batch gradient descent with momentum and individual gains. + + Parameters + ---------- + objective : callable + Should return a tuple of cost and gradient for a given parameter + vector. When expensive to compute, the cost can optionally + be None and can be computed every n_iter_check steps using + the objective_error function. + + p0 : array-like of shape (n_params,) + Initial parameter vector. + + it : int + Current number of iterations (this function will be called more than + once during the optimization). + + max_iter : int + Maximum number of gradient descent iterations. + + n_iter_check : int, default=1 + Number of iterations before evaluating the global error. If the error + is sufficiently low, we abort the optimization. + + n_iter_without_progress : int, default=300 + Maximum number of iterations without progress before we abort the + optimization. + + momentum : float within (0.0, 1.0), default=0.8 + The momentum generates a weight for previous gradients that decays + exponentially. + + learning_rate : float, default=200.0 + The learning rate for t-SNE is usually in the range [10.0, 1000.0]. If + the learning rate is too high, the data may look like a 'ball' with any + point approximately equidistant from its nearest neighbours. If the + learning rate is too low, most points may look compressed in a dense + cloud with few outliers. + + min_gain : float, default=0.01 + Minimum individual gain for each parameter. + + min_grad_norm : float, default=1e-7 + If the gradient norm is below this threshold, the optimization will + be aborted. + + verbose : int, default=0 + Verbosity level. + + args : sequence, default=None + Arguments to pass to objective function. + + kwargs : dict, default=None + Keyword arguments to pass to objective function. + + Returns + ------- + p : ndarray of shape (n_params,) + Optimum parameters. + + error : float + Optimum. + + i : int + Last iteration. + """ + if args is None: + args = [] + if kwargs is None: + kwargs = {} + + p = p0.copy().ravel() + update = np.zeros_like(p) + gains = np.ones_like(p) + error = np.finfo(float).max + best_error = np.finfo(float).max + best_iter = i = it + + tic = time() + for i in range(it, max_iter): + check_convergence = (i + 1) % n_iter_check == 0 + # only compute the error when needed + kwargs["compute_error"] = check_convergence or i == max_iter - 1 + + error, grad = objective(p, *args, **kwargs) + + inc = update * grad < 0.0 + dec = np.invert(inc) + gains[inc] += 0.2 + gains[dec] *= 0.8 + np.clip(gains, min_gain, np.inf, out=gains) + grad *= gains + update = momentum * update - learning_rate * grad + p += update + + if check_convergence: + toc = time() + duration = toc - tic + tic = toc + grad_norm = linalg.norm(grad) + + if verbose >= 2: + print( + "[t-SNE] Iteration %d: error = %.7f," + " gradient norm = %.7f" + " (%s iterations in %0.3fs)" + % (i + 1, error, grad_norm, n_iter_check, duration) + ) + + if error < best_error: + best_error = error + best_iter = i + elif i - best_iter > n_iter_without_progress: + if verbose >= 2: + print( + "[t-SNE] Iteration %d: did not make any progress " + "during the last %d episodes. Finished." + % (i + 1, n_iter_without_progress) + ) + break + if grad_norm <= min_grad_norm: + if verbose >= 2: + print( + "[t-SNE] Iteration %d: gradient norm %f. Finished." + % (i + 1, grad_norm) + ) + break + + return p, error, i + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "X_embedded": ["array-like", "sparse matrix"], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + }, + prefer_skip_nested_validation=True, +) +def trustworthiness(X, X_embedded, *, n_neighbors=5, metric="euclidean"): + r"""Indicate to what extent the local structure is retained. + + The trustworthiness is within [0, 1]. It is defined as + + .. math:: + + T(k) = 1 - \frac{2}{nk (2n - 3k - 1)} \sum^n_{i=1} + \sum_{j \in \mathcal{N}_{i}^{k}} \max(0, (r(i, j) - k)) + + where for each sample i, :math:`\mathcal{N}_{i}^{k}` are its k nearest + neighbors in the output space, and every sample j is its :math:`r(i, j)`-th + nearest neighbor in the input space. In other words, any unexpected nearest + neighbors in the output space are penalised in proportion to their rank in + the input space. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. + + X_embedded : {array-like, sparse matrix} of shape (n_samples, n_components) + Embedding of the training data in low-dimensional space. + + n_neighbors : int, default=5 + The number of neighbors that will be considered. Should be fewer than + `n_samples / 2` to ensure the trustworthiness to lies within [0, 1], as + mentioned in [1]_. An error will be raised otherwise. + + metric : str or callable, default='euclidean' + Which metric to use for computing pairwise distances between samples + from the original input space. If metric is 'precomputed', X must be a + matrix of pairwise distances or squared distances. Otherwise, for a list + of available metrics, see the documentation of argument metric in + `sklearn.pairwise.pairwise_distances` and metrics listed in + `sklearn.metrics.pairwise.PAIRWISE_DISTANCE_FUNCTIONS`. Note that the + "cosine" metric uses :func:`~sklearn.metrics.pairwise.cosine_distances`. + + .. versionadded:: 0.20 + + Returns + ------- + trustworthiness : float + Trustworthiness of the low-dimensional embedding. + + References + ---------- + .. [1] Jarkko Venna and Samuel Kaski. 2001. Neighborhood + Preservation in Nonlinear Projection Methods: An Experimental Study. + In Proceedings of the International Conference on Artificial Neural Networks + (ICANN '01). Springer-Verlag, Berlin, Heidelberg, 485-491. + + .. [2] Laurens van der Maaten. Learning a Parametric Embedding by Preserving + Local Structure. Proceedings of the Twelfth International Conference on + Artificial Intelligence and Statistics, PMLR 5:384-391, 2009. + + Examples + -------- + >>> from sklearn.datasets import make_blobs + >>> from sklearn.decomposition import PCA + >>> from sklearn.manifold import trustworthiness + >>> X, _ = make_blobs(n_samples=100, n_features=10, centers=3, random_state=42) + >>> X_embedded = PCA(n_components=2).fit_transform(X) + >>> print(f"{trustworthiness(X, X_embedded, n_neighbors=5):.2f}") + 0.92 + """ + n_samples = _num_samples(X) + if n_neighbors >= n_samples / 2: + raise ValueError( + f"n_neighbors ({n_neighbors}) should be less than n_samples / 2" + f" ({n_samples / 2})" + ) + dist_X = pairwise_distances(X, metric=metric) + if metric == "precomputed": + dist_X = dist_X.copy() + # we set the diagonal to np.inf to exclude the points themselves from + # their own neighborhood + np.fill_diagonal(dist_X, np.inf) + ind_X = np.argsort(dist_X, axis=1) + # `ind_X[i]` is the index of sorted distances between i and other samples + ind_X_embedded = ( + NearestNeighbors(n_neighbors=n_neighbors) + .fit(X_embedded) + .kneighbors(return_distance=False) + ) + + # We build an inverted index of neighbors in the input space: For sample i, + # we define `inverted_index[i]` as the inverted index of sorted distances: + # inverted_index[i][ind_X[i]] = np.arange(1, n_sample + 1) + inverted_index = np.zeros((n_samples, n_samples), dtype=int) + ordered_indices = np.arange(n_samples + 1) + inverted_index[ordered_indices[:-1, np.newaxis], ind_X] = ordered_indices[1:] + ranks = ( + inverted_index[ordered_indices[:-1, np.newaxis], ind_X_embedded] - n_neighbors + ) + t = np.sum(ranks[ranks > 0]) + t = 1.0 - t * ( + 2.0 / (n_samples * n_neighbors * (2.0 * n_samples - 3.0 * n_neighbors - 1.0)) + ) + return t + + +class TSNE(ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator): + """T-distributed Stochastic Neighbor Embedding. + + t-SNE [1] is a tool to visualize high-dimensional data. It converts + similarities between data points to joint probabilities and tries + to minimize the Kullback-Leibler divergence between the joint + probabilities of the low-dimensional embedding and the + high-dimensional data. t-SNE has a cost function that is not convex, + i.e. with different initializations we can get different results. + + It is highly recommended to use another dimensionality reduction + method (e.g. PCA for dense data or TruncatedSVD for sparse data) + to reduce the number of dimensions to a reasonable amount (e.g. 50) + if the number of features is very high. This will suppress some + noise and speed up the computation of pairwise distances between + samples. For more tips see Laurens van der Maaten's FAQ [2]. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=2 + Dimension of the embedded space. + + perplexity : float, default=30.0 + The perplexity is related to the number of nearest neighbors that + is used in other manifold learning algorithms. Larger datasets + usually require a larger perplexity. Consider selecting a value + between 5 and 50. Different values can result in significantly + different results. The perplexity must be less than the number + of samples. + + early_exaggeration : float, default=12.0 + Controls how tight natural clusters in the original space are in + the embedded space and how much space will be between them. For + larger values, the space between natural clusters will be larger + in the embedded space. Again, the choice of this parameter is not + very critical. If the cost function increases during initial + optimization, the early exaggeration factor or the learning rate + might be too high. + + learning_rate : float or "auto", default="auto" + The learning rate for t-SNE is usually in the range [10.0, 1000.0]. If + the learning rate is too high, the data may look like a 'ball' with any + point approximately equidistant from its nearest neighbours. If the + learning rate is too low, most points may look compressed in a dense + cloud with few outliers. If the cost function gets stuck in a bad local + minimum increasing the learning rate may help. + Note that many other t-SNE implementations (bhtsne, FIt-SNE, openTSNE, + etc.) use a definition of learning_rate that is 4 times smaller than + ours. So our learning_rate=200 corresponds to learning_rate=800 in + those other implementations. The 'auto' option sets the learning_rate + to `max(N / early_exaggeration / 4, 50)` where N is the sample size, + following [4] and [5]. + + .. versionchanged:: 1.2 + The default value changed to `"auto"`. + + max_iter : int, default=1000 + Maximum number of iterations for the optimization. Should be at + least 250. + + .. versionchanged:: 1.5 + Parameter name changed from `n_iter` to `max_iter`. + + n_iter_without_progress : int, default=300 + Maximum number of iterations without progress before we abort the + optimization, used after 250 initial iterations with early + exaggeration. Note that progress is only checked every 50 iterations so + this value is rounded to the next multiple of 50. + + .. versionadded:: 0.17 + parameter *n_iter_without_progress* to control stopping criteria. + + min_grad_norm : float, default=1e-7 + If the gradient norm is below this threshold, the optimization will + be stopped. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by scipy.spatial.distance.pdist for its metric parameter, or + a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. The default is "euclidean" which is + interpreted as squared euclidean distance. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + .. versionadded:: 1.1 + + init : {"random", "pca"} or ndarray of shape (n_samples, n_components), \ + default="pca" + Initialization of embedding. + PCA initialization cannot be used with precomputed distances and is + usually more globally stable than random initialization. + + .. versionchanged:: 1.2 + The default value changed to `"pca"`. + + verbose : int, default=0 + Verbosity level. + + random_state : int, RandomState instance or None, default=None + Determines the random number generator. Pass an int for reproducible + results across multiple function calls. Note that different + initializations might result in different local minima of the cost + function. See :term:`Glossary `. + + method : {'barnes_hut', 'exact'}, default='barnes_hut' + By default the gradient calculation algorithm uses Barnes-Hut + approximation running in O(NlogN) time. method='exact' + will run on the slower, but exact, algorithm in O(N^2) time. The + exact algorithm should be used when nearest-neighbor errors need + to be better than 3%. However, the exact method cannot scale to + millions of examples. + + .. versionadded:: 0.17 + Approximate optimization *method* via the Barnes-Hut. + + angle : float, default=0.5 + Only used if method='barnes_hut' + This is the trade-off between speed and accuracy for Barnes-Hut T-SNE. + 'angle' is the angular size (referred to as theta in [3]) of a distant + node as measured from a point. If this size is below 'angle' then it is + used as a summary node of all points contained within it. + This method is not very sensitive to changes in this parameter + in the range of 0.2 - 0.8. Angle less than 0.2 has quickly increasing + computation time and angle greater 0.8 has quickly increasing error. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. This parameter + has no impact when ``metric="precomputed"`` or + (``metric="euclidean"`` and ``method="exact"``). + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + .. versionadded:: 0.22 + + Attributes + ---------- + embedding_ : array-like of shape (n_samples, n_components) + Stores the embedding vectors. + + kl_divergence_ : float + Kullback-Leibler divergence after optimization. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + learning_rate_ : float + Effective learning rate. + + .. versionadded:: 1.2 + + n_iter_ : int + Number of iterations run. + + See Also + -------- + sklearn.decomposition.PCA : Principal component analysis that is a linear + dimensionality reduction method. + sklearn.decomposition.KernelPCA : Non-linear dimensionality reduction using + kernels and PCA. + MDS : Manifold learning using multidimensional scaling. + Isomap : Manifold learning based on Isometric Mapping. + LocallyLinearEmbedding : Manifold learning using Locally Linear Embedding. + SpectralEmbedding : Spectral embedding for non-linear dimensionality. + + Notes + ----- + For an example of using :class:`~sklearn.manifold.TSNE` in combination with + :class:`~sklearn.neighbors.KNeighborsTransformer` see + :ref:`sphx_glr_auto_examples_neighbors_approximate_nearest_neighbors.py`. + + References + ---------- + + [1] van der Maaten, L.J.P.; Hinton, G.E. Visualizing High-Dimensional Data + Using t-SNE. Journal of Machine Learning Research 9:2579-2605, 2008. + + [2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding + https://lvdmaaten.github.io/tsne/ + + [3] L.J.P. van der Maaten. Accelerating t-SNE using Tree-Based Algorithms. + Journal of Machine Learning Research 15(Oct):3221-3245, 2014. + https://lvdmaaten.github.io/publications/papers/JMLR_2014.pdf + + [4] Belkina, A. C., Ciccolella, C. O., Anno, R., Halpert, R., Spidlen, J., + & Snyder-Cappione, J. E. (2019). Automated optimized parameters for + T-distributed stochastic neighbor embedding improve visualization + and analysis of large datasets. Nature Communications, 10(1), 1-12. + + [5] Kobak, D., & Berens, P. (2019). The art of using t-SNE for single-cell + transcriptomics. Nature Communications, 10(1), 1-14. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.manifold import TSNE + >>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) + >>> X_embedded = TSNE(n_components=2, learning_rate='auto', + ... init='random', perplexity=3).fit_transform(X) + >>> X_embedded.shape + (4, 2) + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 1, None, closed="left")], + "perplexity": [Interval(Real, 0, None, closed="neither")], + "early_exaggeration": [Interval(Real, 1, None, closed="left")], + "learning_rate": [ + StrOptions({"auto"}), + Interval(Real, 0, None, closed="neither"), + ], + "max_iter": [Interval(Integral, 250, None, closed="left")], + "n_iter_without_progress": [Interval(Integral, -1, None, closed="left")], + "min_grad_norm": [Interval(Real, 0, None, closed="left")], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "metric_params": [dict, None], + "init": [ + StrOptions({"pca", "random"}), + np.ndarray, + ], + "verbose": ["verbose"], + "random_state": ["random_state"], + "method": [StrOptions({"barnes_hut", "exact"})], + "angle": [Interval(Real, 0, 1, closed="both")], + "n_jobs": [None, Integral], + } + + # Control the number of exploration iterations with early_exaggeration on + _EXPLORATION_MAX_ITER = 250 + + # Control the number of iterations between progress checks + _N_ITER_CHECK = 50 + + def __init__( + self, + n_components=2, + *, + perplexity=30.0, + early_exaggeration=12.0, + learning_rate="auto", + max_iter=1000, + n_iter_without_progress=300, + min_grad_norm=1e-7, + metric="euclidean", + metric_params=None, + init="pca", + verbose=0, + random_state=None, + method="barnes_hut", + angle=0.5, + n_jobs=None, + ): + self.n_components = n_components + self.perplexity = perplexity + self.early_exaggeration = early_exaggeration + self.learning_rate = learning_rate + self.max_iter = max_iter + self.n_iter_without_progress = n_iter_without_progress + self.min_grad_norm = min_grad_norm + self.metric = metric + self.metric_params = metric_params + self.init = init + self.verbose = verbose + self.random_state = random_state + self.method = method + self.angle = angle + self.n_jobs = n_jobs + + def _check_params_vs_input(self, X): + if self.perplexity >= X.shape[0]: + raise ValueError( + f"perplexity ({self.perplexity}) must be less " + f"than n_samples ({X.shape[0]})" + ) + + def _fit(self, X, skip_num_points=0): + """Private function to fit the model using X as training data.""" + + if isinstance(self.init, str) and self.init == "pca" and issparse(X): + raise TypeError( + "PCA initialization is currently not supported " + "with the sparse input matrix. Use " + 'init="random" instead.' + ) + + if self.learning_rate == "auto": + # See issue #18018 + self.learning_rate_ = X.shape[0] / self.early_exaggeration / 4 + self.learning_rate_ = np.maximum(self.learning_rate_, 50) + else: + self.learning_rate_ = self.learning_rate + + if self.method == "barnes_hut": + X = validate_data( + self, + X, + accept_sparse=["csr"], + ensure_min_samples=2, + dtype=[np.float32, np.float64], + ) + else: + X = validate_data( + self, + X, + accept_sparse=["csr", "csc", "coo"], + dtype=[np.float32, np.float64], + ) + if self.metric == "precomputed": + if isinstance(self.init, str) and self.init == "pca": + raise ValueError( + 'The parameter init="pca" cannot be used with metric="precomputed".' + ) + if X.shape[0] != X.shape[1]: + raise ValueError("X should be a square distance matrix") + + check_non_negative( + X, + ( + "TSNE.fit(). With metric='precomputed', X " + "should contain positive distances." + ), + ) + + if self.method == "exact" and issparse(X): + raise TypeError( + 'TSNE with method="exact" does not accept sparse ' + 'precomputed distance matrix. Use method="barnes_hut" ' + "or provide the dense distance matrix." + ) + + if self.method == "barnes_hut" and self.n_components > 3: + raise ValueError( + "'n_components' should be inferior to 4 for the " + "barnes_hut algorithm as it relies on " + "quad-tree or oct-tree." + ) + random_state = check_random_state(self.random_state) + + n_samples = X.shape[0] + + neighbors_nn = None + if self.method == "exact": + # Retrieve the distance matrix, either using the precomputed one or + # computing it. + if self.metric == "precomputed": + distances = X + else: + if self.verbose: + print("[t-SNE] Computing pairwise distances...") + + if self.metric == "euclidean": + # Euclidean is squared here, rather than using **= 2, + # because euclidean_distances already calculates + # squared distances, and returns np.sqrt(dist) for + # squared=False. + # Also, Euclidean is slower for n_jobs>1, so don't set here + distances = pairwise_distances(X, metric=self.metric, squared=True) + else: + metric_params_ = self.metric_params or {} + distances = pairwise_distances( + X, metric=self.metric, n_jobs=self.n_jobs, **metric_params_ + ) + + if np.any(distances < 0): + raise ValueError( + "All distances should be positive, the metric given is not correct" + ) + + if self.metric != "euclidean": + distances **= 2 + + # compute the joint probability distribution for the input space + P = _joint_probabilities(distances, self.perplexity, self.verbose) + assert np.all(np.isfinite(P)), "All probabilities should be finite" + assert np.all(P >= 0), "All probabilities should be non-negative" + assert np.all(P <= 1), ( + "All probabilities should be less or then equal to one" + ) + + else: + # Compute the number of nearest neighbors to find. + # LvdM uses 3 * perplexity as the number of neighbors. + # In the event that we have very small # of points + # set the neighbors to n - 1. + n_neighbors = min(n_samples - 1, int(3.0 * self.perplexity + 1)) + + if self.verbose: + print("[t-SNE] Computing {} nearest neighbors...".format(n_neighbors)) + + # Find the nearest neighbors for every point + knn = NearestNeighbors( + algorithm="auto", + n_jobs=self.n_jobs, + n_neighbors=n_neighbors, + metric=self.metric, + metric_params=self.metric_params, + ) + t0 = time() + knn.fit(X) + duration = time() - t0 + if self.verbose: + print( + "[t-SNE] Indexed {} samples in {:.3f}s...".format( + n_samples, duration + ) + ) + + t0 = time() + distances_nn = knn.kneighbors_graph(mode="distance") + duration = time() - t0 + if self.verbose: + print( + "[t-SNE] Computed neighbors for {} samples in {:.3f}s...".format( + n_samples, duration + ) + ) + + # Free the memory used by the ball_tree + del knn + + # knn return the euclidean distance but we need it squared + # to be consistent with the 'exact' method. Note that the + # the method was derived using the euclidean method as in the + # input space. Not sure of the implication of using a different + # metric. + distances_nn.data **= 2 + + # compute the joint probability distribution for the input space + P = _joint_probabilities_nn(distances_nn, self.perplexity, self.verbose) + + if isinstance(self.init, np.ndarray): + X_embedded = self.init + elif self.init == "pca": + pca = PCA( + n_components=self.n_components, + svd_solver="randomized", + random_state=random_state, + ) + # Always output a numpy array, no matter what is configured globally + pca.set_output(transform="default") + X_embedded = pca.fit_transform(X).astype(np.float32, copy=False) + # PCA is rescaled so that PC1 has standard deviation 1e-4 which is + # the default value for random initialization. See issue #18018. + X_embedded = X_embedded / np.std(X_embedded[:, 0]) * 1e-4 + elif self.init == "random": + # The embedding is initialized with iid samples from Gaussians with + # standard deviation 1e-4. + X_embedded = 1e-4 * random_state.standard_normal( + size=(n_samples, self.n_components) + ).astype(np.float32) + + # Degrees of freedom of the Student's t-distribution. The suggestion + # degrees_of_freedom = n_components - 1 comes from + # "Learning a Parametric Embedding by Preserving Local Structure" + # Laurens van der Maaten, 2009. + degrees_of_freedom = max(self.n_components - 1, 1) + + return self._tsne( + P, + degrees_of_freedom, + n_samples, + X_embedded=X_embedded, + neighbors=neighbors_nn, + skip_num_points=skip_num_points, + ) + + def _tsne( + self, + P, + degrees_of_freedom, + n_samples, + X_embedded, + neighbors=None, + skip_num_points=0, + ): + """Runs t-SNE.""" + # t-SNE minimizes the Kullback-Leiber divergence of the Gaussians P + # and the Student's t-distributions Q. The optimization algorithm that + # we use is batch gradient descent with two stages: + # * initial optimization with early exaggeration and momentum at 0.5 + # * final optimization with momentum at 0.8 + params = X_embedded.ravel() + + opt_args = { + "it": 0, + "n_iter_check": self._N_ITER_CHECK, + "min_grad_norm": self.min_grad_norm, + "learning_rate": self.learning_rate_, + "verbose": self.verbose, + "kwargs": dict(skip_num_points=skip_num_points), + "args": [P, degrees_of_freedom, n_samples, self.n_components], + "n_iter_without_progress": self._EXPLORATION_MAX_ITER, + "max_iter": self._EXPLORATION_MAX_ITER, + "momentum": 0.5, + } + if self.method == "barnes_hut": + obj_func = _kl_divergence_bh + opt_args["kwargs"]["angle"] = self.angle + # Repeat verbose argument for _kl_divergence_bh + opt_args["kwargs"]["verbose"] = self.verbose + # Get the number of threads for gradient computation here to + # avoid recomputing it at each iteration. + opt_args["kwargs"]["num_threads"] = _openmp_effective_n_threads() + else: + obj_func = _kl_divergence + + # Learning schedule (part 1): do 250 iteration with lower momentum but + # higher learning rate controlled via the early exaggeration parameter + P *= self.early_exaggeration + params, kl_divergence, it = _gradient_descent(obj_func, params, **opt_args) + if self.verbose: + print( + "[t-SNE] KL divergence after %d iterations with early exaggeration: %f" + % (it + 1, kl_divergence) + ) + + # Learning schedule (part 2): disable early exaggeration and finish + # optimization with a higher momentum at 0.8 + P /= self.early_exaggeration + remaining = self.max_iter - self._EXPLORATION_MAX_ITER + if it < self._EXPLORATION_MAX_ITER or remaining > 0: + opt_args["max_iter"] = self.max_iter + opt_args["it"] = it + 1 + opt_args["momentum"] = 0.8 + opt_args["n_iter_without_progress"] = self.n_iter_without_progress + params, kl_divergence, it = _gradient_descent(obj_func, params, **opt_args) + + # Save the final number of iterations + self.n_iter_ = it + + if self.verbose: + print( + "[t-SNE] KL divergence after %d iterations: %f" + % (it + 1, kl_divergence) + ) + + X_embedded = params.reshape(n_samples, self.n_components) + self.kl_divergence_ = kl_divergence + + return X_embedded + + @_fit_context( + # TSNE.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit_transform(self, X, y=None): + """Fit X into an embedded space and return that transformed output. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. If the method + is 'exact', X may be a sparse matrix of type 'csr', 'csc' + or 'coo'. If the method is 'barnes_hut' and the metric is + 'precomputed', X may be a precomputed sparse graph. + + y : None + Ignored. + + Returns + ------- + X_new : ndarray of shape (n_samples, n_components) + Embedding of the training data in low-dimensional space. + """ + self._check_params_vs_input(X) + embedding = self._fit(X) + self.embedding_ = embedding + return self.embedding_ + + @_fit_context( + # TSNE.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Fit X into an embedded space. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) + If the metric is 'precomputed' X must be a square distance + matrix. Otherwise it contains a sample per row. If the method + is 'exact', X may be a sparse matrix of type 'csr', 'csc' + or 'coo'. If the method is 'barnes_hut' and the metric is + 'precomputed', X may be a precomputed sparse graph. + + y : None + Ignored. + + Returns + ------- + self : object + Fitted estimator. + """ + self.fit_transform(X) + return self + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.embedding_.shape[1] + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.metric == "precomputed" + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7ba3e7bf36f1c7e508e4197eb3ed0523a424622b Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.pyx new file mode 100644 index 0000000000000000000000000000000000000000..be3a1d2f91f6670cea8eee130990becc3fc4b8bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/_utils.pyx @@ -0,0 +1,120 @@ +import numpy as np + +from libc cimport math +from libc.math cimport INFINITY + +from ..utils._typedefs cimport float32_t, float64_t + + +cdef float EPSILON_DBL = 1e-8 +cdef float PERPLEXITY_TOLERANCE = 1e-5 + + +# TODO: have this function support float32 and float64 and preserve inputs' dtypes. +def _binary_search_perplexity( + const float32_t[:, :] sqdistances, + float desired_perplexity, + int verbose): + """Binary search for sigmas of conditional Gaussians. + + This approximation reduces the computational complexity from O(N^2) to + O(uN). + + Parameters + ---------- + sqdistances : ndarray of shape (n_samples, n_neighbors), dtype=np.float32 + Distances between training samples and their k nearest neighbors. + When using the exact method, this is a square (n_samples, n_samples) + distance matrix. The TSNE default metric is "euclidean" which is + interpreted as squared euclidean distance. + + desired_perplexity : float + Desired perplexity (2^entropy) of the conditional Gaussians. + + verbose : int + Verbosity level. + + Returns + ------- + P : ndarray of shape (n_samples, n_samples), dtype=np.float64 + Probabilities of conditional Gaussian distributions p_i|j. + """ + # Maximum number of binary search steps + cdef long n_steps = 100 + + cdef long n_samples = sqdistances.shape[0] + cdef long n_neighbors = sqdistances.shape[1] + cdef int using_neighbors = n_neighbors < n_samples + # Precisions of conditional Gaussian distributions + cdef double beta + cdef double beta_min + cdef double beta_max + cdef double beta_sum = 0.0 + + # Use log scale + cdef double desired_entropy = math.log(desired_perplexity) + cdef double entropy_diff + + cdef double entropy + cdef double sum_Pi + cdef double sum_disti_Pi + cdef long i, j, l + + # This array is later used as a 32bit array. It has multiple intermediate + # floating point additions that benefit from the extra precision + cdef float64_t[:, :] P = np.zeros( + (n_samples, n_neighbors), dtype=np.float64) + + for i in range(n_samples): + beta_min = -INFINITY + beta_max = INFINITY + beta = 1.0 + + # Binary search of precision for i-th conditional distribution + for l in range(n_steps): + # Compute current entropy and corresponding probabilities + # computed just over the nearest neighbors or over all data + # if we're not using neighbors + sum_Pi = 0.0 + for j in range(n_neighbors): + if j != i or using_neighbors: + P[i, j] = math.exp(-sqdistances[i, j] * beta) + sum_Pi += P[i, j] + + if sum_Pi == 0.0: + sum_Pi = EPSILON_DBL + sum_disti_Pi = 0.0 + + for j in range(n_neighbors): + P[i, j] /= sum_Pi + sum_disti_Pi += sqdistances[i, j] * P[i, j] + + entropy = math.log(sum_Pi) + beta * sum_disti_Pi + entropy_diff = entropy - desired_entropy + + if math.fabs(entropy_diff) <= PERPLEXITY_TOLERANCE: + break + + if entropy_diff > 0.0: + beta_min = beta + if beta_max == INFINITY: + beta *= 2.0 + else: + beta = (beta + beta_max) / 2.0 + else: + beta_max = beta + if beta_min == -INFINITY: + beta /= 2.0 + else: + beta = (beta + beta_min) / 2.0 + + beta_sum += beta + + if verbose and ((i + 1) % 1000 == 0 or i + 1 == n_samples): + print("[t-SNE] Computed conditional probabilities for sample " + "%d / %d" % (i + 1, n_samples)) + + if verbose: + print("[t-SNE] Mean sigma: %f" + % np.mean(math.sqrt(n_samples / beta_sum))) + return np.asarray(P) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..c060590410d63ff06ca8b0f062b08cd1581a07de --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/meson.build @@ -0,0 +1,14 @@ +py.extension_module( + '_utils', + [cython_gen.process('_utils.pyx'), utils_cython_tree], + subdir: 'sklearn/manifold', + install: true +) + +py.extension_module( + '_barnes_hut_tsne', + cython_gen.process('_barnes_hut_tsne.pyx'), + dependencies: [np_dep, openmp_dep], + subdir: 'sklearn/manifold', + install: true +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_isomap.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_isomap.py new file mode 100644 index 0000000000000000000000000000000000000000..e38b92442e58d9881726bdee85073ad38a7c95e1 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_isomap.py @@ -0,0 +1,348 @@ +import math +from itertools import product + +import numpy as np +import pytest +from scipy.sparse import rand as sparse_rand + +from sklearn import clone, datasets, manifold, neighbors, pipeline, 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, + assert_array_equal, +) +from sklearn.utils.fixes import CSR_CONTAINERS + +eigen_solvers = ["auto", "dense", "arpack"] +path_methods = ["auto", "FW", "D"] + + +def create_sample_data(dtype, n_pts=25, add_noise=False): + # grid of equidistant points in 2D, n_components = n_dim + n_per_side = int(math.sqrt(n_pts)) + X = np.array(list(product(range(n_per_side), repeat=2))).astype(dtype, copy=False) + if add_noise: + # add noise in a third dimension + rng = np.random.RandomState(0) + noise = 0.1 * rng.randn(n_pts, 1).astype(dtype, copy=False) + X = np.concatenate((X, noise), 1) + return X + + +@pytest.mark.parametrize("n_neighbors, radius", [(24, None), (None, np.inf)]) +@pytest.mark.parametrize("eigen_solver", eigen_solvers) +@pytest.mark.parametrize("path_method", path_methods) +def test_isomap_simple_grid( + global_dtype, n_neighbors, radius, eigen_solver, path_method +): + # Isomap should preserve distances when all neighbors are used + n_pts = 25 + X = create_sample_data(global_dtype, n_pts=n_pts, add_noise=False) + + # distances from each point to all others + 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") + + clf = manifold.Isomap( + n_neighbors=n_neighbors, + radius=radius, + n_components=2, + eigen_solver=eigen_solver, + path_method=path_method, + ) + clf.fit(X) + + 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" + ) + atol = 1e-5 if global_dtype == np.float32 else 0 + assert_allclose_dense_sparse(G, G_iso, atol=atol) + + +@pytest.mark.parametrize("n_neighbors, radius", [(24, None), (None, np.inf)]) +@pytest.mark.parametrize("eigen_solver", eigen_solvers) +@pytest.mark.parametrize("path_method", path_methods) +def test_isomap_reconstruction_error( + global_dtype, n_neighbors, radius, eigen_solver, path_method +): + if global_dtype is np.float32: + pytest.skip( + "Skipping test due to numerical instabilities on float32 data" + "from KernelCenterer used in the reconstruction_error method" + ) + + # Same setup as in test_isomap_simple_grid, with an added dimension + n_pts = 25 + X = create_sample_data(global_dtype, n_pts=n_pts, add_noise=True) + + # compute input kernel + 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) + + clf = manifold.Isomap( + n_neighbors=n_neighbors, + radius=radius, + n_components=2, + eigen_solver=eigen_solver, + path_method=path_method, + ) + clf.fit(X) + + # compute output kernel + 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) / n_pts + atol = 1e-5 if global_dtype == np.float32 else 0 + assert_allclose(reconstruction_error, clf.reconstruction_error(), atol=atol) + + +@pytest.mark.parametrize("n_neighbors, radius", [(2, None), (None, 0.5)]) +def test_transform(global_dtype, n_neighbors, radius): + n_samples = 200 + n_components = 10 + noise_scale = 0.01 + + # Create S-curve dataset + X, y = datasets.make_s_curve(n_samples, random_state=0) + + X = X.astype(global_dtype, copy=False) + + # Compute isomap embedding + 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 + rng = np.random.RandomState(0) + noise = noise_scale * rng.randn(*X.shape) + X_iso2 = iso.transform(X + noise) + + # Make sure the rms error on re-embedding is comparable to noise_scale + assert np.sqrt(np.mean((X_iso - X_iso2) ** 2)) < 2 * noise_scale + + +@pytest.mark.parametrize("n_neighbors, radius", [(2, None), (None, 10.0)]) +def test_pipeline(n_neighbors, radius, global_dtype): + # 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) + X = X.astype(global_dtype, copy=False) + clf = pipeline.Pipeline( + [ + ("isomap", manifold.Isomap(n_neighbors=n_neighbors, radius=radius)), + ("clf", neighbors.KNeighborsClassifier()), + ] + ) + clf.fit(X, y) + assert 0.9 < clf.score(X, y) + + +def test_pipeline_with_nearest_neighbors_transformer(global_dtype): + # Test chaining NearestNeighborsTransformer and Isomap with + # neighbors_algorithm='precomputed' + algorithm = "auto" + n_neighbors = 10 + + X, _ = datasets.make_blobs(random_state=0) + X2, _ = datasets.make_blobs(random_state=1) + + X = X.astype(global_dtype, copy=False) + X2 = X2.astype(global_dtype, copy=False) + + # compare the chained version and the compact version + est_chain = pipeline.make_pipeline( + neighbors.KNeighborsTransformer( + n_neighbors=n_neighbors, algorithm=algorithm, mode="distance" + ), + manifold.Isomap(n_neighbors=n_neighbors, metric="precomputed"), + ) + est_compact = manifold.Isomap( + n_neighbors=n_neighbors, neighbors_algorithm=algorithm + ) + + Xt_chain = est_chain.fit_transform(X) + Xt_compact = est_compact.fit_transform(X) + assert_allclose(Xt_chain, Xt_compact) + + Xt_chain = est_chain.transform(X2) + Xt_compact = est_compact.transform(X2) + assert_allclose(Xt_chain, Xt_compact) + + +@pytest.mark.parametrize( + "metric, p, is_euclidean", + [ + ("euclidean", 2, True), + ("manhattan", 1, False), + ("minkowski", 1, False), + ("minkowski", 2, True), + (lambda x1, x2: np.sqrt(np.sum(x1**2 + x2**2)), 2, False), + ], +) +def test_different_metric(global_dtype, metric, p, is_euclidean): + # Isomap must work on various metric parameters work correctly + # and must default to euclidean. + X, _ = datasets.make_blobs(random_state=0) + X = X.astype(global_dtype, copy=False) + + reference = manifold.Isomap().fit_transform(X) + embedding = manifold.Isomap(metric=metric, p=p).fit_transform(X) + + if is_euclidean: + assert_allclose(embedding, reference) + else: + with pytest.raises(AssertionError, match="Not equal to tolerance"): + assert_allclose(embedding, reference) + + +def test_isomap_clone_bug(): + # regression test for bug reported in #6062 + model = manifold.Isomap() + for n_neighbors in [10, 15, 20]: + model.set_params(n_neighbors=n_neighbors) + model.fit(np.random.rand(50, 2)) + assert model.nbrs_.n_neighbors == n_neighbors + + +@pytest.mark.parametrize("eigen_solver", eigen_solvers) +@pytest.mark.parametrize("path_method", path_methods) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_input( + global_dtype, eigen_solver, path_method, global_random_seed, csr_container +): + # TODO: compare results on dense and sparse data as proposed in: + # https://github.com/scikit-learn/scikit-learn/pull/23585#discussion_r968388186 + X = csr_container( + sparse_rand( + 100, + 3, + density=0.1, + format="csr", + dtype=global_dtype, + random_state=global_random_seed, + ) + ) + + iso_dense = manifold.Isomap( + n_components=2, + eigen_solver=eigen_solver, + path_method=path_method, + n_neighbors=8, + ) + iso_sparse = clone(iso_dense) + + X_trans_dense = iso_dense.fit_transform(X.toarray()) + X_trans_sparse = iso_sparse.fit_transform(X) + + assert_allclose(X_trans_sparse, X_trans_dense, rtol=1e-4, atol=1e-4) + + +def test_isomap_fit_precomputed_radius_graph(global_dtype): + # Isomap.fit_transform must yield similar result when using + # a precomputed distance matrix. + + X, y = datasets.make_s_curve(200, random_state=0) + X = X.astype(global_dtype, copy=False) + 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) + atol = 1e-5 if global_dtype == np.float32 else 0 + assert_allclose(precomputed_result, result, atol=atol) + + +def test_isomap_fitted_attributes_dtype(global_dtype): + """Check that the fitted attributes are stored accordingly to the + data type of X.""" + iso = manifold.Isomap(n_neighbors=2) + + X = np.array([[1, 2], [3, 4], [5, 6]], dtype=global_dtype) + + iso.fit(X) + + assert iso.dist_matrix_.dtype == global_dtype + assert iso.embedding_.dtype == global_dtype + + +def test_isomap_dtype_equivalence(): + """Check the equivalence of the results with 32 and 64 bits input.""" + iso_32 = manifold.Isomap(n_neighbors=2) + X_32 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float32) + iso_32.fit(X_32) + + iso_64 = manifold.Isomap(n_neighbors=2) + X_64 = np.array([[1, 2], [3, 4], [5, 6]], dtype=np.float64) + iso_64.fit(X_64) + + assert_allclose(iso_32.dist_matrix_, iso_64.dist_matrix_) + + +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] + with pytest.warns(UserWarning, match="number of connected components"): + manifold.Isomap(n_neighbors=2).fit(X) + + +def test_multiple_connected_components_metric_precomputed(global_dtype): + # Test that an error is raised when the graph has multiple components + # and when X is a precomputed neighbors graph. + X = np.array([0, 1, 2, 5, 6, 7])[:, None].astype(global_dtype, copy=False) + + # works with a precomputed distance matrix (dense) + X_distances = pairwise_distances(X) + with pytest.warns(UserWarning, match="number of connected components"): + manifold.Isomap(n_neighbors=1, metric="precomputed").fit(X_distances) + + # does not work with a precomputed neighbors graph (sparse) + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_locally_linear.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_locally_linear.py new file mode 100644 index 0000000000000000000000000000000000000000..835aa20fd1d32ace684eea9afd451bcdcf695f79 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_locally_linear.py @@ -0,0 +1,171 @@ +from itertools import product + +import numpy as np +import pytest +from scipy import linalg + +from sklearn import manifold, neighbors +from sklearn.datasets import make_blobs +from sklearn.manifold._locally_linear import barycenter_kneighbors_graph +from sklearn.utils._testing import ( + assert_allclose, + assert_array_equal, + ignore_warnings, +) + +eigen_solvers = ["dense", "arpack"] + + +# ---------------------------------------------------------------------- +# Test utility routines +def test_barycenter_kneighbors_graph(global_dtype): + X = np.array([[0, 1], [1.01, 1.0], [2, 0]], dtype=global_dtype) + + graph = barycenter_kneighbors_graph(X, 1) + expected_graph = np.array( + [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], dtype=global_dtype + ) + + assert graph.dtype == global_dtype + + assert_allclose(graph.toarray(), expected_graph) + + graph = barycenter_kneighbors_graph(X, 2) + # check that columns sum to one + assert_allclose(np.sum(graph.toarray(), axis=1), np.ones(3)) + pred = np.dot(graph.toarray(), X) + assert linalg.norm(pred - X) / X.shape[0] < 1 + + +# ---------------------------------------------------------------------- +# Test LLE by computing the reconstruction error on some manifolds. + + +def test_lle_simple_grid(global_dtype): + # note: ARPACK is numerically unstable, so this test will fail for + # some random seeds. We choose 42 because the tests pass. + # for arm64 platforms 2 makes the test fail. + # TODO: rewrite this test to make less sensitive to the random seed, + # irrespective of the platform. + rng = np.random.RandomState(42) + + # grid of equidistant points in 2D, n_components = n_dim + X = np.array(list(product(range(5), repeat=2))) + X = X + 1e-10 * rng.uniform(size=X.shape) + X = X.astype(global_dtype, copy=False) + + n_components = 2 + clf = manifold.LocallyLinearEmbedding( + n_neighbors=5, n_components=n_components, random_state=rng + ) + tol = 0.1 + + N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() + reconstruction_error = linalg.norm(np.dot(N, X) - X, "fro") + assert reconstruction_error < tol + + for solver in eigen_solvers: + clf.set_params(eigen_solver=solver) + clf.fit(X) + assert clf.embedding_.shape[1] == n_components + reconstruction_error = ( + linalg.norm(np.dot(N, clf.embedding_) - clf.embedding_, "fro") ** 2 + ) + + assert reconstruction_error < tol + assert_allclose(clf.reconstruction_error_, reconstruction_error, atol=1e-1) + + # re-embed a noisy version of X using the transform method + noise = rng.randn(*X.shape).astype(global_dtype, copy=False) / 100 + X_reembedded = clf.transform(X + noise) + assert linalg.norm(X_reembedded - clf.embedding_) < tol + + +@pytest.mark.parametrize("method", ["standard", "hessian", "modified", "ltsa"]) +@pytest.mark.parametrize("solver", eigen_solvers) +def test_lle_manifold(global_dtype, method, solver): + rng = np.random.RandomState(0) + # similar test on a slightly more complex manifold + X = np.array(list(product(np.arange(18), repeat=2))) + X = np.c_[X, X[:, 0] ** 2 / 18] + X = X + 1e-10 * rng.uniform(size=X.shape) + X = X.astype(global_dtype, copy=False) + n_components = 2 + + clf = manifold.LocallyLinearEmbedding( + n_neighbors=6, n_components=n_components, method=method, random_state=0 + ) + tol = 1.5 if method == "standard" else 3 + + N = barycenter_kneighbors_graph(X, clf.n_neighbors).toarray() + reconstruction_error = linalg.norm(np.dot(N, X) - X) + assert reconstruction_error < tol + + clf.set_params(eigen_solver=solver) + clf.fit(X) + assert clf.embedding_.shape[1] == n_components + reconstruction_error = ( + linalg.norm(np.dot(N, clf.embedding_) - clf.embedding_, "fro") ** 2 + ) + details = "solver: %s, method: %s" % (solver, method) + assert reconstruction_error < tol, details + assert ( + np.abs(clf.reconstruction_error_ - reconstruction_error) + < tol * reconstruction_error + ), details + + +def test_pipeline(): + # check that LocallyLinearEmbedding works fine as a Pipeline + # only checks that no error is raised. + # TODO check that it actually does something useful + from sklearn import datasets, pipeline + + X, y = datasets.make_blobs(random_state=0) + clf = pipeline.Pipeline( + [ + ("filter", manifold.LocallyLinearEmbedding(random_state=0)), + ("clf", neighbors.KNeighborsClassifier()), + ] + ) + clf.fit(X, y) + assert 0.9 < clf.score(X, y) + + +# Test the error raised when the weight matrix is singular +def test_singular_matrix(): + M = np.ones((200, 3)) + f = ignore_warnings + with pytest.raises(ValueError, match="Error in determining null-space with ARPACK"): + f( + manifold.locally_linear_embedding( + M, + n_neighbors=2, + n_components=1, + method="standard", + eigen_solver="arpack", + ) + ) + + +# regression test for #6033 +def test_integer_input(): + rand = np.random.RandomState(0) + X = rand.randint(0, 100, size=(20, 3)) + + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_mds.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_mds.py new file mode 100644 index 0000000000000000000000000000000000000000..88dc842a1d5fc4168a3cc9003c929f1770e839bb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_mds.py @@ -0,0 +1,234 @@ +from unittest.mock import Mock + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_almost_equal, assert_equal + +from sklearn.datasets import load_digits +from sklearn.manifold import _mds as mds +from sklearn.metrics import euclidean_distances + + +def test_smacof(): + # test metric smacof using the data of "Modern Multidimensional Scaling", + # Borg & Groenen, p 154 + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + Z = np.array([[-0.266, -0.539], [0.451, 0.252], [0.016, -0.238], [-0.200, 0.524]]) + X, _ = mds.smacof(sim, init=Z, n_components=2, max_iter=1, n_init=1) + X_true = np.array( + [[-1.415, -2.471], [1.633, 1.107], [0.249, -0.067], [-0.468, 1.431]] + ) + assert_array_almost_equal(X, X_true, decimal=3) + + +def test_nonmetric_lower_normalized_stress(): + # Testing that nonmetric MDS results in lower normalized stress compared + # compared to metric MDS (non-regression test for issue 27028) + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + Z = np.array([[-0.266, -0.539], [0.451, 0.252], [0.016, -0.238], [-0.200, 0.524]]) + + _, stress1 = mds.smacof( + sim, init=Z, n_components=2, max_iter=1000, n_init=1, normalized_stress=True + ) + + _, stress2 = mds.smacof( + sim, + init=Z, + n_components=2, + max_iter=1000, + n_init=1, + normalized_stress=True, + metric=False, + ) + assert stress1 > stress2 + + +def test_nonmetric_mds_optimization(): + # Test that stress is decreasing during nonmetric MDS optimization + # (non-regression test for issue 27028) + X, _ = load_digits(return_X_y=True) + rng = np.random.default_rng(seed=42) + ind_subset = rng.choice(len(X), size=200, replace=False) + X = X[ind_subset] + + mds_est = mds.MDS( + n_components=2, + n_init=1, + max_iter=2, + metric=False, + random_state=42, + ).fit(X) + stress_after_2_iter = mds_est.stress_ + + mds_est = mds.MDS( + n_components=2, + n_init=1, + max_iter=3, + metric=False, + random_state=42, + ).fit(X) + stress_after_3_iter = mds_est.stress_ + + assert stress_after_2_iter > stress_after_3_iter + + +@pytest.mark.parametrize("metric", [True, False]) +def test_mds_recovers_true_data(metric): + X = np.array([[1, 1], [1, 4], [1, 5], [3, 3]]) + mds_est = mds.MDS( + n_components=2, + n_init=1, + eps=1e-15, + max_iter=1000, + metric=metric, + random_state=42, + ).fit(X) + stress = mds_est.stress_ + assert_allclose(stress, 0, atol=1e-6) + + +def test_smacof_error(): + # Not symmetric similarity matrix: + sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + + with pytest.raises(ValueError): + mds.smacof(sim, n_init=1) + + # Not squared similarity matrix: + sim = np.array([[0, 5, 9, 4], [5, 0, 2, 2], [4, 2, 1, 0]]) + + with pytest.raises(ValueError): + mds.smacof(sim, n_init=1) + + # init not None and not correct format: + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + + Z = np.array([[-0.266, -0.539], [0.016, -0.238], [-0.200, 0.524]]) + with pytest.raises(ValueError): + mds.smacof(sim, init=Z, n_init=1) + + +def test_MDS(): + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + mds_clf = mds.MDS( + metric=False, + n_jobs=3, + n_init=3, + dissimilarity="precomputed", + ) + mds_clf.fit(sim) + + +# TODO(1.9): remove warning filter +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("k", [0.5, 1.5, 2]) +def test_normed_stress(k): + """Test that non-metric MDS normalized stress is scale-invariant.""" + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + + X1, stress1 = mds.smacof(sim, metric=False, max_iter=5, random_state=0) + X2, stress2 = mds.smacof(k * sim, metric=False, max_iter=5, random_state=0) + + assert_allclose(stress1, stress2, rtol=1e-5) + assert_allclose(X1, X2, rtol=1e-5) + + +# TODO(1.9): remove warning filter +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("metric", [True, False]) +def test_normalized_stress_auto(metric, monkeypatch): + rng = np.random.RandomState(0) + X = rng.randn(4, 3) + dist = euclidean_distances(X) + + mock = Mock(side_effect=mds._smacof_single) + monkeypatch.setattr("sklearn.manifold._mds._smacof_single", mock) + + est = mds.MDS(metric=metric, normalized_stress="auto", random_state=rng) + est.fit_transform(X) + assert mock.call_args[1]["normalized_stress"] != metric + + mds.smacof(dist, metric=metric, normalized_stress="auto", random_state=rng) + assert mock.call_args[1]["normalized_stress"] != metric + + +def test_isotonic_outofbounds(): + # This particular configuration can trigger out of bounds error + # in the isotonic regression (non-regression test for issue 26999) + dis = np.array( + [ + [0.0, 1.732050807568877, 1.7320508075688772], + [1.732050807568877, 0.0, 6.661338147750939e-16], + [1.7320508075688772, 6.661338147750939e-16, 0.0], + ] + ) + init = np.array( + [ + [0.08665881585055124, 0.7939114643387546], + [0.9959834154297658, 0.7555546025640025], + [0.8766008278401566, 0.4227358815811242], + ] + ) + mds.smacof(dis, init=init, metric=False, n_init=1) + + +# TODO(1.9): remove warning filter +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("normalized_stress", [True, False]) +def test_returned_stress(normalized_stress): + # Test that the final stress corresponds to the final embedding + # (non-regression test for issue 16846) + X = np.array([[1, 1], [1, 4], [1, 5], [3, 3]]) + D = euclidean_distances(X) + + mds_est = mds.MDS( + n_components=2, + random_state=42, + normalized_stress=normalized_stress, + ).fit(X) + + Z = mds_est.embedding_ + stress = mds_est.stress_ + + D_mds = euclidean_distances(Z) + stress_Z = ((D_mds.ravel() - D.ravel()) ** 2).sum() / 2 + + if normalized_stress: + stress_Z = np.sqrt(stress_Z / ((D_mds.ravel() ** 2).sum() / 2)) + + assert_allclose(stress, stress_Z) + + +# TODO(1.9): remove warning filter +@pytest.mark.filterwarnings("ignore::FutureWarning") +@pytest.mark.parametrize("metric", [True, False]) +def test_convergence_does_not_depend_on_scale(metric): + # Test that the number of iterations until convergence does not depend on + # the scale of the input data + X = np.array([[1, 1], [1, 4], [1, 5], [3, 3]]) + + mds_est = mds.MDS( + n_components=2, + random_state=42, + metric=metric, + ) + + mds_est.fit(X * 100) + n_iter1 = mds_est.n_iter_ + + mds_est.fit(X / 100) + n_iter2 = mds_est.n_iter_ + + assert_equal(n_iter1, n_iter2) + + +# TODO(1.9): delete this test +def test_future_warning_n_init(): + X = np.array([[1, 1], [1, 4], [1, 5], [3, 3]]) + sim = np.array([[0, 5, 3, 4], [5, 0, 2, 2], [3, 2, 0, 1], [4, 2, 1, 0]]) + + with pytest.warns(FutureWarning): + mds.smacof(sim) + + with pytest.warns(FutureWarning): + mds.MDS().fit(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_spectral_embedding.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_spectral_embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..4c4115734a404360d0d4ce507d18df9e4b2b5396 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_spectral_embedding.py @@ -0,0 +1,503 @@ +import itertools +from unittest.mock import Mock + +import numpy as np +import pytest +from scipy import sparse +from scipy.linalg import eigh +from scipy.sparse.linalg import eigsh, lobpcg + +from sklearn.cluster import KMeans +from sklearn.datasets import make_blobs +from sklearn.manifold import SpectralEmbedding, _spectral_embedding, spectral_embedding +from sklearn.manifold._spectral_embedding import ( + _graph_connected_component, + _graph_is_connected, +) +from sklearn.metrics import normalized_mutual_info_score, pairwise_distances +from sklearn.metrics.pairwise import rbf_kernel +from sklearn.neighbors import NearestNeighbors +from sklearn.utils._testing import assert_array_almost_equal, assert_array_equal +from sklearn.utils.extmath import _deterministic_vector_sign_flip +from sklearn.utils.fixes import ( + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + parse_version, + sp_version, +) +from sklearn.utils.fixes import laplacian as csgraph_laplacian + +try: + from pyamg import smoothed_aggregation_solver # noqa: F401 + + 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( + [ + [0.0, 5.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 4.0, 0.0, 0.0], + [1.0, 0.0, 0.0, 5.0, 1.0], + ] +) +n_samples = 1000 +n_clusters, n_features = centers.shape +S, true_labels = make_blobs( + n_samples=n_samples, centers=centers, cluster_std=1.0, random_state=42 +) + + +def _assert_equal_with_sign_flipping(A, B, tol=0.0): + """Check array A and B are equal with possible sign flipping on + each column""" + tol_squared = tol**2 + for A_col, B_col in zip(A.T, B.T): + assert ( + np.max((A_col - B_col) ** 2) <= tol_squared + or np.max((A_col + B_col) ** 2) <= tol_squared + ) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_sparse_graph_connected_component(coo_container): + rng = np.random.RandomState(42) + n_samples = 300 + boundaries = [0, 42, 121, 200, n_samples] + p = rng.permutation(n_samples) + connections = [] + + for start, stop in itertools.pairwise(boundaries): + group = p[start:stop] + # Connect all elements within the group at least once via an + # arbitrary path that spans the group. + for i in range(len(group) - 1): + connections.append((group[i], group[i + 1])) + + # Add some more random connections within the group + min_idx, max_idx = 0, len(group) - 1 + n_random_connections = 1000 + source = rng.randint(min_idx, max_idx, size=n_random_connections) + target = rng.randint(min_idx, max_idx, size=n_random_connections) + connections.extend(zip(group[source], group[target])) + + # Build a symmetric affinity matrix + row_idx, column_idx = tuple(np.array(connections).T) + data = rng.uniform(0.1, 42, size=len(connections)) + affinity = coo_container((data, (row_idx, column_idx))) + affinity = 0.5 * (affinity + affinity.T) + + for start, stop in itertools.pairwise(boundaries): + component_1 = _graph_connected_component(affinity, p[start]) + component_size = stop - start + assert component_1.sum() == component_size + + # We should retrieve the same component mask by starting by both ends + # of the group + component_2 = _graph_connected_component(affinity, p[stop - 1]) + assert component_2.sum() == component_size + assert_array_equal(component_1, component_2) + + +# TODO: investigate why this test is seed-sensitive on 32-bit Python +# runtimes. Is this revealing a numerical stability problem ? Or is it +# expected from the test numerical design ? In the latter case the test +# should be made less seed-sensitive instead. +@pytest.mark.parametrize( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) +@pytest.mark.parametrize("dtype", [np.float32, np.float64]) +def test_spectral_embedding_two_components(eigen_solver, dtype, seed=0): + # Test spectral embedding with two components + random_state = np.random.RandomState(seed) + n_sample = 100 + affinity = np.zeros(shape=[n_sample * 2, n_sample * 2]) + # first component + affinity[0:n_sample, 0:n_sample] = ( + np.abs(random_state.randn(n_sample, n_sample)) + 2 + ) + # second component + affinity[n_sample::, n_sample::] = ( + np.abs(random_state.randn(n_sample, n_sample)) + 2 + ) + + # Test of internal _graph_connected_component before connection + component = _graph_connected_component(affinity, 0) + assert component[:n_sample].all() + assert not component[n_sample:].any() + component = _graph_connected_component(affinity, -1) + assert not component[:n_sample].any() + assert component[n_sample:].all() + + # connection + affinity[0, n_sample + 1] = 1 + affinity[n_sample + 1, 0] = 1 + affinity.flat[:: 2 * n_sample + 1] = 0 + affinity = 0.5 * (affinity + affinity.T) + + true_label = np.zeros(shape=2 * n_sample) + true_label[0:n_sample] = 1 + + se_precomp = SpectralEmbedding( + n_components=1, + affinity="precomputed", + random_state=np.random.RandomState(seed), + eigen_solver=eigen_solver, + ) + + 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("sparse_container", [None, *CSR_CONTAINERS]) +@pytest.mark.parametrize( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +def test_spectral_embedding_precomputed_affinity( + sparse_container, eigen_solver, dtype, seed=36 +): + # Test spectral embedding with precomputed kernel + gamma = 1.0 + X = S if sparse_container is None else sparse_container(S) + + se_precomp = SpectralEmbedding( + 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.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) + + +def test_precomputed_nearest_neighbors_filtering(): + # Test precomputed graph filtering when containing too many neighbors + n_neighbors = 2 + results = [] + for additional_neighbors in [0, 10]: + nn = NearestNeighbors(n_neighbors=n_neighbors + additional_neighbors).fit(S) + graph = nn.kneighbors_graph(S, mode="connectivity") + embedding = ( + SpectralEmbedding( + random_state=0, + n_components=2, + affinity="precomputed_nearest_neighbors", + n_neighbors=n_neighbors, + ) + .fit(graph) + .embedding_ + ) + results.append(embedding) + + assert_array_equal(results[0], results[1]) + + +@pytest.mark.parametrize("sparse_container", [None, *CSR_CONTAINERS]) +def test_spectral_embedding_callable_affinity(sparse_container, seed=36): + # Test spectral embedding with callable affinity + gamma = 0.9 + kern = rbf_kernel(S, gamma=gamma) + X = S if sparse_container is None else sparse_container(S) + + se_callable = SpectralEmbedding( + n_components=2, + affinity=(lambda x: rbf_kernel(x, gamma=gamma)), + gamma=gamma, + random_state=np.random.RandomState(seed), + ) + se_rbf = SpectralEmbedding( + n_components=2, + affinity="rbf", + gamma=gamma, + random_state=np.random.RandomState(seed), + ) + embed_rbf = se_rbf.fit_transform(X) + embed_callable = se_callable.fit_transform(X) + assert_array_almost_equal(se_callable.affinity_matrix_, se_rbf.affinity_matrix_) + assert_array_almost_equal(kern, se_rbf.affinity_matrix_) + _assert_equal_with_sign_flipping(embed_rbf, embed_callable, 0.05) + + +@pytest.mark.skipif( + not pyamg_available, reason="PyAMG is required for the tests in this function." +) +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_spectral_embedding_amg_solver(dtype, coo_container, seed=36): + se_amg = SpectralEmbedding( + n_components=2, + affinity="nearest_neighbors", + eigen_solver="amg", + n_neighbors=5, + random_state=np.random.RandomState(seed), + ) + se_arpack = SpectralEmbedding( + n_components=2, + affinity="nearest_neighbors", + eigen_solver="arpack", + n_neighbors=5, + random_state=np.random.RandomState(seed), + ) + 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 + # regression test for #10715 + # affinity between nodes + row = np.array([0, 0, 1, 2, 3, 3, 4], dtype=np.int32) + col = np.array([1, 2, 2, 3, 4, 5, 5], dtype=np.int32) + val = np.array([100, 100, 100, 1, 100, 100, 100], dtype=np.int64) + + affinity = coo_container( + (np.hstack([val, val]), (np.hstack([row, col]), np.hstack([col, row]))), + shape=(6, 6), + ) + se_amg.affinity = "precomputed" + se_arpack.affinity = "precomputed" + 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) + + # Check that passing a sparse matrix with `np.int64` indices dtype raises an error + # or is successful based on the version of SciPy which is installed. + # Use a CSR matrix to avoid any conversion during the validation + affinity = affinity.tocsr() + affinity.indptr = affinity.indptr.astype(np.int64) + affinity.indices = affinity.indices.astype(np.int64) + + # PR: https://github.com/scipy/scipy/pull/18913 + # First integration in 1.11.3: https://github.com/scipy/scipy/pull/19279 + scipy_graph_traversal_supports_int64_index = sp_version >= parse_version("1.11.3") + if scipy_graph_traversal_supports_int64_index: + se_amg.fit_transform(affinity) + else: + err_msg = "Only sparse matrices with 32-bit integer indices are accepted" + with pytest.raises(ValueError, match=err_msg): + se_amg.fit_transform(affinity) + + +@pytest.mark.skipif( + not pyamg_available, reason="PyAMG is required for the tests in this function." +) +@pytest.mark.parametrize("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) + 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( + sym_matrix, n_components=10, eigen_solver="amg", random_state=0 + ) + + # Check that the learned embedding is stable w.r.t. random solver init: + for i in range(3): + new_embedding = spectral_embedding( + sym_matrix, n_components=10, eigen_solver="amg", random_state=i + 1 + ) + _assert_equal_with_sign_flipping(embedding, new_embedding, tol=0.05) + + +def test_pipeline_spectral_clustering(seed=36): + # Test using pipeline to do spectral clustering + random_state = np.random.RandomState(seed) + se_rbf = SpectralEmbedding( + n_components=n_clusters, affinity="rbf", random_state=random_state + ) + se_knn = SpectralEmbedding( + n_components=n_clusters, + affinity="nearest_neighbors", + n_neighbors=5, + random_state=random_state, + ) + for se in [se_rbf, se_knn]: + km = KMeans(n_clusters=n_clusters, random_state=random_state, n_init=10) + km.fit(se.fit_transform(S)) + assert_array_almost_equal( + normalized_mutual_info_score(km.labels_, true_labels), 1.0, 2 + ) + + +def test_connectivity(seed=36): + # Test that graph connectivity test works as expected + graph = np.array( + [ + [1, 0, 0, 0, 0], + [0, 1, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 1, 1], + [0, 0, 0, 1, 1], + ] + ) + assert not _graph_is_connected(graph) + for csr_container in CSR_CONTAINERS: + assert not _graph_is_connected(csr_container(graph)) + for csc_container in CSC_CONTAINERS: + assert not _graph_is_connected(csc_container(graph)) + + graph = np.array( + [ + [1, 1, 0, 0, 0], + [1, 1, 1, 0, 0], + [0, 1, 1, 1, 0], + [0, 0, 1, 1, 1], + [0, 0, 0, 1, 1], + ] + ) + assert _graph_is_connected(graph) + for csr_container in CSR_CONTAINERS: + assert _graph_is_connected(csr_container(graph)) + for csc_container in CSC_CONTAINERS: + assert _graph_is_connected(csc_container(graph)) + + +def test_spectral_embedding_deterministic(): + # Test that Spectral Embedding is deterministic + random_state = np.random.RandomState(36) + data = random_state.randn(10, 30) + sims = rbf_kernel(data) + embedding_1 = spectral_embedding(sims) + embedding_2 = spectral_embedding(sims) + assert_array_almost_equal(embedding_1, embedding_2) + + +def test_spectral_embedding_unnormalized(): + # Test that spectral_embedding is also processing unnormalized laplacian + # correctly + random_state = np.random.RandomState(36) + data = random_state.randn(10, 30) + sims = rbf_kernel(data) + n_components = 8 + embedding_1 = spectral_embedding( + sims, norm_laplacian=False, n_components=n_components, drop_first=False + ) + + # Verify using manual computation with dense eigh + laplacian, dd = csgraph_laplacian(sims, normed=False, return_diag=True) + _, diffusion_map = eigh(laplacian) + embedding_2 = diffusion_map.T[:n_components] + embedding_2 = _deterministic_vector_sign_flip(embedding_2).T + + assert_array_almost_equal(embedding_1, embedding_2) + + +def test_spectral_embedding_first_eigen_vector(): + # Test that the first eigenvector of spectral_embedding + # is constant and that the second is not (for a connected graph) + random_state = np.random.RandomState(36) + data = random_state.randn(10, 30) + sims = rbf_kernel(data) + n_components = 2 + + for seed in range(10): + embedding = spectral_embedding( + sims, + norm_laplacian=False, + n_components=n_components, + drop_first=False, + random_state=seed, + ) + + assert np.std(embedding[:, 0]) == pytest.approx(0) + assert np.std(embedding[:, 1]) > 1e-3 + + +@pytest.mark.parametrize( + "eigen_solver", + [ + "arpack", + "lobpcg", + pytest.param("amg", marks=skip_if_no_pyamg), + ], +) +@pytest.mark.parametrize("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 + + +@pytest.mark.skipif( + 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) + + +@pytest.mark.parametrize("solver", ["arpack", "amg", "lobpcg"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_spectral_eigen_tol_auto(monkeypatch, solver, csr_container): + """Test that `eigen_tol="auto"` is resolved correctly""" + if solver == "amg" and not pyamg_available: + pytest.skip("PyAMG is not available.") + X, _ = make_blobs( + n_samples=200, random_state=0, centers=[[1, 1], [-1, -1]], cluster_std=0.01 + ) + D = pairwise_distances(X) # Distance matrix + S = np.max(D) - D # Similarity matrix + + solver_func = eigsh if solver == "arpack" else lobpcg + default_value = 0 if solver == "arpack" else None + if solver == "amg": + S = csr_container(S) + + mocked_solver = Mock(side_effect=solver_func) + + monkeypatch.setattr(_spectral_embedding, solver_func.__qualname__, mocked_solver) + + spectral_embedding(S, random_state=42, eigen_solver=solver, eigen_tol="auto") + mocked_solver.assert_called() + + _, kwargs = mocked_solver.call_args + assert kwargs["tol"] == default_value diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_t_sne.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_t_sne.py new file mode 100644 index 0000000000000000000000000000000000000000..4f32b889d5b1f20c758228f075e4f5541bfb3300 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/manifold/tests/test_t_sne.py @@ -0,0 +1,1187 @@ +import re +import sys +from io import StringIO + +import numpy as np +import pytest +import scipy.sparse as sp +from numpy.testing import assert_allclose +from scipy.optimize import check_grad +from scipy.spatial.distance import pdist, squareform + +from sklearn import config_context +from sklearn.datasets import make_blobs + +# mypy error: Module 'sklearn.manifold' has no attribute '_barnes_hut_tsne' +from sklearn.manifold import ( # type: ignore[attr-defined] + TSNE, + _barnes_hut_tsne, +) +from sklearn.manifold._t_sne import ( + _gradient_descent, + _joint_probabilities, + _joint_probabilities_nn, + _kl_divergence, + _kl_divergence_bh, + trustworthiness, +) +from sklearn.manifold._utils import _binary_search_perplexity +from sklearn.metrics.pairwise import ( + cosine_distances, + manhattan_distances, + pairwise_distances, +) +from sklearn.neighbors import NearestNeighbors, kneighbors_graph +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + skip_if_32bit, +) +from sklearn.utils.fixes import CSR_CONTAINERS, LIL_CONTAINERS + +x = np.linspace(0, 1, 10) +xx, yy = np.meshgrid(x, x) +X_2d_grid = np.hstack( + [ + xx.ravel().reshape(-1, 1), + yy.ravel().reshape(-1, 1), + ] +) + + +def test_gradient_descent_stops(): + # Test stopping conditions of gradient descent. + class ObjectiveSmallGradient: + def __init__(self): + self.it = -1 + + def __call__(self, _, compute_error=True): + self.it += 1 + return (10 - self.it) / 10.0, np.array([1e-5]) + + def flat_function(_, compute_error=True): + return 0.0, np.ones(1) + + # Gradient norm + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + ObjectiveSmallGradient(), + np.zeros(1), + 0, + max_iter=100, + n_iter_without_progress=100, + momentum=0.0, + learning_rate=0.0, + min_gain=0.0, + min_grad_norm=1e-5, + verbose=2, + ) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert error == 1.0 + assert it == 0 + assert "gradient norm" in out + + # Maximum number of iterations without improvement + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + flat_function, + np.zeros(1), + 0, + max_iter=100, + n_iter_without_progress=10, + momentum=0.0, + learning_rate=0.0, + min_gain=0.0, + min_grad_norm=0.0, + verbose=2, + ) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert error == 0.0 + assert it == 11 + assert "did not make any progress" in out + + # Maximum number of iterations + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + _, error, it = _gradient_descent( + ObjectiveSmallGradient(), + np.zeros(1), + 0, + max_iter=11, + n_iter_without_progress=100, + momentum=0.0, + learning_rate=0.0, + min_gain=0.0, + min_grad_norm=0.0, + verbose=2, + ) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + assert error == 0.0 + assert it == 10 + assert "Iteration 10" in out + + +def test_binary_search(): + # Test if the binary search finds Gaussians with desired perplexity. + random_state = check_random_state(0) + data = random_state.randn(50, 5) + distances = pairwise_distances(data).astype(np.float32) + desired_perplexity = 25.0 + P = _binary_search_perplexity(distances, desired_perplexity, verbose=0) + P = np.maximum(P, np.finfo(np.double).eps) + mean_perplexity = np.mean( + [np.exp(-np.sum(P[i] * np.log(P[i]))) for i in range(P.shape[0])] + ) + assert_almost_equal(mean_perplexity, desired_perplexity, decimal=3) + + +def test_binary_search_underflow(): + # Test if the binary search finds Gaussians with desired perplexity. + # A more challenging case than the one above, producing numeric + # underflow in float precision (see issue #19471 and PR #19472). + random_state = check_random_state(42) + data = random_state.randn(1, 90).astype(np.float32) + 100 + desired_perplexity = 30.0 + P = _binary_search_perplexity(data, desired_perplexity, verbose=0) + perplexity = 2 ** -np.nansum(P[0, 1:] * np.log2(P[0, 1:])) + assert_almost_equal(perplexity, desired_perplexity, decimal=3) + + +def test_binary_search_neighbors(): + # Binary perplexity search approximation. + # Should be approximately equal to the slow method when we use + # all points as neighbors. + n_samples = 200 + desired_perplexity = 25.0 + random_state = check_random_state(0) + data = random_state.randn(n_samples, 2).astype(np.float32, copy=False) + distances = pairwise_distances(data) + P1 = _binary_search_perplexity(distances, desired_perplexity, verbose=0) + + # Test that when we use all the neighbors the results are identical + n_neighbors = n_samples - 1 + nn = NearestNeighbors().fit(data) + distance_graph = nn.kneighbors_graph(n_neighbors=n_neighbors, mode="distance") + distances_nn = distance_graph.data.astype(np.float32, copy=False) + distances_nn = distances_nn.reshape(n_samples, n_neighbors) + P2 = _binary_search_perplexity(distances_nn, desired_perplexity, verbose=0) + + indptr = distance_graph.indptr + P1_nn = np.array( + [ + P1[k, distance_graph.indices[indptr[k] : indptr[k + 1]]] + for k in range(n_samples) + ] + ) + assert_array_almost_equal(P1_nn, P2, decimal=4) + + # Test that the highest P_ij are the same when fewer neighbors are used + for k in np.linspace(150, n_samples - 1, 5): + k = int(k) + topn = k * 10 # check the top 10 * k entries out of k * k entries + distance_graph = nn.kneighbors_graph(n_neighbors=k, mode="distance") + distances_nn = distance_graph.data.astype(np.float32, copy=False) + distances_nn = distances_nn.reshape(n_samples, k) + P2k = _binary_search_perplexity(distances_nn, desired_perplexity, verbose=0) + assert_array_almost_equal(P1_nn, P2, decimal=2) + idx = np.argsort(P1.ravel())[::-1] + P1top = P1.ravel()[idx][:topn] + idx = np.argsort(P2k.ravel())[::-1] + P2top = P2k.ravel()[idx][:topn] + assert_array_almost_equal(P1top, P2top, decimal=2) + + +def test_binary_perplexity_stability(): + # Binary perplexity search should be stable. + # The binary_search_perplexity had a bug wherein the P array + # was uninitialized, leading to sporadically failing tests. + n_neighbors = 10 + n_samples = 100 + random_state = check_random_state(0) + data = random_state.randn(n_samples, 5) + nn = NearestNeighbors().fit(data) + distance_graph = nn.kneighbors_graph(n_neighbors=n_neighbors, mode="distance") + distances = distance_graph.data.astype(np.float32, copy=False) + distances = distances.reshape(n_samples, n_neighbors) + last_P = None + desired_perplexity = 3 + for _ in range(100): + P = _binary_search_perplexity(distances.copy(), desired_perplexity, verbose=0) + P1 = _joint_probabilities_nn(distance_graph, desired_perplexity, verbose=0) + # Convert the sparse matrix to a dense one for testing + P1 = P1.toarray() + if last_P is None: + last_P = P + last_P1 = P1 + else: + assert_array_almost_equal(P, last_P, decimal=4) + assert_array_almost_equal(P1, last_P1, decimal=4) + + +def test_gradient(): + # Test gradient of Kullback-Leibler divergence. + random_state = check_random_state(0) + + n_samples = 50 + n_features = 2 + n_components = 2 + alpha = 1.0 + + distances = random_state.randn(n_samples, n_features).astype(np.float32) + distances = np.abs(distances.dot(distances.T)) + np.fill_diagonal(distances, 0.0) + X_embedded = random_state.randn(n_samples, n_components).astype(np.float32) + + P = _joint_probabilities(distances, desired_perplexity=25.0, verbose=0) + + def fun(params): + return _kl_divergence(params, P, alpha, n_samples, n_components)[0] + + def grad(params): + return _kl_divergence(params, P, alpha, n_samples, n_components)[1] + + assert_almost_equal(check_grad(fun, grad, X_embedded.ravel()), 0.0, decimal=5) + + +def test_trustworthiness(): + # Test trustworthiness score. + random_state = check_random_state(0) + + # Affine transformation + X = random_state.randn(100, 2) + assert trustworthiness(X, 5.0 + X / 10.0) == 1.0 + + # Randomly shuffled + X = np.arange(100).reshape(-1, 1) + X_embedded = X.copy() + random_state.shuffle(X_embedded) + assert trustworthiness(X, X_embedded) < 0.6 + + # Completely different + X = np.arange(5).reshape(-1, 1) + X_embedded = np.array([[0], [2], [4], [1], [3]]) + assert_almost_equal(trustworthiness(X, X_embedded, n_neighbors=1), 0.2) + + +def test_trustworthiness_n_neighbors_error(): + """Raise an error when n_neighbors >= n_samples / 2. + + Non-regression test for #18567. + """ + regex = "n_neighbors .+ should be less than .+" + rng = np.random.RandomState(42) + X = rng.rand(7, 4) + X_embedded = rng.rand(7, 2) + with pytest.raises(ValueError, match=regex): + trustworthiness(X, X_embedded, n_neighbors=5) + + trust = trustworthiness(X, X_embedded, n_neighbors=3) + assert 0 <= trust <= 1 + + +@pytest.mark.parametrize("method", ["exact", "barnes_hut"]) +@pytest.mark.parametrize("init", ("random", "pca")) +def test_preserve_trustworthiness_approximately(method, init): + # Nearest neighbors should be preserved approximately. + random_state = check_random_state(0) + n_components = 2 + X = random_state.randn(50, n_components).astype(np.float32) + tsne = TSNE( + n_components=n_components, + init=init, + random_state=0, + method=method, + max_iter=700, + learning_rate="auto", + ) + X_embedded = tsne.fit_transform(X) + t = trustworthiness(X, X_embedded, n_neighbors=1) + assert t > 0.85 + + +def test_optimization_minimizes_kl_divergence(): + """t-SNE should give a lower KL divergence with more iterations.""" + random_state = check_random_state(0) + X, _ = make_blobs(n_features=3, random_state=random_state) + kl_divergences = [] + for max_iter in [250, 300, 350]: + tsne = TSNE( + n_components=2, + init="random", + perplexity=10, + learning_rate=100.0, + max_iter=max_iter, + random_state=0, + ) + tsne.fit_transform(X) + kl_divergences.append(tsne.kl_divergence_) + assert kl_divergences[1] <= kl_divergences[0] + assert kl_divergences[2] <= kl_divergences[1] + + +@pytest.mark.parametrize("method", ["exact", "barnes_hut"]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_fit_transform_csr_matrix(method, csr_container): + # TODO: compare results on dense and sparse data as proposed in: + # https://github.com/scikit-learn/scikit-learn/pull/23585#discussion_r968388186 + # X can be a sparse matrix. + rng = check_random_state(0) + X = rng.randn(50, 2) + X[(rng.randint(0, 50, 25), rng.randint(0, 2, 25))] = 0.0 + X_csr = csr_container(X) + tsne = TSNE( + n_components=2, + init="random", + perplexity=10, + learning_rate=100.0, + random_state=0, + method=method, + max_iter=750, + ) + X_embedded = tsne.fit_transform(X_csr) + assert_allclose(trustworthiness(X_csr, X_embedded, n_neighbors=1), 1.0, rtol=1.1e-1) + + +def test_preserve_trustworthiness_approximately_with_precomputed_distances(): + # Nearest neighbors should be preserved approximately. + random_state = check_random_state(0) + for i in range(3): + X = random_state.randn(80, 2) + D = squareform(pdist(X), "sqeuclidean") + tsne = TSNE( + n_components=2, + perplexity=2, + learning_rate=100.0, + early_exaggeration=2.0, + metric="precomputed", + random_state=i, + verbose=0, + max_iter=500, + init="random", + ) + X_embedded = tsne.fit_transform(D) + t = trustworthiness(D, X_embedded, n_neighbors=1, metric="precomputed") + assert t > 0.95 + + +def test_trustworthiness_not_euclidean_metric(): + # Test trustworthiness with a metric different from 'euclidean' and + # 'precomputed' + random_state = check_random_state(0) + X = random_state.randn(100, 2) + assert trustworthiness(X, X, metric="cosine") == trustworthiness( + pairwise_distances(X, metric="cosine"), X, metric="precomputed" + ) + + +@pytest.mark.parametrize( + "method, retype", + [ + ("exact", np.asarray), + ("barnes_hut", np.asarray), + *[("barnes_hut", csr_container) for csr_container in CSR_CONTAINERS], + ], +) +@pytest.mark.parametrize( + "D, message_regex", + [ + ([[0.0], [1.0]], ".* square distance matrix"), + ([[0.0, -1.0], [1.0, 0.0]], ".* positive.*"), + ], +) +def test_bad_precomputed_distances(method, D, retype, message_regex): + tsne = TSNE( + metric="precomputed", + method=method, + init="random", + random_state=42, + perplexity=1, + ) + with pytest.raises(ValueError, match=message_regex): + tsne.fit_transform(retype(D)) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_exact_no_precomputed_sparse(csr_container): + tsne = TSNE( + metric="precomputed", + method="exact", + init="random", + random_state=42, + perplexity=1, + ) + with pytest.raises(TypeError, match="sparse"): + tsne.fit_transform(csr_container([[0, 5], [5, 0]])) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_high_perplexity_precomputed_sparse_distances(csr_container): + # Perplexity should be less than 50 + dist = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) + bad_dist = csr_container(dist) + tsne = TSNE(metric="precomputed", init="random", random_state=42, perplexity=1) + msg = "3 neighbors per samples are required, but some samples have only 1" + with pytest.raises(ValueError, match=msg): + tsne.fit_transform(bad_dist) + + +@pytest.mark.filterwarnings( + "ignore:Precomputed sparse input was not sorted by " + "row values:sklearn.exceptions.EfficiencyWarning" +) +@pytest.mark.parametrize("sparse_container", CSR_CONTAINERS + LIL_CONTAINERS) +def test_sparse_precomputed_distance(sparse_container): + """Make sure that TSNE works identically for sparse and dense matrix""" + random_state = check_random_state(0) + X = random_state.randn(100, 2) + + D_sparse = kneighbors_graph(X, n_neighbors=100, mode="distance", include_self=True) + D = pairwise_distances(X) + assert sp.issparse(D_sparse) + assert_almost_equal(D_sparse.toarray(), D) + + tsne = TSNE( + metric="precomputed", random_state=0, init="random", learning_rate="auto" + ) + Xt_dense = tsne.fit_transform(D) + + Xt_sparse = tsne.fit_transform(sparse_container(D_sparse)) + assert_almost_equal(Xt_dense, Xt_sparse) + + +def test_non_positive_computed_distances(): + # Computed distance matrices must be positive. + def metric(x, y): + return -1 + + # Negative computed distances should be caught even if result is squared + tsne = TSNE(metric=metric, method="exact", perplexity=1) + X = np.array([[0.0, 0.0], [1.0, 1.0]]) + with pytest.raises(ValueError, match="All distances .*metric given.*"): + tsne.fit_transform(X) + + +def test_init_ndarray(): + # Initialize TSNE with ndarray and test fit + tsne = TSNE(init=np.zeros((100, 2)), learning_rate="auto") + X_embedded = tsne.fit_transform(np.ones((100, 5))) + assert_array_equal(np.zeros((100, 2)), X_embedded) + + +def test_init_ndarray_precomputed(): + # Initialize TSNE with ndarray and metric 'precomputed' + # Make sure no FutureWarning is thrown from _fit + tsne = TSNE( + init=np.zeros((100, 2)), + metric="precomputed", + learning_rate=50.0, + ) + tsne.fit(np.zeros((100, 100))) + + +def test_pca_initialization_not_compatible_with_precomputed_kernel(): + # Precomputed distance matrices cannot use PCA initialization. + tsne = TSNE(metric="precomputed", init="pca", perplexity=1) + with pytest.raises( + ValueError, + match='The parameter init="pca" cannot be used with metric="precomputed".', + ): + tsne.fit_transform(np.array([[0.0], [1.0]])) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pca_initialization_not_compatible_with_sparse_input(csr_container): + # Sparse input matrices cannot use PCA initialization. + tsne = TSNE(init="pca", learning_rate=100.0, perplexity=1) + with pytest.raises(TypeError, match="PCA initialization.*"): + tsne.fit_transform(csr_container([[0, 5], [5, 0]])) + + +def test_n_components_range(): + # barnes_hut method should only be used with n_components <= 3 + tsne = TSNE(n_components=4, method="barnes_hut", perplexity=1) + with pytest.raises(ValueError, match="'n_components' should be .*"): + tsne.fit_transform(np.array([[0.0], [1.0]])) + + +def test_early_exaggeration_used(): + # check that the ``early_exaggeration`` parameter has an effect + random_state = check_random_state(0) + n_components = 2 + methods = ["exact", "barnes_hut"] + X = random_state.randn(25, n_components).astype(np.float32) + for method in methods: + tsne = TSNE( + n_components=n_components, + perplexity=1, + learning_rate=100.0, + init="pca", + random_state=0, + method=method, + early_exaggeration=1.0, + max_iter=250, + ) + X_embedded1 = tsne.fit_transform(X) + tsne = TSNE( + n_components=n_components, + perplexity=1, + learning_rate=100.0, + init="pca", + random_state=0, + method=method, + early_exaggeration=10.0, + max_iter=250, + ) + X_embedded2 = tsne.fit_transform(X) + + assert not np.allclose(X_embedded1, X_embedded2) + + +def test_max_iter_used(): + # check that the ``max_iter`` parameter has an effect + random_state = check_random_state(0) + n_components = 2 + methods = ["exact", "barnes_hut"] + X = random_state.randn(25, n_components).astype(np.float32) + for method in methods: + for max_iter in [251, 500]: + tsne = TSNE( + n_components=n_components, + perplexity=1, + learning_rate=0.5, + init="random", + random_state=0, + method=method, + early_exaggeration=1.0, + max_iter=max_iter, + ) + tsne.fit_transform(X) + + assert tsne.n_iter_ == max_iter - 1 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_answer_gradient_two_points(csr_container): + # Test the tree with only a single set of children. + # + # These tests & answers have been checked against the reference + # implementation by LvdM. + pos_input = np.array([[1.0, 0.0], [0.0, 1.0]]) + pos_output = np.array( + [[-4.961291e-05, -1.072243e-04], [9.259460e-05, 2.702024e-04]] + ) + neighbors = np.array([[1], [0]]) + grad_output = np.array( + [[-2.37012478e-05, -6.29044398e-05], [2.37012478e-05, 6.29044398e-05]] + ) + _run_answer_test(pos_input, pos_output, neighbors, grad_output, csr_container) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_answer_gradient_four_points(csr_container): + # Four points tests the tree with multiple levels of children. + # + # These tests & answers have been checked against the reference + # implementation by LvdM. + pos_input = np.array([[1.0, 0.0], [0.0, 1.0], [5.0, 2.0], [7.3, 2.2]]) + pos_output = np.array( + [ + [6.080564e-05, -7.120823e-05], + [-1.718945e-04, -4.000536e-05], + [-2.271720e-04, 8.663310e-05], + [-1.032577e-04, -3.582033e-05], + ] + ) + neighbors = np.array([[1, 2, 3], [0, 2, 3], [1, 0, 3], [1, 2, 0]]) + grad_output = np.array( + [ + [5.81128448e-05, -7.78033454e-06], + [-5.81526851e-05, 7.80976444e-06], + [4.24275173e-08, -3.69569698e-08], + [-2.58720939e-09, 7.52706374e-09], + ] + ) + _run_answer_test(pos_input, pos_output, neighbors, grad_output, csr_container) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_skip_num_points_gradient(csr_container): + # Test the kwargs option skip_num_points. + # + # Skip num points should make it such that the Barnes_hut gradient + # is not calculated for indices below skip_num_point. + # Aside from skip_num_points=2 and the first two gradient rows + # being set to zero, these data points are the same as in + # test_answer_gradient_four_points() + pos_input = np.array([[1.0, 0.0], [0.0, 1.0], [5.0, 2.0], [7.3, 2.2]]) + pos_output = np.array( + [ + [6.080564e-05, -7.120823e-05], + [-1.718945e-04, -4.000536e-05], + [-2.271720e-04, 8.663310e-05], + [-1.032577e-04, -3.582033e-05], + ] + ) + neighbors = np.array([[1, 2, 3], [0, 2, 3], [1, 0, 3], [1, 2, 0]]) + grad_output = np.array( + [ + [0.0, 0.0], + [0.0, 0.0], + [4.24275173e-08, -3.69569698e-08], + [-2.58720939e-09, 7.52706374e-09], + ] + ) + _run_answer_test( + pos_input, pos_output, neighbors, grad_output, csr_container, False, 0.1, 2 + ) + + +def _run_answer_test( + pos_input, + pos_output, + neighbors, + grad_output, + csr_container, + verbose=False, + perplexity=0.1, + skip_num_points=0, +): + distances = pairwise_distances(pos_input).astype(np.float32) + args = distances, perplexity, verbose + pos_output = pos_output.astype(np.float32) + neighbors = neighbors.astype(np.int64, copy=False) + pij_input = _joint_probabilities(*args) + pij_input = squareform(pij_input).astype(np.float32) + grad_bh = np.zeros(pos_output.shape, dtype=np.float32) + + P = csr_container(pij_input) + + neighbors = P.indices.astype(np.int64) + indptr = P.indptr.astype(np.int64) + + _barnes_hut_tsne.gradient( + P.data, pos_output, neighbors, indptr, grad_bh, 0.5, 2, 1, skip_num_points=0 + ) + assert_array_almost_equal(grad_bh, grad_output, decimal=4) + + +def test_verbose(): + # Verbose options write to stdout. + random_state = check_random_state(0) + tsne = TSNE(verbose=2, perplexity=4) + X = random_state.randn(5, 2) + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + tsne.fit_transform(X) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + assert "[t-SNE]" in out + assert "nearest neighbors..." in out + assert "Computed conditional probabilities" in out + assert "Mean sigma" in out + assert "early exaggeration" in out + + +def test_chebyshev_metric(): + # t-SNE should allow metrics that cannot be squared (issue #3526). + random_state = check_random_state(0) + tsne = TSNE(metric="chebyshev", perplexity=4) + X = random_state.randn(5, 2) + tsne.fit_transform(X) + + +def test_reduction_to_one_component(): + # t-SNE should allow reduction to one component (issue #4154). + random_state = check_random_state(0) + tsne = TSNE(n_components=1, perplexity=4) + X = random_state.randn(5, 2) + X_embedded = tsne.fit(X).embedding_ + assert np.all(np.isfinite(X_embedded)) + + +@pytest.mark.parametrize("method", ["barnes_hut", "exact"]) +@pytest.mark.parametrize("dt", [np.float32, np.float64]) +def test_64bit(method, dt): + # Ensure 64bit arrays are handled correctly. + random_state = check_random_state(0) + + X = random_state.randn(10, 2).astype(dt, copy=False) + tsne = TSNE( + n_components=2, + perplexity=2, + learning_rate=100.0, + random_state=0, + method=method, + verbose=0, + max_iter=300, + init="random", + ) + X_embedded = tsne.fit_transform(X) + effective_type = X_embedded.dtype + + # tsne cython code is only single precision, so the output will + # always be single precision, irrespectively of the input dtype + assert effective_type == np.float32 + + +@pytest.mark.parametrize("method", ["barnes_hut", "exact"]) +def test_kl_divergence_not_nan(method): + # Ensure kl_divergence_ is computed at last iteration + # even though max_iter % n_iter_check != 0, i.e. 1003 % 50 != 0 + random_state = check_random_state(0) + + X = random_state.randn(50, 2) + tsne = TSNE( + n_components=2, + perplexity=2, + learning_rate=100.0, + random_state=0, + method=method, + verbose=0, + max_iter=503, + init="random", + ) + tsne.fit_transform(X) + + assert not np.isnan(tsne.kl_divergence_) + + +def test_barnes_hut_angle(): + # When Barnes-Hut's angle=0 this corresponds to the exact method. + angle = 0.0 + perplexity = 10 + n_samples = 100 + for n_components in [2, 3]: + n_features = 5 + degrees_of_freedom = float(n_components - 1.0) + + random_state = check_random_state(0) + data = random_state.randn(n_samples, n_features) + distances = pairwise_distances(data) + params = random_state.randn(n_samples, n_components) + P = _joint_probabilities(distances, perplexity, verbose=0) + kl_exact, grad_exact = _kl_divergence( + params, P, degrees_of_freedom, n_samples, n_components + ) + + n_neighbors = n_samples - 1 + distances_csr = ( + NearestNeighbors() + .fit(data) + .kneighbors_graph(n_neighbors=n_neighbors, mode="distance") + ) + P_bh = _joint_probabilities_nn(distances_csr, perplexity, verbose=0) + kl_bh, grad_bh = _kl_divergence_bh( + params, + P_bh, + degrees_of_freedom, + n_samples, + n_components, + angle=angle, + skip_num_points=0, + verbose=0, + ) + + P = squareform(P) + P_bh = P_bh.toarray() + assert_array_almost_equal(P_bh, P, decimal=5) + assert_almost_equal(kl_exact, kl_bh, decimal=3) + + +@skip_if_32bit +def test_n_iter_without_progress(): + # Use a dummy negative n_iter_without_progress and check output on stdout + random_state = check_random_state(0) + X = random_state.randn(100, 10) + for method in ["barnes_hut", "exact"]: + tsne = TSNE( + n_iter_without_progress=-1, + verbose=2, + learning_rate=1e8, + random_state=0, + method=method, + max_iter=351, + init="random", + ) + tsne._N_ITER_CHECK = 1 + tsne._EXPLORATION_MAX_ITER = 0 + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + tsne.fit_transform(X) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + # The output needs to contain the value of n_iter_without_progress + assert "did not make any progress during the last -1 episodes. Finished." in out + + +def test_min_grad_norm(): + # Make sure that the parameter min_grad_norm is used correctly + random_state = check_random_state(0) + X = random_state.randn(100, 2) + min_grad_norm = 0.002 + tsne = TSNE(min_grad_norm=min_grad_norm, verbose=2, random_state=0, method="exact") + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + tsne.fit_transform(X) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + lines_out = out.split("\n") + + # extract the gradient norm from the verbose output + gradient_norm_values = [] + for line in lines_out: + # When the computation is Finished just an old gradient norm value + # is repeated that we do not need to store + if "Finished" in line: + break + + start_grad_norm = line.find("gradient norm") + if start_grad_norm >= 0: + line = line[start_grad_norm:] + line = line.replace("gradient norm = ", "").split(" ")[0] + gradient_norm_values.append(float(line)) + + # Compute how often the gradient norm is smaller than min_grad_norm + gradient_norm_values = np.array(gradient_norm_values) + n_smaller_gradient_norms = len( + gradient_norm_values[gradient_norm_values <= min_grad_norm] + ) + + # The gradient norm can be smaller than min_grad_norm at most once, + # because in the moment it becomes smaller the optimization stops + assert n_smaller_gradient_norms <= 1 + + +def test_accessible_kl_divergence(): + # Ensures that the accessible kl_divergence matches the computed value + random_state = check_random_state(0) + X = random_state.randn(50, 2) + tsne = TSNE( + n_iter_without_progress=2, + verbose=2, + random_state=0, + method="exact", + max_iter=500, + ) + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + tsne.fit_transform(X) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + # The output needs to contain the accessible kl_divergence as the error at + # the last iteration + for line in out.split("\n")[::-1]: + if "Iteration" in line: + _, _, error = line.partition("error = ") + if error: + error, _, _ = error.partition(",") + break + assert_almost_equal(tsne.kl_divergence_, float(error), decimal=5) + + +@pytest.mark.parametrize("method", ["barnes_hut", "exact"]) +def test_uniform_grid(method): + """Make sure that TSNE can approximately recover a uniform 2D grid + + Due to ties in distances between point in X_2d_grid, this test is platform + dependent for ``method='barnes_hut'`` due to numerical imprecision. + + Also, t-SNE is not assured to converge to the right solution because bad + initialization can lead to convergence to bad local minimum (the + optimization problem is non-convex). To avoid breaking the test too often, + we re-run t-SNE from the final point when the convergence is not good + enough. + """ + seeds = range(3) + max_iter = 500 + for seed in seeds: + tsne = TSNE( + n_components=2, + init="random", + random_state=seed, + perplexity=50, + max_iter=max_iter, + method=method, + learning_rate="auto", + ) + Y = tsne.fit_transform(X_2d_grid) + + try_name = "{}_{}".format(method, seed) + try: + assert_uniform_grid(Y, try_name) + except AssertionError: + # If the test fails a first time, re-run with init=Y to see if + # this was caused by a bad initialization. Note that this will + # also run an early_exaggeration step. + try_name += ":rerun" + tsne.init = Y + Y = tsne.fit_transform(X_2d_grid) + assert_uniform_grid(Y, try_name) + + +def assert_uniform_grid(Y, try_name=None): + # Ensure that the resulting embedding leads to approximately + # uniformly spaced points: the distance to the closest neighbors + # should be non-zero and approximately constant. + nn = NearestNeighbors(n_neighbors=1).fit(Y) + dist_to_nn = nn.kneighbors(return_distance=True)[0].ravel() + assert dist_to_nn.min() > 0.1 + + smallest_to_mean = dist_to_nn.min() / np.mean(dist_to_nn) + largest_to_mean = dist_to_nn.max() / np.mean(dist_to_nn) + + assert smallest_to_mean > 0.5, try_name + assert largest_to_mean < 2, try_name + + +def test_bh_match_exact(): + # check that the ``barnes_hut`` method match the exact one when + # ``angle = 0`` and ``perplexity > n_samples / 3`` + random_state = check_random_state(0) + n_features = 10 + X = random_state.randn(30, n_features).astype(np.float32) + X_embeddeds = {} + max_iter = {} + for method in ["exact", "barnes_hut"]: + tsne = TSNE( + n_components=2, + method=method, + learning_rate=1.0, + init="random", + random_state=0, + max_iter=251, + perplexity=29.5, + angle=0, + ) + # Kill the early_exaggeration + tsne._EXPLORATION_MAX_ITER = 0 + X_embeddeds[method] = tsne.fit_transform(X) + max_iter[method] = tsne.n_iter_ + + assert max_iter["exact"] == max_iter["barnes_hut"] + assert_allclose(X_embeddeds["exact"], X_embeddeds["barnes_hut"], rtol=1e-4) + + +def test_gradient_bh_multithread_match_sequential(): + # check that the bh gradient with different num_threads gives the same + # results + + n_features = 10 + n_samples = 30 + n_components = 2 + degrees_of_freedom = 1 + + angle = 3 + perplexity = 5 + + random_state = check_random_state(0) + data = random_state.randn(n_samples, n_features).astype(np.float32) + params = random_state.randn(n_samples, n_components) + + n_neighbors = n_samples - 1 + distances_csr = ( + NearestNeighbors() + .fit(data) + .kneighbors_graph(n_neighbors=n_neighbors, mode="distance") + ) + P_bh = _joint_probabilities_nn(distances_csr, perplexity, verbose=0) + kl_sequential, grad_sequential = _kl_divergence_bh( + params, + P_bh, + degrees_of_freedom, + n_samples, + n_components, + angle=angle, + skip_num_points=0, + verbose=0, + num_threads=1, + ) + for num_threads in [2, 4]: + kl_multithread, grad_multithread = _kl_divergence_bh( + params, + P_bh, + degrees_of_freedom, + n_samples, + n_components, + angle=angle, + skip_num_points=0, + verbose=0, + num_threads=num_threads, + ) + + assert_allclose(kl_multithread, kl_sequential, rtol=1e-6) + assert_allclose(grad_multithread, grad_multithread) + + +@pytest.mark.parametrize( + "metric, dist_func", + [("manhattan", manhattan_distances), ("cosine", cosine_distances)], +) +@pytest.mark.parametrize("method", ["barnes_hut", "exact"]) +def test_tsne_with_different_distance_metrics(metric, dist_func, method): + """Make sure that TSNE works for different distance metrics""" + + if method == "barnes_hut" and metric == "manhattan": + # The distances computed by `manhattan_distances` differ slightly from those + # computed internally by NearestNeighbors via the PairwiseDistancesReduction + # Cython code-based. This in turns causes T-SNE to converge to a different + # solution but this should not impact the qualitative results as both + # methods. + # NOTE: it's probably not valid from a mathematical point of view to use the + # Manhattan distance for T-SNE... + # TODO: re-enable this test if/when `manhattan_distances` is refactored to + # reuse the same underlying Cython code NearestNeighbors. + # For reference, see: + # https://github.com/scikit-learn/scikit-learn/pull/23865/files#r925721573 + pytest.xfail( + "Distance computations are different for method == 'barnes_hut' and metric" + " == 'manhattan', but this is expected." + ) + + random_state = check_random_state(0) + n_components_original = 3 + n_components_embedding = 2 + X = random_state.randn(50, n_components_original).astype(np.float32) + X_transformed_tsne = TSNE( + metric=metric, + method=method, + n_components=n_components_embedding, + random_state=0, + max_iter=300, + init="random", + learning_rate="auto", + ).fit_transform(X) + X_transformed_tsne_precomputed = TSNE( + metric="precomputed", + method=method, + n_components=n_components_embedding, + random_state=0, + max_iter=300, + init="random", + learning_rate="auto", + ).fit_transform(dist_func(X)) + assert_array_equal(X_transformed_tsne, X_transformed_tsne_precomputed) + + +@pytest.mark.parametrize("method", ["exact", "barnes_hut"]) +def test_tsne_n_jobs(method): + """Make sure that the n_jobs parameter doesn't impact the output""" + random_state = check_random_state(0) + n_features = 10 + X = random_state.randn(30, n_features) + X_tr_ref = TSNE( + n_components=2, + method=method, + perplexity=25.0, + angle=0, + n_jobs=1, + random_state=0, + init="random", + learning_rate="auto", + ).fit_transform(X) + X_tr = TSNE( + n_components=2, + method=method, + perplexity=25.0, + angle=0, + n_jobs=2, + random_state=0, + init="random", + learning_rate="auto", + ).fit_transform(X) + + assert_allclose(X_tr_ref, X_tr) + + +def test_tsne_with_mahalanobis_distance(): + """Make sure that method_parameters works with mahalanobis distance.""" + random_state = check_random_state(0) + n_samples, n_features = 300, 10 + X = random_state.randn(n_samples, n_features) + default_params = { + "perplexity": 40, + "max_iter": 250, + "learning_rate": "auto", + "init": "random", + "n_components": 3, + "random_state": 0, + } + + tsne = TSNE(metric="mahalanobis", **default_params) + msg = "Must provide either V or VI for Mahalanobis distance" + with pytest.raises(ValueError, match=msg): + tsne.fit_transform(X) + + precomputed_X = squareform(pdist(X, metric="mahalanobis"), checks=True) + X_trans_expected = TSNE(metric="precomputed", **default_params).fit_transform( + precomputed_X + ) + + X_trans = TSNE( + metric="mahalanobis", metric_params={"V": np.cov(X.T)}, **default_params + ).fit_transform(X) + assert_allclose(X_trans, X_trans_expected) + + +@pytest.mark.parametrize("perplexity", (20, 30)) +def test_tsne_perplexity_validation(perplexity): + """Make sure that perplexity > n_samples results in a ValueError""" + + random_state = check_random_state(0) + X = random_state.randn(20, 2) + est = TSNE( + learning_rate="auto", + init="pca", + perplexity=perplexity, + random_state=random_state, + ) + msg = re.escape(f"perplexity ({perplexity}) must be less than n_samples (20)") + with pytest.raises(ValueError, match=msg): + est.fit_transform(X) + + +def test_tsne_works_with_pandas_output(): + """Make sure that TSNE works when the output is set to "pandas". + + Non-regression test for gh-25365. + """ + pytest.importorskip("pandas") + with config_context(transform_output="pandas"): + arr = np.arange(35 * 4).reshape(35, 4) + TSNE(n_components=2).fit_transform(arr) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ce86525acc368f681af3c1fd635fbe37ed2815c3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/__init__.py @@ -0,0 +1,181 @@ +"""Score functions, performance metrics, pairwise metrics and distance computations.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from . import cluster +from ._classification import ( + accuracy_score, + balanced_accuracy_score, + brier_score_loss, + class_likelihood_ratios, + classification_report, + cohen_kappa_score, + confusion_matrix, + d2_log_loss_score, + f1_score, + fbeta_score, + hamming_loss, + hinge_loss, + jaccard_score, + log_loss, + matthews_corrcoef, + multilabel_confusion_matrix, + precision_recall_fscore_support, + precision_score, + recall_score, + zero_one_loss, +) +from ._dist_metrics import DistanceMetric +from ._plot.confusion_matrix import ConfusionMatrixDisplay +from ._plot.det_curve import DetCurveDisplay +from ._plot.precision_recall_curve import PrecisionRecallDisplay +from ._plot.regression import PredictionErrorDisplay +from ._plot.roc_curve import RocCurveDisplay +from ._ranking import ( + auc, + average_precision_score, + coverage_error, + dcg_score, + det_curve, + label_ranking_average_precision_score, + label_ranking_loss, + ndcg_score, + precision_recall_curve, + roc_auc_score, + roc_curve, + top_k_accuracy_score, +) +from ._regression import ( + d2_absolute_error_score, + d2_pinball_score, + d2_tweedie_score, + explained_variance_score, + max_error, + mean_absolute_error, + mean_absolute_percentage_error, + mean_gamma_deviance, + mean_pinball_loss, + mean_poisson_deviance, + mean_squared_error, + mean_squared_log_error, + mean_tweedie_deviance, + median_absolute_error, + r2_score, + root_mean_squared_error, + root_mean_squared_log_error, +) +from ._scorer import check_scoring, get_scorer, get_scorer_names, make_scorer +from .cluster import ( + adjusted_mutual_info_score, + adjusted_rand_score, + calinski_harabasz_score, + completeness_score, + consensus_score, + davies_bouldin_score, + fowlkes_mallows_score, + homogeneity_completeness_v_measure, + homogeneity_score, + mutual_info_score, + normalized_mutual_info_score, + pair_confusion_matrix, + rand_score, + silhouette_samples, + silhouette_score, + v_measure_score, +) +from .pairwise import ( + euclidean_distances, + nan_euclidean_distances, + pairwise_distances, + pairwise_distances_argmin, + pairwise_distances_argmin_min, + pairwise_distances_chunked, + pairwise_kernels, +) + +__all__ = [ + "ConfusionMatrixDisplay", + "DetCurveDisplay", + "DistanceMetric", + "PrecisionRecallDisplay", + "PredictionErrorDisplay", + "RocCurveDisplay", + "accuracy_score", + "adjusted_mutual_info_score", + "adjusted_rand_score", + "auc", + "average_precision_score", + "balanced_accuracy_score", + "brier_score_loss", + "calinski_harabasz_score", + "check_scoring", + "class_likelihood_ratios", + "classification_report", + "cluster", + "cohen_kappa_score", + "completeness_score", + "confusion_matrix", + "consensus_score", + "coverage_error", + "d2_absolute_error_score", + "d2_log_loss_score", + "d2_pinball_score", + "d2_tweedie_score", + "davies_bouldin_score", + "dcg_score", + "det_curve", + "euclidean_distances", + "explained_variance_score", + "f1_score", + "fbeta_score", + "fowlkes_mallows_score", + "get_scorer", + "get_scorer_names", + "hamming_loss", + "hinge_loss", + "homogeneity_completeness_v_measure", + "homogeneity_score", + "jaccard_score", + "label_ranking_average_precision_score", + "label_ranking_loss", + "log_loss", + "make_scorer", + "matthews_corrcoef", + "max_error", + "mean_absolute_error", + "mean_absolute_percentage_error", + "mean_gamma_deviance", + "mean_pinball_loss", + "mean_poisson_deviance", + "mean_squared_error", + "mean_squared_log_error", + "mean_tweedie_deviance", + "median_absolute_error", + "multilabel_confusion_matrix", + "mutual_info_score", + "nan_euclidean_distances", + "ndcg_score", + "normalized_mutual_info_score", + "pair_confusion_matrix", + "pairwise_distances", + "pairwise_distances_argmin", + "pairwise_distances_argmin_min", + "pairwise_distances_chunked", + "pairwise_kernels", + "precision_recall_curve", + "precision_recall_fscore_support", + "precision_score", + "r2_score", + "rand_score", + "recall_score", + "roc_auc_score", + "roc_curve", + "root_mean_squared_error", + "root_mean_squared_log_error", + "silhouette_samples", + "silhouette_score", + "top_k_accuracy_score", + "v_measure_score", + "zero_one_loss", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..aa4150c88a9783aee51d6bf9e89172806728c97f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_base.py @@ -0,0 +1,193 @@ +""" +Common code for all metrics. + +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from itertools import combinations + +import numpy as np + +from ..utils import check_array, check_consistent_length +from ..utils.multiclass import type_of_target + + +def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight=None): + """Average a binary metric for multilabel classification. + + Parameters + ---------- + y_true : array, shape = [n_samples] or [n_samples, n_classes] + True binary labels in binary label indicators. + + y_score : array, shape = [n_samples] or [n_samples, n_classes] + Target scores, can either be probability estimates of the positive + class, confidence values, or binary decisions. + + average : {None, 'micro', 'macro', 'samples', 'weighted'}, default='macro' + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + binary_metric : callable, returns shape [n_classes] + The binary metric function to use. + + Returns + ------- + score : float or array of shape [n_classes] + If not ``None``, average the score, else return the score for each + classes. + + """ + average_options = (None, "micro", "macro", "weighted", "samples") + if average not in average_options: + raise ValueError("average has to be one of {0}".format(average_options)) + + y_type = type_of_target(y_true) + if y_type not in ("binary", "multilabel-indicator"): + raise ValueError("{0} format is not supported".format(y_type)) + + if y_type == "binary": + return binary_metric(y_true, y_score, sample_weight=sample_weight) + + check_consistent_length(y_true, y_score, sample_weight) + y_true = check_array(y_true) + y_score = check_array(y_score) + + not_average_axis = 1 + score_weight = sample_weight + average_weight = None + + if average == "micro": + if score_weight is not None: + score_weight = np.repeat(score_weight, y_true.shape[1]) + y_true = y_true.ravel() + y_score = y_score.ravel() + + elif average == "weighted": + if score_weight is not None: + average_weight = np.sum( + np.multiply(y_true, np.reshape(score_weight, (-1, 1))), axis=0 + ) + else: + average_weight = np.sum(y_true, axis=0) + if np.isclose(average_weight.sum(), 0.0): + return 0 + + elif average == "samples": + # swap average_weight <-> score_weight + average_weight = score_weight + score_weight = None + not_average_axis = 0 + + if y_true.ndim == 1: + y_true = y_true.reshape((-1, 1)) + + if y_score.ndim == 1: + y_score = y_score.reshape((-1, 1)) + + n_classes = y_score.shape[not_average_axis] + score = np.zeros((n_classes,)) + for c in range(n_classes): + y_true_c = y_true.take([c], axis=not_average_axis).ravel() + y_score_c = y_score.take([c], axis=not_average_axis).ravel() + score[c] = binary_metric(y_true_c, y_score_c, sample_weight=score_weight) + + # Average the results + if average is not None: + if average_weight is not None: + # Scores with 0 weights are forced to be 0, preventing the average + # score from being affected by 0-weighted NaN elements. + average_weight = np.asarray(average_weight) + score[average_weight == 0] = 0 + return float(np.average(score, weights=average_weight)) + else: + return score + + +def _average_multiclass_ovo_score(binary_metric, y_true, y_score, average="macro"): + """Average one-versus-one scores for multiclass classification. + + Uses the binary metric for one-vs-one multiclass classification, + where the score is computed according to the Hand & Till (2001) algorithm. + + Parameters + ---------- + binary_metric : callable + The binary metric function to use that accepts the following as input: + y_true_target : array, shape = [n_samples_target] + Some sub-array of y_true for a pair of classes designated + positive and negative in the one-vs-one scheme. + y_score_target : array, shape = [n_samples_target] + Scores corresponding to the probability estimates + of a sample belonging to the designated positive class label + + y_true : array-like of shape (n_samples,) + True multiclass labels. + + y_score : array-like of shape (n_samples, n_classes) + Target scores corresponding to probability estimates of a sample + belonging to a particular class. + + average : {'macro', 'weighted'}, default='macro' + Determines the type of averaging performed on the pairwise binary + metric scores: + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. Classes + are assumed to be uniformly distributed. + ``'weighted'``: + Calculate metrics for each label, taking into account the + prevalence of the classes. + + Returns + ------- + score : float + Average of the pairwise binary metric scores. + """ + check_consistent_length(y_true, y_score) + + y_true_unique = np.unique(y_true) + n_classes = y_true_unique.shape[0] + n_pairs = n_classes * (n_classes - 1) // 2 + pair_scores = np.empty(n_pairs) + + is_weighted = average == "weighted" + prevalence = np.empty(n_pairs) if is_weighted else None + + # Compute scores treating a as positive class and b as negative class, + # then b as positive class and a as negative class + for ix, (a, b) in enumerate(combinations(y_true_unique, 2)): + a_mask = y_true == a + b_mask = y_true == b + ab_mask = np.logical_or(a_mask, b_mask) + + if is_weighted: + prevalence[ix] = np.average(ab_mask) + + a_true = a_mask[ab_mask] + b_true = b_mask[ab_mask] + + a_true_score = binary_metric(a_true, y_score[ab_mask, a]) + b_true_score = binary_metric(b_true, y_score[ab_mask, b]) + pair_scores[ix] = (a_true_score + b_true_score) / 2 + + return np.average(pair_scores, weights=prevalence) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_classification.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..06503046790beacc11e0a40df39ec9aeb89d0cac --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_classification.py @@ -0,0 +1,3730 @@ +"""Metrics to assess performance on classification task given class prediction. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral, Real + +import numpy as np +from scipy.sparse import coo_matrix, csr_matrix, issparse +from scipy.special import xlogy + +from ..exceptions import UndefinedMetricWarning +from ..preprocessing import LabelBinarizer, LabelEncoder +from ..utils import ( + assert_all_finite, + check_array, + check_consistent_length, + check_scalar, + column_or_1d, +) +from ..utils._array_api import ( + _average, + _bincount, + _count_nonzero, + _find_matching_floating_dtype, + _is_numpy_namespace, + _max_precision_float_dtype, + _searchsorted, + _tolist, + _union1d, + get_namespace, + get_namespace_and_device, + xpx, +) +from ..utils._param_validation import ( + Hidden, + Interval, + Options, + StrOptions, + validate_params, +) +from ..utils._unique import attach_unique +from ..utils.extmath import _nanaverage +from ..utils.multiclass import type_of_target, unique_labels +from ..utils.validation import ( + _check_pos_label_consistency, + _check_sample_weight, + _num_samples, +) + + +def _check_zero_division(zero_division): + if isinstance(zero_division, str) and zero_division == "warn": + return np.float64(0.0) + elif isinstance(zero_division, (int, float)) and zero_division in [0, 1]: + return np.float64(zero_division) + else: # np.isnan(zero_division) + return np.nan + + +def _check_targets(y_true, y_pred): + """Check that y_true and y_pred belong to the same classification task. + + This converts multiclass or binary types to a common shape, and raises a + ValueError for a mix of multilabel and multiclass targets, a mix of + multilabel formats, for the presence of continuous-valued or multioutput + targets, or for targets of different lengths. + + Column vectors are squeezed to 1d, while multilabel formats are returned + as CSR sparse label indicators. + + Parameters + ---------- + y_true : array-like + + y_pred : array-like + + Returns + ------- + type_true : one of {'multilabel-indicator', 'multiclass', 'binary'} + The type of the true target data, as output by + ``utils.multiclass.type_of_target``. + + y_true : array or indicator matrix + + y_pred : array or indicator matrix + """ + xp, _ = get_namespace(y_true, y_pred) + check_consistent_length(y_true, y_pred) + type_true = type_of_target(y_true, input_name="y_true") + type_pred = type_of_target(y_pred, input_name="y_pred") + + y_type = {type_true, type_pred} + if y_type == {"binary", "multiclass"}: + y_type = {"multiclass"} + + if len(y_type) > 1: + raise ValueError( + "Classification metrics can't handle a mix of {0} and {1} targets".format( + type_true, type_pred + ) + ) + + # We can't have more than one value on y_type => The set is no more needed + y_type = y_type.pop() + + # No metrics support "multiclass-multioutput" format + if y_type not in ["binary", "multiclass", "multilabel-indicator"]: + raise ValueError("{0} is not supported".format(y_type)) + + if y_type in ["binary", "multiclass"]: + xp, _ = get_namespace(y_true, y_pred) + y_true = column_or_1d(y_true) + y_pred = column_or_1d(y_pred) + if y_type == "binary": + try: + unique_values = _union1d(y_true, y_pred, xp) + except TypeError as e: + # We expect y_true and y_pred to be of the same data type. + # If `y_true` was provided to the classifier as strings, + # `y_pred` given by the classifier will also be encoded with + # strings. So we raise a meaningful error + raise TypeError( + "Labels in y_true and y_pred should be of the same type. " + f"Got y_true={xp.unique(y_true)} and " + f"y_pred={xp.unique(y_pred)}. Make sure that the " + "predictions provided by the classifier coincides with " + "the true labels." + ) from e + if unique_values.shape[0] > 2: + y_type = "multiclass" + + if y_type.startswith("multilabel"): + if _is_numpy_namespace(xp): + # XXX: do we really want to sparse-encode multilabel indicators when + # they are passed as a dense arrays? This is not possible for array + # API inputs in general hence we only do it for NumPy inputs. But even + # for NumPy the usefulness is questionable. + y_true = csr_matrix(y_true) + y_pred = csr_matrix(y_pred) + y_type = "multilabel-indicator" + + return y_type, y_true, y_pred + + +def _validate_multiclass_probabilistic_prediction( + y_true, y_prob, sample_weight, labels +): + r"""Convert y_true and y_prob to shape (n_samples, n_classes) + + 1. Verify that y_true, y_prob, and sample_weights have the same first dim + 2. Ensure 2 or more classes in y_true i.e. valid classification task. The + classes are provided by the labels argument, or inferred using y_true. + When inferring y_true is assumed binary if it has shape (n_samples, ). + 3. Validate y_true, and y_prob have the same number of classes. Convert to + shape (n_samples, n_classes) + + Parameters + ---------- + y_true : array-like or label indicator matrix + Ground truth (correct) labels for n_samples samples. + + y_prob : array-like of float, shape=(n_samples, n_classes) or (n_samples,) + Predicted probabilities, as returned by a classifier's + predict_proba method. If `y_prob.shape = (n_samples,)` + the probabilities provided are assumed to be that of the + positive class. The labels in `y_prob` are assumed to be + ordered lexicographically, as done by + :class:`preprocessing.LabelBinarizer`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like, default=None + If not provided, labels will be inferred from y_true. If `labels` + is `None` and `y_prob` has shape `(n_samples,)` the labels are + assumed to be binary and are inferred from `y_true`. + + Returns + ------- + transformed_labels : array of shape (n_samples, n_classes) + + y_prob : array of shape (n_samples, n_classes) + """ + y_prob = check_array( + y_prob, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] + ) + + if y_prob.max() > 1: + raise ValueError(f"y_prob contains values greater than 1: {y_prob.max()}") + if y_prob.min() < 0: + raise ValueError(f"y_prob contains values lower than 0: {y_prob.min()}") + + check_consistent_length(y_prob, y_true, sample_weight) + lb = LabelBinarizer() + + if labels is not None: + lb = lb.fit(labels) + # LabelBinarizer does not respect the order implied by labels, which + # can be misleading. + if not np.all(lb.classes_ == labels): + warnings.warn( + f"Labels passed were {labels}. But this function " + "assumes labels are ordered lexicographically. " + f"Pass the ordered labels={lb.classes_.tolist()} and ensure that " + "the columns of y_prob correspond to this ordering.", + UserWarning, + ) + if not np.isin(y_true, labels).all(): + undeclared_labels = set(y_true) - set(labels) + raise ValueError( + f"y_true contains values {undeclared_labels} not belonging " + f"to the passed labels {labels}." + ) + + else: + lb = lb.fit(y_true) + + if len(lb.classes_) == 1: + if labels is None: + raise ValueError( + "y_true contains only one label ({0}). Please " + "provide the list of all expected class labels explicitly through the " + "labels argument.".format(lb.classes_[0]) + ) + else: + raise ValueError( + "The labels array needs to contain at least two " + "labels, got {0}.".format(lb.classes_) + ) + + transformed_labels = lb.transform(y_true) + + if transformed_labels.shape[1] == 1: + transformed_labels = np.append( + 1 - transformed_labels, transformed_labels, axis=1 + ) + + # If y_prob is of single dimension, assume y_true to be binary + # and then check. + if y_prob.ndim == 1: + y_prob = y_prob[:, np.newaxis] + if y_prob.shape[1] == 1: + y_prob = np.append(1 - y_prob, y_prob, axis=1) + + eps = np.finfo(y_prob.dtype).eps + + # Make sure y_prob is normalized + y_prob_sum = y_prob.sum(axis=1) + if not np.allclose(y_prob_sum, 1, rtol=np.sqrt(eps)): + warnings.warn( + "The y_prob values do not sum to one. Make sure to pass probabilities.", + UserWarning, + ) + + # Check if dimensions are consistent. + transformed_labels = check_array(transformed_labels) + if len(lb.classes_) != y_prob.shape[1]: + if labels is None: + raise ValueError( + "y_true and y_prob contain different number of " + "classes: {0} vs {1}. Please provide the true " + "labels explicitly through the labels argument. " + "Classes found in " + "y_true: {2}".format( + transformed_labels.shape[1], y_prob.shape[1], lb.classes_ + ) + ) + else: + raise ValueError( + "The number of classes in labels is different " + "from that in y_prob. Classes found in " + "labels: {0}".format(lb.classes_) + ) + + return transformed_labels, y_prob + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "normalize": ["boolean"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def accuracy_score(y_true, y_pred, *, normalize=True, sample_weight=None): + """Accuracy classification score. + + In multilabel classification, this function computes subset accuracy: + the set of labels predicted for a sample must *exactly* match the + corresponding set of labels in y_true. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, default=True + If ``False``, return the number of correctly classified samples. + Otherwise, return the fraction of correctly classified samples. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float or int + If ``normalize == True``, return the fraction of correctly + classified samples (float), else returns the number of correctly + classified samples (int). + + The best performance is 1 with ``normalize == True`` and the number + of samples with ``normalize == False``. + + See Also + -------- + balanced_accuracy_score : Compute the balanced accuracy to deal with + imbalanced datasets. + jaccard_score : Compute the Jaccard similarity coefficient score. + hamming_loss : Compute the average Hamming loss or Hamming distance between + two sets of samples. + zero_one_loss : Compute the Zero-one classification loss. By default, the + function will return the percentage of imperfectly predicted subsets. + + Examples + -------- + >>> from sklearn.metrics import accuracy_score + >>> y_pred = [0, 2, 1, 3] + >>> y_true = [0, 1, 2, 3] + >>> accuracy_score(y_true, y_pred) + 0.5 + >>> accuracy_score(y_true, y_pred, normalize=False) + 2.0 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> accuracy_score(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight) + # Compute accuracy for each possible representation + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + + if y_type.startswith("multilabel"): + differing_labels = _count_nonzero(y_true - y_pred, xp=xp, device=device, axis=1) + score = xp.asarray(differing_labels == 0, device=device) + else: + score = y_true == y_pred + + return float(_average(score, weights=sample_weight, normalize=normalize)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "labels": ["array-like", None], + "sample_weight": ["array-like", None], + "normalize": [StrOptions({"true", "pred", "all"}), None], + }, + prefer_skip_nested_validation=True, +) +def confusion_matrix( + y_true, y_pred, *, labels=None, sample_weight=None, normalize=None +): + """Compute confusion matrix to evaluate the accuracy of a classification. + + By definition a confusion matrix :math:`C` is such that :math:`C_{i, j}` + is equal to the number of observations known to be in group :math:`i` and + predicted to be in group :math:`j`. + + Thus in binary classification, the count of true negatives is + :math:`C_{0,0}`, false negatives is :math:`C_{1,0}`, true positives is + :math:`C_{1,1}` and false positives is :math:`C_{0,1}`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated targets as returned by a classifier. + + labels : array-like of shape (n_classes), default=None + List of labels to index the matrix. This may be used to reorder + or select a subset of labels. + If ``None`` is given, those that appear at least once + in ``y_true`` or ``y_pred`` are used in sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + normalize : {'true', 'pred', 'all'}, default=None + Normalizes confusion matrix over the true (rows), predicted (columns) + conditions or all the population. If None, confusion matrix will not be + normalized. + + Returns + ------- + C : ndarray of shape (n_classes, n_classes) + Confusion matrix whose i-th row and j-th + column entry indicates the number of + samples with true label being i-th class + and predicted label being j-th class. + + See Also + -------- + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + ConfusionMatrixDisplay : Confusion Matrix visualization. + + References + ---------- + .. [1] `Wikipedia entry for the Confusion matrix + `_ + (Wikipedia and other references may use a different + convention for axes). + + Examples + -------- + >>> from sklearn.metrics import confusion_matrix + >>> y_true = [2, 0, 2, 2, 0, 1] + >>> y_pred = [0, 0, 2, 2, 0, 2] + >>> confusion_matrix(y_true, y_pred) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] + >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] + >>> confusion_matrix(y_true, y_pred, labels=["ant", "bird", "cat"]) + array([[2, 0, 0], + [0, 0, 1], + [1, 0, 2]]) + + In the binary case, we can extract true positives, etc. as follows: + + >>> tn, fp, fn, tp = confusion_matrix([0, 1, 0, 1], [1, 1, 1, 0]).ravel().tolist() + >>> (tn, fp, fn, tp) + (0, 2, 1, 1) + """ + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type not in ("binary", "multiclass"): + raise ValueError("%s is not supported" % y_type) + + if labels is None: + labels = unique_labels(y_true, y_pred) + else: + labels = np.asarray(labels) + n_labels = labels.size + if n_labels == 0: + raise ValueError("'labels' should contains at least one label.") + elif y_true.size == 0: + return np.zeros((n_labels, n_labels), dtype=int) + elif len(np.intersect1d(y_true, labels)) == 0: + raise ValueError("At least one label specified must be in y_true") + + if sample_weight is None: + sample_weight = np.ones(y_true.shape[0], dtype=np.int64) + else: + sample_weight = np.asarray(sample_weight) + + check_consistent_length(y_true, y_pred, sample_weight) + + n_labels = labels.size + # If labels are not consecutive integers starting from zero, then + # y_true and y_pred must be converted into index form + need_index_conversion = not ( + labels.dtype.kind in {"i", "u", "b"} + and np.all(labels == np.arange(n_labels)) + and y_true.min() >= 0 + and y_pred.min() >= 0 + ) + if need_index_conversion: + label_to_ind = {y: x for x, y in enumerate(labels)} + y_pred = np.array([label_to_ind.get(x, n_labels + 1) for x in y_pred]) + y_true = np.array([label_to_ind.get(x, n_labels + 1) for x in y_true]) + + # intersect y_pred, y_true with labels, eliminate items not in labels + ind = np.logical_and(y_pred < n_labels, y_true < n_labels) + if not np.all(ind): + y_pred = y_pred[ind] + y_true = y_true[ind] + # also eliminate weights of eliminated items + sample_weight = sample_weight[ind] + + # Choose the accumulator dtype to always have high precision + if sample_weight.dtype.kind in {"i", "u", "b"}: + dtype = np.int64 + else: + dtype = np.float64 + + cm = coo_matrix( + (sample_weight, (y_true, y_pred)), + shape=(n_labels, n_labels), + dtype=dtype, + ).toarray() + + with np.errstate(all="ignore"): + if normalize == "true": + cm = cm / cm.sum(axis=1, keepdims=True) + elif normalize == "pred": + cm = cm / cm.sum(axis=0, keepdims=True) + elif normalize == "all": + cm = cm / cm.sum() + cm = np.nan_to_num(cm) + + if cm.shape == (1, 1): + warnings.warn( + ( + "A single label was found in 'y_true' and 'y_pred'. For the confusion " + "matrix to have the correct shape, use the 'labels' parameter to pass " + "all known labels." + ), + UserWarning, + ) + + return cm + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "sample_weight": ["array-like", None], + "labels": ["array-like", None], + "samplewise": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def multilabel_confusion_matrix( + y_true, y_pred, *, sample_weight=None, labels=None, samplewise=False +): + """Compute a confusion matrix for each class or sample. + + .. versionadded:: 0.21 + + Compute class-wise (default) or sample-wise (samplewise=True) multilabel + confusion matrix to evaluate the accuracy of a classification, and output + confusion matrices for each class or sample. + + In multilabel confusion matrix :math:`MCM`, the count of true negatives + is :math:`MCM_{:,0,0}`, false negatives is :math:`MCM_{:,1,0}`, + true positives is :math:`MCM_{:,1,1}` and false positives is + :math:`MCM_{:,0,1}`. + + Multiclass data will be treated as if binarized under a one-vs-rest + transformation. Returned confusion matrices will be in the order of + sorted unique labels in the union of (y_true, y_pred). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ + (n_samples,) + Ground truth (correct) target values. + + y_pred : {array-like, sparse matrix} of shape (n_samples, n_outputs) or \ + (n_samples,) + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like of shape (n_classes,), default=None + A list of classes or column indices to select some (or to force + inclusion of classes absent from the data). + + samplewise : bool, default=False + In the multilabel case, this calculates a confusion matrix per sample. + + Returns + ------- + multi_confusion : ndarray of shape (n_outputs, 2, 2) + A 2x2 confusion matrix corresponding to each output in the input. + When calculating class-wise multi_confusion (default), then + n_outputs = n_labels; when calculating sample-wise multi_confusion + (samplewise=True), n_outputs = n_samples. If ``labels`` is defined, + the results will be returned in the order specified in ``labels``, + otherwise the results will be returned in sorted order by default. + + See Also + -------- + confusion_matrix : Compute confusion matrix to evaluate the accuracy of a + classifier. + + Notes + ----- + The `multilabel_confusion_matrix` calculates class-wise or sample-wise + multilabel confusion matrices, and in multiclass tasks, labels are + binarized under a one-vs-rest way; while + :func:`~sklearn.metrics.confusion_matrix` calculates one confusion matrix + for confusion between every two classes. + + Examples + -------- + Multilabel-indicator case: + + >>> import numpy as np + >>> from sklearn.metrics import multilabel_confusion_matrix + >>> y_true = np.array([[1, 0, 1], + ... [0, 1, 0]]) + >>> y_pred = np.array([[1, 0, 0], + ... [0, 1, 1]]) + >>> multilabel_confusion_matrix(y_true, y_pred) + array([[[1, 0], + [0, 1]], + + [[1, 0], + [0, 1]], + + [[0, 1], + [1, 0]]]) + + Multiclass case: + + >>> y_true = ["cat", "ant", "cat", "cat", "ant", "bird"] + >>> y_pred = ["ant", "ant", "cat", "cat", "ant", "cat"] + >>> multilabel_confusion_matrix(y_true, y_pred, + ... labels=["ant", "bird", "cat"]) + array([[[3, 1], + [0, 2]], + + [[5, 0], + [1, 0]], + + [[2, 1], + [1, 2]]]) + """ + y_true, y_pred = attach_unique(y_true, y_pred) + xp, _, device_ = get_namespace_and_device(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight, device=device_) + check_consistent_length(y_true, y_pred, sample_weight) + + if y_type not in ("binary", "multiclass", "multilabel-indicator"): + raise ValueError("%s is not supported" % y_type) + + present_labels = unique_labels(y_true, y_pred) + if labels is None: + labels = present_labels + n_labels = None + else: + labels = xp.asarray(labels, device=device_) + n_labels = labels.shape[0] + labels = xp.concat( + [labels, xpx.setdiff1d(present_labels, labels, assume_unique=True, xp=xp)], + axis=-1, + ) + + if y_true.ndim == 1: + if samplewise: + raise ValueError( + "Samplewise metrics are not available outside of " + "multilabel classification." + ) + + le = LabelEncoder() + le.fit(labels) + y_true = le.transform(y_true) + y_pred = le.transform(y_pred) + sorted_labels = le.classes_ + + # labels are now from 0 to len(labels) - 1 -> use bincount + tp = y_true == y_pred + tp_bins = y_true[tp] + if sample_weight is not None: + tp_bins_weights = sample_weight[tp] + else: + tp_bins_weights = None + + if tp_bins.shape[0]: + tp_sum = _bincount( + tp_bins, weights=tp_bins_weights, minlength=labels.shape[0], xp=xp + ) + else: + # Pathological case + true_sum = pred_sum = tp_sum = xp.zeros(labels.shape[0]) + if y_pred.shape[0]: + pred_sum = _bincount( + y_pred, weights=sample_weight, minlength=labels.shape[0], xp=xp + ) + if y_true.shape[0]: + true_sum = _bincount( + y_true, weights=sample_weight, minlength=labels.shape[0], xp=xp + ) + + # Retain only selected labels + indices = _searchsorted(sorted_labels, labels[:n_labels], xp=xp) + tp_sum = xp.take(tp_sum, indices, axis=0) + true_sum = xp.take(true_sum, indices, axis=0) + pred_sum = xp.take(pred_sum, indices, axis=0) + + else: + sum_axis = 1 if samplewise else 0 + + # All labels are index integers for multilabel. + # Select labels: + if labels.shape != present_labels.shape or xp.any( + xp.not_equal(labels, present_labels) + ): + if xp.max(labels) > xp.max(present_labels): + raise ValueError( + "All labels must be in [0, n labels) for " + "multilabel targets. " + "Got %d > %d" % (xp.max(labels), xp.max(present_labels)) + ) + if xp.min(labels) < 0: + raise ValueError( + "All labels must be in [0, n labels) for " + "multilabel targets. " + "Got %d < 0" % xp.min(labels) + ) + + if n_labels is not None: + y_true = y_true[:, labels[:n_labels]] + y_pred = y_pred[:, labels[:n_labels]] + + if issparse(y_true) or issparse(y_pred): + true_and_pred = y_true.multiply(y_pred) + else: + true_and_pred = xp.multiply(y_true, y_pred) + + # calculate weighted counts + tp_sum = _count_nonzero( + true_and_pred, + axis=sum_axis, + sample_weight=sample_weight, + xp=xp, + device=device_, + ) + pred_sum = _count_nonzero( + y_pred, + axis=sum_axis, + sample_weight=sample_weight, + xp=xp, + device=device_, + ) + true_sum = _count_nonzero( + y_true, + axis=sum_axis, + sample_weight=sample_weight, + xp=xp, + device=device_, + ) + + fp = pred_sum - tp_sum + fn = true_sum - tp_sum + tp = tp_sum + + if sample_weight is not None and samplewise: + tp = xp.asarray(tp) + fp = xp.asarray(fp) + fn = xp.asarray(fn) + tn = sample_weight * y_true.shape[1] - tp - fp - fn + elif sample_weight is not None: + tn = xp.sum(sample_weight) - tp - fp - fn + elif samplewise: + tn = y_true.shape[1] - tp - fp - fn + else: + tn = y_true.shape[0] - tp - fp - fn + + return xp.reshape(xp.stack([tn, fp, fn, tp]).T, (-1, 2, 2)) + + +@validate_params( + { + "y1": ["array-like"], + "y2": ["array-like"], + "labels": ["array-like", None], + "weights": [StrOptions({"linear", "quadratic"}), None], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def cohen_kappa_score(y1, y2, *, labels=None, weights=None, sample_weight=None): + r"""Compute Cohen's kappa: a statistic that measures inter-annotator agreement. + + This function computes Cohen's kappa [1]_, a score that expresses the level + of agreement between two annotators on a classification problem. It is + defined as + + .. math:: + \kappa = (p_o - p_e) / (1 - p_e) + + where :math:`p_o` is the empirical probability of agreement on the label + assigned to any sample (the observed agreement ratio), and :math:`p_e` is + the expected agreement when both annotators assign labels randomly. + :math:`p_e` is estimated using a per-annotator empirical prior over the + class labels [2]_. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y1 : array-like of shape (n_samples,) + Labels assigned by the first annotator. + + y2 : array-like of shape (n_samples,) + Labels assigned by the second annotator. The kappa statistic is + symmetric, so swapping ``y1`` and ``y2`` doesn't change the value. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the matrix. This may be used to select a + subset of labels. If `None`, all labels that appear at least once in + ``y1`` or ``y2`` are used. Note that at least one label in `labels` must be + present in `y1`, even though this function is otherwise agnostic to the order + of `y1` and `y2`. + + weights : {'linear', 'quadratic'}, default=None + Weighting type to calculate the score. `None` means not weighted; + "linear" means linear weighting; "quadratic" means quadratic weighting. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + kappa : float + The kappa statistic, which is a number between -1 and 1. The maximum + value means complete agreement; zero or lower means chance agreement. + + References + ---------- + .. [1] :doi:`J. Cohen (1960). "A coefficient of agreement for nominal scales". + Educational and Psychological Measurement 20(1):37-46. + <10.1177/001316446002000104>` + .. [2] `R. Artstein and M. Poesio (2008). "Inter-coder agreement for + computational linguistics". Computational Linguistics 34(4):555-596 + `_. + .. [3] `Wikipedia entry for the Cohen's kappa + `_. + + Examples + -------- + >>> from sklearn.metrics import cohen_kappa_score + >>> y1 = ["negative", "positive", "negative", "neutral", "positive"] + >>> y2 = ["negative", "positive", "negative", "neutral", "negative"] + >>> cohen_kappa_score(y1, y2) + 0.6875 + """ + try: + confusion = confusion_matrix(y1, y2, labels=labels, sample_weight=sample_weight) + except ValueError as e: + if "At least one label specified must be in y_true" in str(e): + msg = ( + "At least one label in `labels` must be present in `y1` (even though " + "`cohen_kappa_score` is otherwise agnostic to the order of `y1` and " + "`y2`)." + ) + raise ValueError(msg) from e + raise + + n_classes = confusion.shape[0] + sum0 = np.sum(confusion, axis=0) + sum1 = np.sum(confusion, axis=1) + expected = np.outer(sum0, sum1) / np.sum(sum0) + + if weights is None: + w_mat = np.ones([n_classes, n_classes], dtype=int) + w_mat.flat[:: n_classes + 1] = 0 + else: # "linear" or "quadratic" + w_mat = np.zeros([n_classes, n_classes], dtype=int) + w_mat += np.arange(n_classes) + if weights == "linear": + w_mat = np.abs(w_mat - w_mat.T) + else: + w_mat = (w_mat - w_mat.T) ** 2 + + k = np.sum(w_mat * confusion) / np.sum(w_mat * expected) + return float(1 - k) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0, 1}), + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def jaccard_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Jaccard similarity coefficient score. + + The Jaccard index [1], or Jaccard similarity coefficient, defined as + the size of the intersection divided by the size of the union of two label + sets, is used to compare set of predicted labels for a sample to the + corresponding set of labels in ``y_true``. + + Support beyond term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return the + Jaccard similarity coefficient for `pos_label`. If `average` is not `'binary'`, + `pos_label` is ignored and scores for both classes are computed, then averaged or + both returned (when `average=None`). Similarly, for :term:`multiclass` and + :term:`multilabel` targets, scores for all `labels` are either returned or + averaged depending on the `average` parameter. Use `labels` specify the set of + labels to calculate the score for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + labels : array-like of shape (n_classes,), default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', \ + 'binary'} or None, default='binary' + If ``None``, the scores for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : "warn", {0.0, 1.0}, default="warn" + Sets the value to return when there is a zero division, i.e. when there + there are no negative values in predictions and labels. If set to + "warn", this acts like 0, but a warning is also raised. + + .. versionadded:: 0.24 + + Returns + ------- + score : float or ndarray of shape (n_unique_labels,), dtype=np.float64 + The Jaccard score. When `average` is not `None`, a single scalar is + returned. + + See Also + -------- + accuracy_score : Function for calculating the accuracy score. + f1_score : Function for calculating the F1 score. + multilabel_confusion_matrix : Function for computing a confusion matrix\ + for each class or sample. + + Notes + ----- + :func:`jaccard_score` may be a poor metric if there are no + positives for some samples or classes. Jaccard is undefined if there are + no true or predicted labels, and our implementation will return a score + of 0 with a warning. + + References + ---------- + .. [1] `Wikipedia entry for the Jaccard index + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import jaccard_score + >>> y_true = np.array([[0, 1, 1], + ... [1, 1, 0]]) + >>> y_pred = np.array([[1, 1, 1], + ... [1, 0, 0]]) + + In the binary case: + + >>> jaccard_score(y_true[0], y_pred[0]) + 0.6666 + + In the 2D comparison case (e.g. image similarity): + + >>> jaccard_score(y_true, y_pred, average="micro") + 0.6 + + In the multilabel case: + + >>> jaccard_score(y_true, y_pred, average='samples') + 0.5833 + >>> jaccard_score(y_true, y_pred, average='macro') + 0.6666 + >>> jaccard_score(y_true, y_pred, average=None) + array([0.5, 0.5, 1. ]) + + In the multiclass case: + + >>> y_pred = [0, 2, 1, 2] + >>> y_true = [0, 1, 2, 2] + >>> jaccard_score(y_true, y_pred, average=None) + array([1. , 0. , 0.33]) + """ + labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) + samplewise = average == "samples" + MCM = multilabel_confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + samplewise=samplewise, + ) + numerator = MCM[:, 1, 1] + denominator = MCM[:, 1, 1] + MCM[:, 0, 1] + MCM[:, 1, 0] + + xp, _, device_ = get_namespace_and_device(y_true, y_pred) + if average == "micro": + numerator = xp.asarray(xp.sum(numerator, keepdims=True), device=device_) + denominator = xp.asarray(xp.sum(denominator, keepdims=True), device=device_) + + jaccard = _prf_divide( + numerator, + denominator, + "jaccard", + "true or predicted", + average, + ("jaccard",), + zero_division=zero_division, + ) + if average is None: + return jaccard + if average == "weighted": + weights = MCM[:, 1, 0] + MCM[:, 1, 1] + if not xp.any(weights): + # numerator is 0, and warning should have already been issued + weights = None + elif average == "samples" and sample_weight is not None: + weights = sample_weight + else: + weights = None + return float(_average(jaccard, weights=weights, xp=xp)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def matthews_corrcoef(y_true, y_pred, *, sample_weight=None): + """Compute the Matthews correlation coefficient (MCC). + + The Matthews correlation coefficient is used in machine learning as a + measure of the quality of binary and multiclass classifications. It takes + into account true and false positives and negatives and is generally + regarded as a balanced measure which can be used even if the classes are of + very different sizes. The MCC is in essence a correlation coefficient value + between -1 and +1. A coefficient of +1 represents a perfect prediction, 0 + an average random prediction and -1 an inverse prediction. The statistic + is also known as the phi coefficient. [source: Wikipedia] + + Binary and multiclass labels are supported. Only in the binary case does + this relate to information about true and false positives and negatives. + See references below. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + Returns + ------- + mcc : float + The Matthews correlation coefficient (+1 represents a perfect + prediction, 0 an average random prediction and -1 and inverse + prediction). + + References + ---------- + .. [1] :doi:`Baldi, Brunak, Chauvin, Andersen and Nielsen, (2000). Assessing the + accuracy of prediction algorithms for classification: an overview. + <10.1093/bioinformatics/16.5.412>` + + .. [2] `Wikipedia entry for the Matthews Correlation Coefficient (phi coefficient) + `_. + + .. [3] `Gorodkin, (2004). Comparing two K-category assignments by a + K-category correlation coefficient + `_. + + .. [4] `Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC and CEN + Error Measures in MultiClass Prediction + `_. + + Examples + -------- + >>> from sklearn.metrics import matthews_corrcoef + >>> y_true = [+1, +1, +1, -1] + >>> y_pred = [+1, -1, +1, +1] + >>> matthews_corrcoef(y_true, y_pred) + -0.33 + """ + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + if y_type not in {"binary", "multiclass"}: + raise ValueError("%s is not supported" % y_type) + + lb = LabelEncoder() + lb.fit(np.hstack([y_true, y_pred])) + y_true = lb.transform(y_true) + y_pred = lb.transform(y_pred) + + C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) + t_sum = C.sum(axis=1, dtype=np.float64) + p_sum = C.sum(axis=0, dtype=np.float64) + n_correct = np.trace(C, dtype=np.float64) + n_samples = p_sum.sum() + cov_ytyp = n_correct * n_samples - np.dot(t_sum, p_sum) + cov_ypyp = n_samples**2 - np.dot(p_sum, p_sum) + cov_ytyt = n_samples**2 - np.dot(t_sum, t_sum) + + cov_ypyp_ytyt = cov_ypyp * cov_ytyt + if cov_ypyp_ytyt == 0: + return 0.0 + else: + return float(cov_ytyp / np.sqrt(cov_ypyp_ytyt)) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "normalize": ["boolean"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def zero_one_loss(y_true, y_pred, *, normalize=True, sample_weight=None): + """Zero-one classification loss. + + If normalize is ``True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). The best + performance is 0. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + normalize : bool, default=True + If ``False``, return the number of misclassifications. + Otherwise, return the fraction of misclassifications. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float or int, + If ``normalize == True``, return the fraction of misclassifications + (float), else it returns the number of misclassifications (int). + + See Also + -------- + accuracy_score : Compute the accuracy score. By default, the function will + return the fraction of correct predictions divided by the total number + of predictions. + hamming_loss : Compute the average Hamming loss or Hamming distance between + two sets of samples. + jaccard_score : Compute the Jaccard similarity coefficient score. + + Notes + ----- + In multilabel classification, the zero_one_loss function corresponds to + the subset zero-one loss: for each sample, the entire set of labels must be + correctly predicted, otherwise the loss for that sample is equal to one. + + Examples + -------- + >>> from sklearn.metrics import zero_one_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> zero_one_loss(y_true, y_pred) + 0.25 + >>> zero_one_loss(y_true, y_pred, normalize=False) + 1.0 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> zero_one_loss(np.array([[0, 1], [1, 1]]), np.ones((2, 2))) + 0.5 + """ + xp, _ = get_namespace(y_true, y_pred) + score = accuracy_score( + y_true, y_pred, normalize=normalize, sample_weight=sample_weight + ) + + if normalize: + return 1 - score + else: + if sample_weight is not None: + n_samples = xp.sum(sample_weight) + else: + n_samples = _num_samples(y_true) + return n_samples - score + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def f1_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the F1 score, also known as balanced F-score or F-measure. + + The F1 score can be interpreted as a harmonic mean of the precision and + recall, where an F1 score reaches its best value at 1 and worst score at 0. + The relative contribution of precision and recall to the F1 score are + equal. The formula for the F1 score is: + + .. math:: + \\text{F1} = \\frac{2 * \\text{TP}}{2 * \\text{TP} + \\text{FP} + \\text{FN}} + + Where :math:`\\text{TP}` is the number of true positives, :math:`\\text{FN}` is the + number of false negatives, and :math:`\\text{FP}` is the number of false positives. + F1 is by default + calculated as 0.0 when there are no true positives, false negatives, or + false positives. + + Support beyond :term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return + F1 score for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored + and F1 score for both classes are computed, then averaged or both returned (when + `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, + F1 score for all `labels` are either returned or averaged depending on the + `average` parameter. Use `labels` specify the set of labels to calculate F1 score + for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the metrics for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division, i.e. when all + predictions and labels are negative. + + Notes: + - If set to "warn", this acts like 0, but a warning is also raised. + - If set to `np.nan`, such values will be excluded from the average. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + f1_score : float or array of float, shape = [n_unique_labels] + F1 score of the positive class in binary classification or weighted + average of the F1 scores of each class for the multiclass task. + + See Also + -------- + fbeta_score : Compute the F-beta score. + precision_recall_fscore_support : Compute the precision, recall, F-score, + and support. + jaccard_score : Compute the Jaccard similarity coefficient score. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive + false negative == 0`` (i.e. a class + is completely absent from both ``y_true`` or ``y_pred``), f-score is + undefined. In such cases, by default f-score will be set to 0.0, and + ``UndefinedMetricWarning`` will be raised. This behavior can be modified by + setting the ``zero_division`` parameter. + + References + ---------- + .. [1] `Wikipedia entry for the F1-score + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import f1_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> f1_score(y_true, y_pred, average='macro') + 0.267 + >>> f1_score(y_true, y_pred, average='micro') + 0.33 + >>> f1_score(y_true, y_pred, average='weighted') + 0.267 + >>> f1_score(y_true, y_pred, average=None) + array([0.8, 0. , 0. ]) + + >>> # binary classification + >>> y_true_empty = [0, 0, 0, 0, 0, 0] + >>> y_pred_empty = [0, 0, 0, 0, 0, 0] + >>> f1_score(y_true_empty, y_pred_empty) + 0.0... + >>> f1_score(y_true_empty, y_pred_empty, zero_division=1.0) + 1.0... + >>> f1_score(y_true_empty, y_pred_empty, zero_division=np.nan) + nan... + + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> f1_score(y_true, y_pred, average=None) + array([0.66666667, 1. , 0.66666667]) + """ + return fbeta_score( + y_true, + y_pred, + beta=1, + labels=labels, + pos_label=pos_label, + average=average, + sample_weight=sample_weight, + zero_division=zero_division, + ) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "beta": [Interval(Real, 0.0, None, closed="both")], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def fbeta_score( + y_true, + y_pred, + *, + beta, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the F-beta score. + + The F-beta score is the weighted harmonic mean of precision and recall, + reaching its optimal value at 1 and its worst value at 0. + + The `beta` parameter represents the ratio of recall importance to + precision importance. `beta > 1` gives more weight to recall, while + `beta < 1` favors precision. For example, `beta = 2` makes recall twice + as important as precision, while `beta = 0.5` does the opposite. + Asymptotically, `beta -> +inf` considers only recall, and `beta -> 0` + only precision. + + The formula for F-beta score is: + + .. math:: + + F_\\beta = \\frac{(1 + \\beta^2) \\text{tp}} + {(1 + \\beta^2) \\text{tp} + \\text{fp} + \\beta^2 \\text{fn}} + + Where :math:`\\text{tp}` is the number of true positives, :math:`\\text{fp}` is the + number of false positives, and :math:`\\text{fn}` is the number of false negatives. + + Support beyond term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return + F-beta score for `pos_label`. If `average` is not `'binary'`, `pos_label` is + ignored and F-beta score for both classes are computed, then averaged or both + returned (when `average=None`). Similarly, for :term:`multiclass` and + :term:`multilabel` targets, F-beta score for all `labels` are either returned or + averaged depending on the `average` parameter. Use `labels` specify the set of + labels to calculate F-beta score for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta : float + Determines the weight of recall in the combined score. + + labels : array-like, default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the metrics for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division, i.e. when all + predictions and labels are negative. + + Notes: + + - If set to "warn", this acts like 0, but a warning is also raised. + - If set to `np.nan`, such values will be excluded from the average. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + fbeta_score : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + F-beta score of the positive class in binary classification or weighted + average of the F-beta score of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute the precision, recall, F-score, + and support. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive + false negative == 0``, f-score + returns 0.0 and raises ``UndefinedMetricWarning``. This behavior can be + modified by setting ``zero_division``. + + F-beta score is not implemented as a named scorer that can be passed to + the `scoring` parameter of cross-validation tools directly: it requires to be + wrapped with :func:`make_scorer` so as to specify the value of `beta`. See + examples for details. + + References + ---------- + .. [1] R. Baeza-Yates and B. Ribeiro-Neto (2011). + Modern Information Retrieval. Addison Wesley, pp. 327-328. + + .. [2] `Wikipedia entry for the F1-score + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import fbeta_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> fbeta_score(y_true, y_pred, average='macro', beta=0.5) + 0.238 + >>> fbeta_score(y_true, y_pred, average='micro', beta=0.5) + 0.33 + >>> fbeta_score(y_true, y_pred, average='weighted', beta=0.5) + 0.238 + >>> fbeta_score(y_true, y_pred, average=None, beta=0.5) + array([0.71, 0. , 0. ]) + >>> y_pred_empty = [0, 0, 0, 0, 0, 0] + >>> fbeta_score( + ... y_true, + ... y_pred_empty, + ... average="macro", + ... zero_division=np.nan, + ... beta=0.5, + ... ) + 0.128 + + In order to use :func:`fbeta_scorer` as a scorer, a callable + scorer objects needs to be created first with :func:`make_scorer`, + passing the value for the `beta` parameter. + + >>> from sklearn.metrics import fbeta_score, make_scorer + >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) + >>> from sklearn.model_selection import GridSearchCV + >>> from sklearn.svm import LinearSVC + >>> grid = GridSearchCV( + ... LinearSVC(dual="auto"), + ... param_grid={'C': [1, 10]}, + ... scoring=ftwo_scorer, + ... cv=5 + ... ) + """ + + _, _, f, _ = precision_recall_fscore_support( + y_true, + y_pred, + beta=beta, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("f-score",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return f + + +def _prf_divide( + numerator, denominator, metric, modifier, average, warn_for, zero_division="warn" +): + """Performs division and handles divide-by-zero. + + On zero-division, sets the corresponding result elements equal to + 0, 1 or np.nan (according to ``zero_division``). Plus, if + ``zero_division != "warn"`` raises a warning. + + The metric, modifier and average arguments are used only for determining + an appropriate warning. + """ + xp, _ = get_namespace(numerator, denominator) + dtype_float = _find_matching_floating_dtype(numerator, denominator, xp=xp) + mask = denominator == 0 + denominator = xp.asarray(denominator, copy=True, dtype=dtype_float) + denominator[mask] = 1 # avoid infs/nans + result = xp.asarray(numerator, dtype=dtype_float) / denominator + + if not xp.any(mask): + return result + + # set those with 0 denominator to `zero_division`, and 0 when "warn" + zero_division_value = _check_zero_division(zero_division) + result[mask] = zero_division_value + + # we assume the user will be removing warnings if zero_division is set + # to something different than "warn". If we are computing only f-score + # the warning will be raised only if precision and recall are ill-defined + if zero_division != "warn" or metric not in warn_for: + return result + + # build appropriate warning + if metric in warn_for: + _warn_prf(average, modifier, f"{metric.capitalize()} is", result.shape[0]) + + return result + + +def _warn_prf(average, modifier, msg_start, result_size): + axis0, axis1 = "sample", "label" + if average == "samples": + axis0, axis1 = axis1, axis0 + msg = ( + "{0} ill-defined and being set to 0.0 {{0}} " + "no {1} {2}s. Use `zero_division` parameter to control" + " this behavior.".format(msg_start, modifier, axis0) + ) + if result_size == 1: + msg = msg.format("due to") + else: + msg = msg.format("in {0}s with".format(axis1)) + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + + +def _check_set_wise_labels(y_true, y_pred, average, labels, pos_label): + """Validation associated with set-wise metrics. + + Returns identified labels. + """ + average_options = (None, "micro", "macro", "weighted", "samples") + if average not in average_options and average != "binary": + raise ValueError("average has to be one of " + str(average_options)) + + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + # Convert to Python primitive type to avoid NumPy type / Python str + # comparison. See https://github.com/numpy/numpy/issues/6784 + present_labels = _tolist(unique_labels(y_true, y_pred)) + if average == "binary": + if y_type == "binary": + if pos_label not in present_labels: + if len(present_labels) >= 2: + raise ValueError( + f"pos_label={pos_label} is not a valid label. It " + f"should be one of {present_labels}" + ) + labels = [pos_label] + else: + average_options = list(average_options) + if y_type == "multiclass": + average_options.remove("samples") + raise ValueError( + "Target is %s but average='binary'. Please " + "choose another average setting, one of %r." % (y_type, average_options) + ) + elif pos_label not in (None, 1): + warnings.warn( + "Note that pos_label (set to %r) is ignored when " + "average != 'binary' (got %r). You may use " + "labels=[pos_label] to specify a single positive class." + % (pos_label, average), + UserWarning, + ) + return labels + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "beta": [Interval(Real, 0.0, None, closed="both")], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "warn_for": [list, tuple, set], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def precision_recall_fscore_support( + y_true, + y_pred, + *, + beta=1.0, + labels=None, + pos_label=1, + average=None, + warn_for=("precision", "recall", "f-score"), + sample_weight=None, + zero_division="warn", +): + """Compute precision, recall, F-measure and support for each class. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label a negative sample as + positive. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The F-beta score can be interpreted as a weighted harmonic mean of + the precision and recall, where an F-beta score reaches its best + value at 1 and worst score at 0. + + The F-beta score weights recall more than precision by a factor of + ``beta``. ``beta == 1.0`` means recall and precision are equally important. + + The support is the number of occurrences of each class in ``y_true``. + + Support beyond term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return + metrics for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored + and metrics for both classes are computed, then averaged or both returned (when + `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, + metrics for all `labels` are either returned or averaged depending on the `average` + parameter. Use `labels` specify the set of labels to calculate metrics for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + beta : float, default=1.0 + The strength of recall versus precision in the F-score. + + labels : array-like, default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the metrics for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + warn_for : list, tuple or set, for internal use + This determines which warnings will be made in the case that this + function is being used to return only one of its metrics. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division: + + - recall: when there are no positive labels + - precision: when there are no positive predictions + - f-score: both + + Notes: + + - If set to "warn", this acts like 0, but a warning is also raised. + - If set to `np.nan`, such values will be excluded from the average. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + precision : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Precision score. + + recall : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + Recall score. + + fbeta_score : float (if average is not None) or array of float, shape =\ + [n_unique_labels] + F-beta score. + + support : None (if average is not None) or array of int, shape =\ + [n_unique_labels] + The number of occurrences of each label in ``y_true``. + + Notes + ----- + When ``true positive + false positive == 0``, precision is undefined. + When ``true positive + false negative == 0``, recall is undefined. When + ``true positive + false negative + false positive == 0``, f-score is + undefined. In such cases, by default the metric will be set to 0, and + ``UndefinedMetricWarning`` will be raised. This behavior can be modified + with ``zero_division``. + + References + ---------- + .. [1] `Wikipedia entry for the Precision and recall + `_. + + .. [2] `Wikipedia entry for the F1-score + `_. + + .. [3] `Discriminative Methods for Multi-labeled Classification Advances + in Knowledge Discovery and Data Mining (2004), pp. 22-30 by Shantanu + Godbole, Sunita Sarawagi + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_fscore_support + >>> y_true = np.array(['cat', 'dog', 'pig', 'cat', 'dog', 'pig']) + >>> y_pred = np.array(['cat', 'pig', 'dog', 'cat', 'cat', 'dog']) + >>> precision_recall_fscore_support(y_true, y_pred, average='macro') + (0.222, 0.333, 0.267, None) + >>> precision_recall_fscore_support(y_true, y_pred, average='micro') + (0.33, 0.33, 0.33, None) + >>> precision_recall_fscore_support(y_true, y_pred, average='weighted') + (0.222, 0.333, 0.267, None) + + It is possible to compute per-label precisions, recalls, F1-scores and + supports instead of averaging: + + >>> precision_recall_fscore_support(y_true, y_pred, average=None, + ... labels=['pig', 'dog', 'cat']) + (array([0. , 0. , 0.66]), + array([0., 0., 1.]), array([0. , 0. , 0.8]), + array([2, 2, 2])) + """ + _check_zero_division(zero_division) + labels = _check_set_wise_labels(y_true, y_pred, average, labels, pos_label) + + # Calculate tp_sum, pred_sum, true_sum ### + samplewise = average == "samples" + MCM = multilabel_confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + samplewise=samplewise, + ) + tp_sum = MCM[:, 1, 1] + pred_sum = tp_sum + MCM[:, 0, 1] + true_sum = tp_sum + MCM[:, 1, 0] + + xp, _, device_ = get_namespace_and_device(y_true, y_pred) + if average == "micro": + tp_sum = xp.reshape(xp.sum(tp_sum), (1,)) + pred_sum = xp.reshape(xp.sum(pred_sum), (1,)) + true_sum = xp.reshape(xp.sum(true_sum), (1,)) + + # Finally, we have all our sufficient statistics. Divide! # + beta2 = beta**2 + + # Divide, and on zero-division, set scores and/or warn according to + # zero_division: + precision = _prf_divide( + tp_sum, pred_sum, "precision", "predicted", average, warn_for, zero_division + ) + recall = _prf_divide( + tp_sum, true_sum, "recall", "true", average, warn_for, zero_division + ) + + if np.isposinf(beta): + f_score = recall + elif beta == 0: + f_score = precision + else: + # The score is defined as: + # score = (1 + beta**2) * precision * recall / (beta**2 * precision + recall) + # Therefore, we can express the score in terms of confusion matrix entries as: + # score = (1 + beta**2) * tp / ((1 + beta**2) * tp + beta**2 * fn + fp) + + # Array api strict requires all arrays to be of the same type so we + # need to convert true_sum, pred_sum and tp_sum to the max supported + # float dtype because beta2 is a float + max_float_type = _max_precision_float_dtype(xp=xp, device=device_) + denom = beta2 * xp.astype(true_sum, max_float_type) + xp.astype( + pred_sum, max_float_type + ) + f_score = _prf_divide( + (1 + beta2) * xp.astype(tp_sum, max_float_type), + denom, + "f-score", + "true nor predicted", + average, + warn_for, + zero_division, + ) + + # Average the results + if average == "weighted": + weights = true_sum + elif average == "samples": + weights = sample_weight + else: + weights = None + + if average is not None: + precision = float(_nanaverage(precision, weights=weights)) + recall = float(_nanaverage(recall, weights=weights)) + f_score = float(_nanaverage(f_score, weights=weights)) + true_sum = None # return no support + + return precision, recall, f_score, true_sum + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "sample_weight": ["array-like", None], + "raise_warning": ["boolean", Hidden(StrOptions({"deprecated"}))], + "replace_undefined_by": [ + Options(Real, {1.0, np.nan}), + dict, + ], + }, + prefer_skip_nested_validation=True, +) +def class_likelihood_ratios( + y_true, + y_pred, + *, + labels=None, + sample_weight=None, + raise_warning="deprecated", + replace_undefined_by=np.nan, +): + """Compute binary classification positive and negative likelihood ratios. + + The positive likelihood ratio is `LR+ = sensitivity / (1 - specificity)` + where the sensitivity or recall is the ratio `tp / (tp + fn)` and the + specificity is `tn / (tn + fp)`. The negative likelihood ratio is `LR- = (1 + - sensitivity) / specificity`. Here `tp` is the number of true positives, + `fp` the number of false positives, `tn` is the number of true negatives and + `fn` the number of false negatives. Both class likelihood ratios can be used + to obtain post-test probabilities given a pre-test probability. + + `LR+` ranges from 1.0 to infinity. A `LR+` of 1.0 indicates that the probability + of predicting the positive class is the same for samples belonging to either + class; therefore, the test is useless. The greater `LR+` is, the more a + positive prediction is likely to be a true positive when compared with the + pre-test probability. A value of `LR+` lower than 1.0 is invalid as it would + indicate that the odds of a sample being a true positive decrease with + respect to the pre-test odds. + + `LR-` ranges from 0.0 to 1.0. The closer it is to 0.0, the lower the probability + of a given sample to be a false negative. A `LR-` of 1.0 means the test is + useless because the odds of having the condition did not change after the + test. A value of `LR-` greater than 1.0 invalidates the classifier as it + indicates an increase in the odds of a sample belonging to the positive + class after being classified as negative. This is the case when the + classifier systematically predicts the opposite of the true label. + + A typical application in medicine is to identify the positive/negative class + to the presence/absence of a disease, respectively; the classifier being a + diagnostic test; the pre-test probability of an individual having the + disease can be the prevalence of such disease (proportion of a particular + population found to be affected by a medical condition); and the post-test + probabilities would be the probability that the condition is truly present + given a positive test result. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + List of labels to index the matrix. This may be used to select the + positive and negative classes with the ordering `labels=[negative_class, + positive_class]`. If `None` is given, those that appear at least once in + `y_true` or `y_pred` are used in sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + raise_warning : bool, default=True + Whether or not a case-specific warning message is raised when there is division + by zero. + + .. deprecated:: 1.7 + `raise_warning` was deprecated in version 1.7 and will be removed in 1.9, + when an :class:`~sklearn.exceptions.UndefinedMetricWarning` will always + raise in case of a division by zero. + + replace_undefined_by : np.nan, 1.0, or dict, default=np.nan + Sets the return values for LR+ and LR- when there is a division by zero. Can + take the following values: + + - `np.nan` to return `np.nan` for both `LR+` and `LR-` + - `1.0` to return the worst possible scores: `{"LR+": 1.0, "LR-": 1.0}` + - a dict in the format `{"LR+": value_1, "LR-": value_2}` where the values can + be non-negative floats, `np.inf` or `np.nan` in the range of the + likelihood ratios. For example, `{"LR+": 1.0, "LR-": 1.0}` can be used for + returning the worst scores, indicating a useless model, and `{"LR+": np.inf, + "LR-": 0.0}` can be used for returning the best scores, indicating a useful + model. + + If a division by zero occurs, only the affected metric is replaced with the set + value; the other metric is calculated as usual. + + .. versionadded:: 1.7 + + Returns + ------- + (positive_likelihood_ratio, negative_likelihood_ratio) : tuple + A tuple of two floats, the first containing the positive likelihood ratio (LR+) + and the second the negative likelihood ratio (LR-). + + Warns + ----- + Raises :class:`~sklearn.exceptions.UndefinedMetricWarning` when `y_true` and + `y_pred` lead to the following conditions: + + - The number of false positives is 0 and `raise_warning` is set to `True` + (default): positive likelihood ratio is undefined. + - The number of true negatives is 0 and `raise_warning` is set to `True` + (default): negative likelihood ratio is undefined. + - The sum of true positives and false negatives is 0 (no samples of the positive + class are present in `y_true`): both likelihood ratios are undefined. + + For the first two cases, an undefined metric can be defined by setting the + `replace_undefined_by` param. + + References + ---------- + .. [1] `Wikipedia entry for the Likelihood ratios in diagnostic testing + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import class_likelihood_ratios + >>> class_likelihood_ratios([0, 1, 0, 1, 0], [1, 1, 0, 0, 0]) + (1.5, 0.75) + >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) + >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) + >>> class_likelihood_ratios(y_true, y_pred) + (1.33, 0.66) + >>> y_true = np.array(["non-zebra", "zebra", "non-zebra", "zebra", "non-zebra"]) + >>> y_pred = np.array(["zebra", "zebra", "non-zebra", "non-zebra", "non-zebra"]) + >>> class_likelihood_ratios(y_true, y_pred) + (1.5, 0.75) + + To avoid ambiguities, use the notation `labels=[negative_class, + positive_class]` + + >>> y_true = np.array(["non-cat", "cat", "non-cat", "cat", "non-cat"]) + >>> y_pred = np.array(["cat", "cat", "non-cat", "non-cat", "non-cat"]) + >>> class_likelihood_ratios(y_true, y_pred, labels=["non-cat", "cat"]) + (1.5, 0.75) + """ + # TODO(1.9): When `raise_warning` is removed, the following changes need to be made: + # The checks for `raise_warning==True` need to be removed and we will always warn, + # remove `FutureWarning`, and the Warns section in the docstring should not mention + # `raise_warning` anymore. + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + if y_type != "binary": + raise ValueError( + "class_likelihood_ratios only supports binary classification " + f"problems, got targets of type: {y_type}" + ) + + msg_deprecated_param = ( + "`raise_warning` was deprecated in version 1.7 and will be removed in 1.9. An " + "`UndefinedMetricWarning` will always be raised in case of a division by zero " + "and the value set with the `replace_undefined_by` param will be returned." + ) + if raise_warning != "deprecated": + warnings.warn(msg_deprecated_param, FutureWarning) + else: + raise_warning = True + + if replace_undefined_by == 1.0: + replace_undefined_by = {"LR+": 1.0, "LR-": 1.0} + + if isinstance(replace_undefined_by, dict): + msg = ( + "The dictionary passed as `replace_undefined_by` needs to be in the form " + "`{'LR+': `value_1`, 'LR-': `value_2`}` where the value for `LR+` ranges " + "from `1.0` to `np.inf` or is `np.nan` and the value for `LR-` ranges from " + f"`0.0` to `1.0` or is `np.nan`; got `{replace_undefined_by}`." + ) + if ("LR+" in replace_undefined_by) and ("LR-" in replace_undefined_by): + try: + desired_lr_pos = replace_undefined_by.get("LR+", None) + check_scalar( + desired_lr_pos, + "positive_likelihood_ratio", + target_type=(Real), + min_val=1.0, + include_boundaries="left", + ) + desired_lr_neg = replace_undefined_by.get("LR-", None) + check_scalar( + desired_lr_neg, + "negative_likelihood_ratio", + target_type=(Real), + min_val=0.0, + max_val=1.0, + include_boundaries="both", + ) + except Exception as e: + raise ValueError(msg) from e + else: + raise ValueError(msg) + + cm = confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + ) + + tn, fp, fn, tp = cm.ravel() + support_pos = tp + fn + support_neg = tn + fp + pos_num = tp * support_neg + pos_denom = fp * support_pos + neg_num = fn * support_neg + neg_denom = tn * support_pos + + # if `support_pos == 0`a division by zero will occur + if support_pos == 0: + msg = ( + "No samples of the positive class are present in `y_true`. " + "`positive_likelihood_ratio` and `negative_likelihood_ratio` are both set " + "to `np.nan`. Use the `replace_undefined_by` param to control this " + "behavior. To suppress this warning or turn it into an error, see Python's " + "`warnings` module and `warnings.catch_warnings()`." + ) + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + positive_likelihood_ratio = np.nan + negative_likelihood_ratio = np.nan + + # if `fp == 0`a division by zero will occur + if fp == 0: + if raise_warning: + if tp == 0: + msg_beginning = ( + "No samples were predicted for the positive class and " + "`positive_likelihood_ratio` is " + ) + else: + msg_beginning = "`positive_likelihood_ratio` is ill-defined and " + msg_end = "set to `np.nan`. Use the `replace_undefined_by` param to " + "control this behavior. To suppress this warning or turn it into an error, " + "see Python's `warnings` module and `warnings.catch_warnings()`." + warnings.warn(msg_beginning + msg_end, UndefinedMetricWarning, stacklevel=2) + if isinstance(replace_undefined_by, float) and np.isnan(replace_undefined_by): + positive_likelihood_ratio = replace_undefined_by + else: + # replace_undefined_by is a dict and + # isinstance(replace_undefined_by.get("LR+", None), Real); this includes + # `np.inf` and `np.nan` + positive_likelihood_ratio = desired_lr_pos + else: + positive_likelihood_ratio = pos_num / pos_denom + + # if `tn == 0`a division by zero will occur + if tn == 0: + if raise_warning: + msg = ( + "`negative_likelihood_ratio` is ill-defined and set to `np.nan`. " + "Use the `replace_undefined_by` param to control this behavior. To " + "suppress this warning or turn it into an error, see Python's " + "`warnings` module and `warnings.catch_warnings()`." + ) + warnings.warn(msg, UndefinedMetricWarning, stacklevel=2) + if isinstance(replace_undefined_by, float) and np.isnan(replace_undefined_by): + negative_likelihood_ratio = replace_undefined_by + else: + # replace_undefined_by is a dict and + # isinstance(replace_undefined_by.get("LR-", None), Real); this includes + # `np.nan` + negative_likelihood_ratio = desired_lr_neg + else: + negative_likelihood_ratio = neg_num / neg_denom + + return float(positive_likelihood_ratio), float(negative_likelihood_ratio) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def precision_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the precision. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The best value is 1 and the worst value is 0. + + Support beyond term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return + precision for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored + and precision for both classes are computed, then averaged or both returned (when + `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, + precision for all `labels` are either returned or averaged depending on the + `average` parameter. Use `labels` specify the set of labels to calculate precision + for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the metrics for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division. + + Notes: + + - If set to "warn", this acts like 0, but a warning is also raised. + - If set to `np.nan`, such values will be excluded from the average. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + precision : float (if average is not None) or array of float of shape \ + (n_unique_labels,) + Precision of the positive class in binary classification or weighted + average of the precision of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute precision, recall, F-measure and + support for each class. + recall_score : Compute the ratio ``tp / (tp + fn)`` where ``tp`` is the + number of true positives and ``fn`` the number of false negatives. + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given + an estimator and some data. + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given + binary class predictions. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + + Notes + ----- + When ``true positive + false positive == 0``, precision returns 0 and + raises ``UndefinedMetricWarning``. This behavior can be + modified with ``zero_division``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> precision_score(y_true, y_pred, average='macro') + 0.22 + >>> precision_score(y_true, y_pred, average='micro') + 0.33 + >>> precision_score(y_true, y_pred, average='weighted') + 0.22 + >>> precision_score(y_true, y_pred, average=None) + array([0.66, 0. , 0. ]) + >>> y_pred = [0, 0, 0, 0, 0, 0] + >>> precision_score(y_true, y_pred, average=None) + array([0.33, 0. , 0. ]) + >>> precision_score(y_true, y_pred, average=None, zero_division=1) + array([0.33, 1. , 1. ]) + >>> precision_score(y_true, y_pred, average=None, zero_division=np.nan) + array([0.33, nan, nan]) + + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> precision_score(y_true, y_pred, average=None) + array([0.5, 1. , 1. ]) + """ + p, _, _, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("precision",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return p + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "average": [ + StrOptions({"micro", "macro", "samples", "weighted", "binary"}), + None, + ], + "sample_weight": ["array-like", None], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def recall_score( + y_true, + y_pred, + *, + labels=None, + pos_label=1, + average="binary", + sample_weight=None, + zero_division="warn", +): + """Compute the recall. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The best value is 1 and the worst value is 0. + + Support beyond term:`binary` targets is achieved by treating :term:`multiclass` + and :term:`multilabel` data as a collection of binary problems, one for each + label. For the :term:`binary` case, setting `average='binary'` will return + recall for `pos_label`. If `average` is not `'binary'`, `pos_label` is ignored + and recall for both classes are computed then averaged or both returned (when + `average=None`). Similarly, for :term:`multiclass` and :term:`multilabel` targets, + recall for all `labels` are either returned or averaged depending on the `average` + parameter. Use `labels` specify the set of labels to calculate recall for. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like, default=None + The set of labels to include when `average != 'binary'`, and their + order if `average is None`. Labels present in the data can be + excluded, for example in multiclass classification to exclude a "negative + class". Labels not present in the data can be included and will be + "assigned" 0 samples. For multilabel targets, labels are column indices. + By default, all labels in `y_true` and `y_pred` are used in sorted order. + + .. versionchanged:: 0.17 + Parameter `labels` improved for multiclass problem. + + pos_label : int, float, bool or str, default=1 + The class to report if `average='binary'` and the data is binary, + otherwise this parameter is ignored. + For multiclass or multilabel targets, set `labels=[pos_label]` and + `average != 'binary'` to report metrics for one label only. + + average : {'micro', 'macro', 'samples', 'weighted', 'binary'} or None, \ + default='binary' + This parameter is required for multiclass/multilabel targets. + If ``None``, the metrics for each class are returned. Otherwise, this + determines the type of averaging performed on the data: + + ``'binary'``: + Only report results for the class specified by ``pos_label``. + This is applicable only if targets (``y_{true,pred}``) are binary. + ``'micro'``: + Calculate metrics globally by counting the total true positives, + false negatives and false positives. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average weighted + by support (the number of true instances for each label). This + alters 'macro' to account for label imbalance; it can result in an + F-score that is not between precision and recall. Weighted recall + is equal to accuracy. + ``'samples'``: + Calculate metrics for each instance, and find their average (only + meaningful for multilabel classification where this differs from + :func:`accuracy_score`). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division. + + Notes: + + - If set to "warn", this acts like 0, but a warning is also raised. + - If set to `np.nan`, such values will be excluded from the average. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + recall : float (if average is not None) or array of float of shape \ + (n_unique_labels,) + Recall of the positive class in binary classification or weighted + average of the recall of each class for the multiclass task. + + See Also + -------- + precision_recall_fscore_support : Compute precision, recall, F-measure and + support for each class. + precision_score : Compute the ratio ``tp / (tp + fp)`` where ``tp`` is the + number of true positives and ``fp`` the number of false positives. + balanced_accuracy_score : Compute balanced accuracy to deal with imbalanced + datasets. + multilabel_confusion_matrix : Compute a confusion matrix for each class or + sample. + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve given + an estimator and some data. + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve given + binary class predictions. + + Notes + ----- + When ``true positive + false negative == 0``, recall returns 0 and raises + ``UndefinedMetricWarning``. This behavior can be modified with + ``zero_division``. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import recall_score + >>> y_true = [0, 1, 2, 0, 1, 2] + >>> y_pred = [0, 2, 1, 0, 0, 1] + >>> recall_score(y_true, y_pred, average='macro') + 0.33 + >>> recall_score(y_true, y_pred, average='micro') + 0.33 + >>> recall_score(y_true, y_pred, average='weighted') + 0.33 + >>> recall_score(y_true, y_pred, average=None) + array([1., 0., 0.]) + >>> y_true = [0, 0, 0, 0, 0, 0] + >>> recall_score(y_true, y_pred, average=None) + array([0.5, 0. , 0. ]) + >>> recall_score(y_true, y_pred, average=None, zero_division=1) + array([0.5, 1. , 1. ]) + >>> recall_score(y_true, y_pred, average=None, zero_division=np.nan) + array([0.5, nan, nan]) + + >>> # multilabel classification + >>> y_true = [[0, 0, 0], [1, 1, 1], [0, 1, 1]] + >>> y_pred = [[0, 0, 0], [1, 1, 1], [1, 1, 0]] + >>> recall_score(y_true, y_pred, average=None) + array([1. , 1. , 0.5]) + """ + _, r, _, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + pos_label=pos_label, + average=average, + warn_for=("recall",), + sample_weight=sample_weight, + zero_division=zero_division, + ) + return r + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "adjusted": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def balanced_accuracy_score(y_true, y_pred, *, sample_weight=None, adjusted=False): + """Compute the balanced accuracy. + + The balanced accuracy in binary and multiclass classification problems to + deal with imbalanced datasets. It is defined as the average of recall + obtained on each class. + + The best value is 1 and the worst value is 0 when ``adjusted=False``. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated targets as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + adjusted : bool, default=False + When true, the result is adjusted for chance, so that random + performance would score 0, while keeping perfect performance at a score + of 1. + + Returns + ------- + balanced_accuracy : float + Balanced accuracy score. + + See Also + -------- + average_precision_score : Compute average precision (AP) from prediction + scores. + precision_score : Compute the precision score. + recall_score : Compute the recall score. + roc_auc_score : Compute Area Under the Receiver Operating Characteristic + Curve (ROC AUC) from prediction scores. + + Notes + ----- + Some literature promotes alternative definitions of balanced accuracy. Our + definition is equivalent to :func:`accuracy_score` with class-balanced + sample weights, and shares desirable properties with the binary case. + See the :ref:`User Guide `. + + References + ---------- + .. [1] Brodersen, K.H.; Ong, C.S.; Stephan, K.E.; Buhmann, J.M. (2010). + The balanced accuracy and its posterior distribution. + Proceedings of the 20th International Conference on Pattern + Recognition, 3121-24. + .. [2] John. D. Kelleher, Brian Mac Namee, Aoife D'Arcy, (2015). + `Fundamentals of Machine Learning for Predictive Data Analytics: + Algorithms, Worked Examples, and Case Studies + `_. + + Examples + -------- + >>> from sklearn.metrics import balanced_accuracy_score + >>> y_true = [0, 1, 0, 0, 1, 0] + >>> y_pred = [0, 1, 0, 0, 0, 1] + >>> balanced_accuracy_score(y_true, y_pred) + 0.625 + """ + C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) + with np.errstate(divide="ignore", invalid="ignore"): + per_class = np.diag(C) / C.sum(axis=1) + if np.any(np.isnan(per_class)): + warnings.warn("y_pred contains classes not in y_true") + per_class = per_class[~np.isnan(per_class)] + score = np.mean(per_class) + if adjusted: + n_classes = len(per_class) + chance = 1 / n_classes + score -= chance + score /= 1 - chance + return float(score) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "labels": ["array-like", None], + "target_names": ["array-like", None], + "sample_weight": ["array-like", None], + "digits": [Interval(Integral, 0, None, closed="left")], + "output_dict": ["boolean"], + "zero_division": [ + Options(Real, {0.0, 1.0}), + "nan", + StrOptions({"warn"}), + ], + }, + prefer_skip_nested_validation=True, +) +def classification_report( + y_true, + y_pred, + *, + labels=None, + target_names=None, + sample_weight=None, + digits=2, + output_dict=False, + zero_division="warn", +): + """Build a text report showing the main classification metrics. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) target values. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Estimated targets as returned by a classifier. + + labels : array-like of shape (n_labels,), default=None + Optional list of label indices to include in the report. + + target_names : array-like of shape (n_labels,), default=None + Optional display names matching the labels (same order). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + digits : int, default=2 + Number of digits for formatting output floating point values. + When ``output_dict`` is ``True``, this will be ignored and the + returned values will not be rounded. + + output_dict : bool, default=False + If True, return output as dict. + + .. versionadded:: 0.20 + + zero_division : {"warn", 0.0, 1.0, np.nan}, default="warn" + Sets the value to return when there is a zero division. If set to + "warn", this acts as 0, but warnings are also raised. + + .. versionadded:: 1.3 + `np.nan` option was added. + + Returns + ------- + report : str or dict + Text summary of the precision, recall, F1 score for each class. + Dictionary returned if output_dict is True. Dictionary has the + following structure:: + + {'label 1': {'precision':0.5, + 'recall':1.0, + 'f1-score':0.67, + 'support':1}, + 'label 2': { ... }, + ... + } + + The reported averages include macro average (averaging the unweighted + mean per label), weighted average (averaging the support-weighted mean + per label), and sample average (only for multilabel classification). + Micro average (averaging the total true positives, false negatives and + false positives) is only shown for multi-label or multi-class + with a subset of classes, because it corresponds to accuracy + otherwise and would be the same for all metrics. + See also :func:`precision_recall_fscore_support` for more details + on averages. + + Note that in binary classification, recall of the positive class + is also known as "sensitivity"; recall of the negative class is + "specificity". + + See Also + -------- + precision_recall_fscore_support: Compute precision, recall, F-measure and + support for each class. + confusion_matrix: Compute confusion matrix to evaluate the accuracy of a + classification. + multilabel_confusion_matrix: Compute a confusion matrix for each class or sample. + + Examples + -------- + >>> from sklearn.metrics import classification_report + >>> y_true = [0, 1, 2, 2, 2] + >>> y_pred = [0, 0, 2, 2, 1] + >>> target_names = ['class 0', 'class 1', 'class 2'] + >>> print(classification_report(y_true, y_pred, target_names=target_names)) + precision recall f1-score support + + class 0 0.50 1.00 0.67 1 + class 1 0.00 0.00 0.00 1 + class 2 1.00 0.67 0.80 3 + + accuracy 0.60 5 + macro avg 0.50 0.56 0.49 5 + weighted avg 0.70 0.60 0.61 5 + + >>> y_pred = [1, 1, 0] + >>> y_true = [1, 1, 1] + >>> print(classification_report(y_true, y_pred, labels=[1, 2, 3])) + precision recall f1-score support + + 1 1.00 0.67 0.80 3 + 2 0.00 0.00 0.00 0 + 3 0.00 0.00 0.00 0 + + micro avg 1.00 0.67 0.80 3 + macro avg 0.33 0.22 0.27 3 + weighted avg 1.00 0.67 0.80 3 + + """ + + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + + if labels is None: + labels = unique_labels(y_true, y_pred) + labels_given = False + else: + labels = np.asarray(labels) + labels_given = True + + # labelled micro average + micro_is_accuracy = (y_type == "multiclass" or y_type == "binary") and ( + not labels_given or (set(labels) >= set(unique_labels(y_true, y_pred))) + ) + + if target_names is not None and len(labels) != len(target_names): + if labels_given: + warnings.warn( + "labels size, {0}, does not match size of target_names, {1}".format( + len(labels), len(target_names) + ) + ) + else: + raise ValueError( + "Number of classes, {0}, does not match size of " + "target_names, {1}. Try specifying the labels " + "parameter".format(len(labels), len(target_names)) + ) + if target_names is None: + target_names = ["%s" % l for l in labels] + + headers = ["precision", "recall", "f1-score", "support"] + # compute per-class results without averaging + p, r, f1, s = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + average=None, + sample_weight=sample_weight, + zero_division=zero_division, + ) + rows = zip(target_names, p, r, f1, s) + + if y_type.startswith("multilabel"): + average_options = ("micro", "macro", "weighted", "samples") + else: + average_options = ("micro", "macro", "weighted") + + if output_dict: + report_dict = {label[0]: label[1:] for label in rows} + for label, scores in report_dict.items(): + report_dict[label] = dict(zip(headers, [float(i) for i in scores])) + else: + longest_last_line_heading = "weighted avg" + name_width = max(len(cn) for cn in target_names) + width = max(name_width, len(longest_last_line_heading), digits) + head_fmt = "{:>{width}s} " + " {:>9}" * len(headers) + report = head_fmt.format("", *headers, width=width) + report += "\n\n" + row_fmt = "{:>{width}s} " + " {:>9.{digits}f}" * 3 + " {:>9}\n" + for row in rows: + report += row_fmt.format(*row, width=width, digits=digits) + report += "\n" + + # compute all applicable averages + for average in average_options: + if average.startswith("micro") and micro_is_accuracy: + line_heading = "accuracy" + else: + line_heading = average + " avg" + + # compute averages with specified averaging method + avg_p, avg_r, avg_f1, _ = precision_recall_fscore_support( + y_true, + y_pred, + labels=labels, + average=average, + sample_weight=sample_weight, + zero_division=zero_division, + ) + avg = [avg_p, avg_r, avg_f1, np.sum(s)] + + if output_dict: + report_dict[line_heading] = dict(zip(headers, [float(i) for i in avg])) + else: + if line_heading == "accuracy": + row_fmt_accuracy = ( + "{:>{width}s} " + + " {:>9.{digits}}" * 2 + + " {:>9.{digits}f}" + + " {:>9}\n" + ) + report += row_fmt_accuracy.format( + line_heading, "", "", *avg[2:], width=width, digits=digits + ) + else: + report += row_fmt.format(line_heading, *avg, width=width, digits=digits) + + if output_dict: + if "accuracy" in report_dict.keys(): + report_dict["accuracy"] = report_dict["accuracy"]["precision"] + return report_dict + else: + return report + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_pred": ["array-like", "sparse matrix"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def hamming_loss(y_true, y_pred, *, sample_weight=None): + """Compute the average Hamming loss. + + The Hamming loss is the fraction of labels that are incorrectly predicted. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : 1d array-like, or label indicator array / sparse matrix + Ground truth (correct) labels. + + y_pred : 1d array-like, or label indicator array / sparse matrix + Predicted labels, as returned by a classifier. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.18 + + Returns + ------- + loss : float or int + Return the average Hamming loss between element of ``y_true`` and + ``y_pred``. + + See Also + -------- + accuracy_score : Compute the accuracy score. By default, the function will + return the fraction of correct predictions divided by the total number + of predictions. + jaccard_score : Compute the Jaccard similarity coefficient score. + zero_one_loss : Compute the Zero-one classification loss. By default, the + function will return the percentage of imperfectly predicted subsets. + + Notes + ----- + In multiclass classification, the Hamming loss corresponds to the Hamming + distance between ``y_true`` and ``y_pred`` which is equivalent to the + subset ``zero_one_loss`` function, when `normalize` parameter is set to + True. + + In multilabel classification, the Hamming loss is different from the + subset zero-one loss. The zero-one loss considers the entire set of labels + for a given sample incorrect if it does not entirely match the true set of + labels. Hamming loss is more forgiving in that it penalizes only the + individual labels. + + The Hamming loss is upperbounded by the subset zero-one loss, when + `normalize` parameter is set to True. It is always between 0 and 1, + lower being better. + + References + ---------- + .. [1] Grigorios Tsoumakas, Ioannis Katakis. Multi-Label Classification: + An Overview. International Journal of Data Warehousing & Mining, + 3(3), 1-13, July-September 2007. + + .. [2] `Wikipedia entry on the Hamming distance + `_. + + Examples + -------- + >>> from sklearn.metrics import hamming_loss + >>> y_pred = [1, 2, 3, 4] + >>> y_true = [2, 2, 3, 4] + >>> hamming_loss(y_true, y_pred) + 0.25 + + In the multilabel case with binary label indicators: + + >>> import numpy as np + >>> hamming_loss(np.array([[0, 1], [1, 1]]), np.zeros((2, 2))) + 0.75 + """ + y_true, y_pred = attach_unique(y_true, y_pred) + y_type, y_true, y_pred = _check_targets(y_true, y_pred) + check_consistent_length(y_true, y_pred, sample_weight) + + xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight) + + if sample_weight is None: + weight_average = 1.0 + else: + sample_weight = xp.asarray(sample_weight, device=device) + weight_average = _average(sample_weight, xp=xp) + + if y_type.startswith("multilabel"): + n_differences = _count_nonzero( + y_true - y_pred, xp=xp, device=device, sample_weight=sample_weight + ) + return float(n_differences) / ( + y_true.shape[0] * y_true.shape[1] * weight_average + ) + + elif y_type in ["binary", "multiclass"]: + return float(_average(y_true != y_pred, weights=sample_weight, normalize=True)) + else: + raise ValueError("{0} is not supported".format(y_type)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "normalize": ["boolean"], + "sample_weight": ["array-like", None], + "labels": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def log_loss(y_true, y_pred, *, normalize=True, sample_weight=None, labels=None): + r"""Log loss, aka logistic loss or cross-entropy loss. + + This is the loss function used in (multinomial) logistic regression + and extensions of it such as neural networks, defined as the negative + log-likelihood of a logistic model that returns ``y_pred`` probabilities + for its training data ``y_true``. + The log loss is only defined for two or more labels. + For a single sample with true label :math:`y \in \{0,1\}` and + a probability estimate :math:`p = \operatorname{Pr}(y = 1)`, the log + loss is: + + .. math:: + L_{\log}(y, p) = -(y \log (p) + (1 - y) \log (1 - p)) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like or label indicator matrix + Ground truth (correct) labels for n_samples samples. + + y_pred : array-like of float, shape = (n_samples, n_classes) or (n_samples,) + Predicted probabilities, as returned by a classifier's + predict_proba method. If ``y_pred.shape = (n_samples,)`` + the probabilities provided are assumed to be that of the + positive class. The labels in ``y_pred`` are assumed to be + ordered alphabetically, as done by + :class:`~sklearn.preprocessing.LabelBinarizer`. + + `y_pred` values are clipped to `[eps, 1-eps]` where `eps` is the machine + precision for `y_pred`'s dtype. + + normalize : bool, default=True + If true, return the mean loss per sample. + Otherwise, return the sum of the per-sample losses. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like, default=None + If not provided, labels will be inferred from y_true. If ``labels`` + is ``None`` and ``y_pred`` has shape (n_samples,) the labels are + assumed to be binary and are inferred from ``y_true``. + + .. versionadded:: 0.18 + + Returns + ------- + loss : float + Log loss, aka logistic loss or cross-entropy loss. + + Notes + ----- + The logarithm used is the natural logarithm (base-e). + + References + ---------- + C.M. Bishop (2006). Pattern Recognition and Machine Learning. Springer, + p. 209. + + Examples + -------- + >>> from sklearn.metrics import log_loss + >>> log_loss(["spam", "ham", "ham", "spam"], + ... [[.1, .9], [.9, .1], [.8, .2], [.35, .65]]) + 0.21616 + """ + transformed_labels, y_pred = _validate_multiclass_probabilistic_prediction( + y_true, y_pred, sample_weight, labels + ) + + # Clipping + eps = np.finfo(y_pred.dtype).eps + y_pred = np.clip(y_pred, eps, 1 - eps) + + loss = -xlogy(transformed_labels, y_pred).sum(axis=1) + + return float(_average(loss, weights=sample_weight, normalize=normalize)) + + +@validate_params( + { + "y_true": ["array-like"], + "pred_decision": ["array-like"], + "labels": ["array-like", None], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def hinge_loss(y_true, pred_decision, *, labels=None, sample_weight=None): + """Average hinge loss (non-regularized). + + In binary class case, assuming labels in y_true are encoded with +1 and -1, + when a prediction mistake is made, ``margin = y_true * pred_decision`` is + always negative (since the signs disagree), implying ``1 - margin`` is + always greater than 1. The cumulated hinge loss is therefore an upper + bound of the number of mistakes made by the classifier. + + In multiclass case, the function expects that either all the labels are + included in y_true or an optional labels argument is provided which + contains all the labels. The multilabel margin is calculated according + to Crammer-Singer's method. As in the binary case, the cumulated hinge loss + is an upper bound of the number of mistakes made by the classifier. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True target, consisting of integers of two values. The positive label + must be greater than the negative label. + + pred_decision : array-like of shape (n_samples,) or (n_samples, n_classes) + Predicted decisions, as output by decision_function (floats). + + labels : array-like, default=None + Contains all the labels for the problem. Used in multiclass hinge loss. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + Average hinge loss. + + References + ---------- + .. [1] `Wikipedia entry on the Hinge loss + `_. + + .. [2] Koby Crammer, Yoram Singer. On the Algorithmic + Implementation of Multiclass Kernel-based Vector + Machines. Journal of Machine Learning Research 2, + (2001), 265-292. + + .. [3] `L1 AND L2 Regularization for Multiclass Hinge Loss Models + by Robert C. Moore, John DeNero + `_. + + Examples + -------- + >>> from sklearn import svm + >>> from sklearn.metrics import hinge_loss + >>> X = [[0], [1]] + >>> y = [-1, 1] + >>> est = svm.LinearSVC(random_state=0) + >>> est.fit(X, y) + LinearSVC(random_state=0) + >>> pred_decision = est.decision_function([[-2], [3], [0.5]]) + >>> pred_decision + array([-2.18, 2.36, 0.09]) + >>> hinge_loss([-1, 1, 1], pred_decision) + 0.30 + + In the multiclass case: + + >>> import numpy as np + >>> X = np.array([[0], [1], [2], [3]]) + >>> Y = np.array([0, 1, 2, 3]) + >>> labels = np.array([0, 1, 2, 3]) + >>> est = svm.LinearSVC() + >>> est.fit(X, Y) + LinearSVC() + >>> pred_decision = est.decision_function([[-1], [2], [3]]) + >>> y_true = [0, 2, 3] + >>> hinge_loss(y_true, pred_decision, labels=labels) + 0.56 + """ + check_consistent_length(y_true, pred_decision, sample_weight) + pred_decision = check_array(pred_decision, ensure_2d=False) + y_true = column_or_1d(y_true) + y_true_unique = np.unique(labels if labels is not None else y_true) + + if y_true_unique.size > 2: + if pred_decision.ndim <= 1: + raise ValueError( + "The shape of pred_decision cannot be 1d array" + "with a multiclass target. pred_decision shape " + "must be (n_samples, n_classes), that is " + f"({y_true.shape[0]}, {y_true_unique.size})." + f" Got: {pred_decision.shape}" + ) + + # pred_decision.ndim > 1 is true + if y_true_unique.size != pred_decision.shape[1]: + if labels is None: + raise ValueError( + "Please include all labels in y_true " + "or pass labels as third argument" + ) + else: + raise ValueError( + "The shape of pred_decision is not " + "consistent with the number of classes. " + "With a multiclass target, pred_decision " + "shape must be " + "(n_samples, n_classes), that is " + f"({y_true.shape[0]}, {y_true_unique.size}). " + f"Got: {pred_decision.shape}" + ) + if labels is None: + labels = y_true_unique + le = LabelEncoder() + le.fit(labels) + y_true = le.transform(y_true) + mask = np.ones_like(pred_decision, dtype=bool) + mask[np.arange(y_true.shape[0]), y_true] = False + margin = pred_decision[~mask] + margin -= np.max(pred_decision[mask].reshape(y_true.shape[0], -1), axis=1) + + else: + # Handles binary class case + # this code assumes that positive and negative labels + # are encoded as +1 and -1 respectively + pred_decision = column_or_1d(pred_decision) + pred_decision = np.ravel(pred_decision) + + lbin = LabelBinarizer(neg_label=-1) + y_true = lbin.fit_transform(y_true)[:, 0] + + try: + margin = y_true * pred_decision + except TypeError: + raise TypeError("pred_decision should be an array of floats.") + + losses = 1 - margin + # The hinge_loss doesn't penalize good enough predictions. + np.clip(losses, 0, None, out=losses) + return float(np.average(losses, weights=sample_weight)) + + +def _validate_binary_probabilistic_prediction(y_true, y_prob, sample_weight, pos_label): + r"""Convert y_true and y_prob in binary classification to shape (n_samples, 2) + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_prob : array-like of shape (n_samples,) + Probabilities of the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : int, float, bool or str, default=None + Label of the positive class. If None, `pos_label` will be inferred + in the following manner: + + * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; + * else if `y_true` contains string, an error will be raised and + `pos_label` should be explicitly specified; + * otherwise, `pos_label` defaults to the greater label, + i.e. `np.unique(y_true)[-1]`. + + Returns + ------- + transformed_labels : array of shape (n_samples, 2) + + y_prob : array of shape (n_samples, 2) + """ + # sanity checks on y_true and y_prob + y_true = column_or_1d(y_true) + y_prob = column_or_1d(y_prob) + + assert_all_finite(y_true) + assert_all_finite(y_prob) + + check_consistent_length(y_prob, y_true, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "binary": + raise ValueError( + f"The type of the target inferred from y_true is {y_type} but should be " + "binary according to the shape of y_prob." + ) + + if y_prob.max() > 1: + raise ValueError(f"y_prob contains values greater than 1: {y_prob.max()}") + if y_prob.min() < 0: + raise ValueError(f"y_prob contains values less than 0: {y_prob.min()}") + + # check that pos_label is consistent with y_true + try: + pos_label = _check_pos_label_consistency(pos_label, y_true) + except ValueError: + classes = np.unique(y_true) + if classes.dtype.kind not in ("O", "U", "S"): + # for backward compatibility, if classes are not string then + # `pos_label` will correspond to the greater label + pos_label = classes[-1] + else: + raise + + # convert (n_samples,) to (n_samples, 2) shape + y_true = np.array(y_true == pos_label, int) + transformed_labels = np.column_stack((1 - y_true, y_true)) + y_prob = np.column_stack((1 - y_prob, y_prob)) + + return transformed_labels, y_prob + + +@validate_params( + { + "y_true": ["array-like"], + "y_proba": ["array-like"], + "sample_weight": ["array-like", None], + "pos_label": [Real, str, "boolean", None], + "labels": ["array-like", None], + "scale_by_half": ["boolean", StrOptions({"auto"})], + }, + prefer_skip_nested_validation=True, +) +def brier_score_loss( + y_true, + y_proba, + *, + sample_weight=None, + pos_label=None, + labels=None, + scale_by_half="auto", +): + r"""Compute the Brier score loss. + + The smaller the Brier score loss, the better, hence the naming with "loss". + The Brier score measures the mean squared difference between the predicted + probability and the actual outcome. The Brier score is a strictly proper scoring + rule. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True targets. + + y_proba : array-like of shape (n_samples,) or (n_samples, n_classes) + Predicted probabilities. If `y_proba.shape = (n_samples,)` + the probabilities provided are assumed to be that of the + positive class. If `y_proba.shape = (n_samples, n_classes)` + the columns in `y_proba` are assumed to correspond to the + labels in alphabetical order, as done by + :class:`~sklearn.preprocessing.LabelBinarizer`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + pos_label : int, float, bool or str, default=None + Label of the positive class when `y_proba.shape = (n_samples,)`. + If not provided, `pos_label` will be inferred in the + following manner: + + * if `y_true` in {-1, 1} or {0, 1}, `pos_label` defaults to 1; + * else if `y_true` contains string, an error will be raised and + `pos_label` should be explicitly specified; + * otherwise, `pos_label` defaults to the greater label, + i.e. `np.unique(y_true)[-1]`. + + labels : array-like of shape (n_classes,), default=None + Class labels when `y_proba.shape = (n_samples, n_classes)`. + If not provided, labels will be inferred from `y_true`. + + .. versionadded:: 1.7 + + scale_by_half : bool or "auto", default="auto" + When True, scale the Brier score by 1/2 to lie in the [0, 1] range instead + of the [0, 2] range. The default "auto" option implements the rescaling to + [0, 1] only for binary classification (as customary) but keeps the + original [0, 2] range for multiclass classification. + + .. versionadded:: 1.7 + + Returns + ------- + score : float + Brier score loss. + + Notes + ----- + + For :math:`N` observations labeled from :math:`C` possible classes, the Brier + score is defined as: + + .. math:: + \frac{1}{N}\sum_{i=1}^{N}\sum_{c=1}^{C}(y_{ic} - \hat{p}_{ic})^{2} + + where :math:`y_{ic}` is 1 if observation `i` belongs to class `c`, + otherwise 0 and :math:`\hat{p}_{ic}` is the predicted probability for + observation `i` to belong to class `c`. + The Brier score then ranges between :math:`[0, 2]`. + + In binary classification tasks the Brier score is usually divided by + two and then ranges between :math:`[0, 1]`. It can be alternatively + written as: + + .. math:: + \frac{1}{N}\sum_{i=1}^{N}(y_{i} - \hat{p}_{i})^{2} + + where :math:`y_{i}` is the binary target and :math:`\hat{p}_{i}` + is the predicted probability of the positive class. + + References + ---------- + .. [1] `Wikipedia entry for the Brier score + `_. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import brier_score_loss + >>> y_true = np.array([0, 1, 1, 0]) + >>> y_true_categorical = np.array(["spam", "ham", "ham", "spam"]) + >>> y_prob = np.array([0.1, 0.9, 0.8, 0.3]) + >>> brier_score_loss(y_true, y_prob) + 0.0375 + >>> brier_score_loss(y_true, 1-y_prob, pos_label=0) + 0.0375 + >>> brier_score_loss(y_true_categorical, y_prob, pos_label="ham") + 0.0375 + >>> brier_score_loss(y_true, np.array(y_prob) > 0.5) + 0.0 + >>> brier_score_loss(y_true, y_prob, scale_by_half=False) + 0.075 + >>> brier_score_loss( + ... ["eggs", "ham", "spam"], + ... [[0.8, 0.1, 0.1], [0.2, 0.7, 0.1], [0.2, 0.2, 0.6]], + ... labels=["eggs", "ham", "spam"] + ... ) + 0.146 + """ + y_proba = check_array( + y_proba, ensure_2d=False, dtype=[np.float64, np.float32, np.float16] + ) + + if y_proba.ndim == 1 or y_proba.shape[1] == 1: + transformed_labels, y_proba = _validate_binary_probabilistic_prediction( + y_true, y_proba, sample_weight, pos_label + ) + else: + transformed_labels, y_proba = _validate_multiclass_probabilistic_prediction( + y_true, y_proba, sample_weight, labels + ) + + brier_score = np.average( + np.sum((transformed_labels - y_proba) ** 2, axis=1), weights=sample_weight + ) + + if scale_by_half == "auto": + scale_by_half = y_proba.ndim == 1 or y_proba.shape[1] < 3 + if scale_by_half: + brier_score *= 0.5 + + return float(brier_score) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "labels": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def d2_log_loss_score(y_true, y_pred, *, sample_weight=None, labels=None): + """ + :math:`D^2` score function, fraction of log loss explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always predicts the per-class proportions + of `y_true`, disregarding the input features, gets a D^2 score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.5 + + Parameters + ---------- + y_true : array-like or label indicator matrix + The actuals labels for the n_samples samples. + + y_pred : array-like of shape (n_samples, n_classes) or (n_samples,) + Predicted probabilities, as returned by a classifier's + predict_proba method. If ``y_pred.shape = (n_samples,)`` + the probabilities provided are assumed to be that of the + positive class. The labels in ``y_pred`` are assumed to be + ordered alphabetically, as done by + :class:`~sklearn.preprocessing.LabelBinarizer`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + labels : array-like, default=None + If not provided, labels will be inferred from y_true. If ``labels`` + is ``None`` and ``y_pred`` has shape (n_samples,) the labels are + assumed to be binary and are inferred from ``y_true``. + + Returns + ------- + d2 : 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 a single sample and will return a NaN + value if n_samples is less than two. + """ + y_pred = check_array(y_pred, ensure_2d=False, dtype="numeric") + check_consistent_length(y_pred, y_true, 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") + + # log loss of the fitted model + numerator = log_loss( + y_true=y_true, + y_pred=y_pred, + normalize=False, + sample_weight=sample_weight, + labels=labels, + ) + + # Proportion of labels in the dataset + weights = _check_sample_weight(sample_weight, y_true) + + # If labels is passed, augment y_true to ensure that all labels are represented + # Use 0 weight for the new samples to not affect the counts + y_true_, weights_ = ( + ( + np.concatenate([y_true, labels]), + np.concatenate([weights, np.zeros_like(weights, shape=len(labels))]), + ) + if labels is not None + else (y_true, weights) + ) + + _, y_value_indices = np.unique(y_true_, return_inverse=True) + counts = np.bincount(y_value_indices, weights=weights_) + y_prob = counts / weights.sum() + y_pred_null = np.tile(y_prob, (len(y_true), 1)) + + # log loss of the null model + denominator = log_loss( + y_true=y_true, + y_pred=y_pred_null, + normalize=False, + sample_weight=sample_weight, + labels=labels, + ) + + return float(1 - (numerator / denominator)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd new file mode 100644 index 0000000000000000000000000000000000000000..0a249a8a9fb0a158c34c9f725891467de6041d40 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd @@ -0,0 +1,268 @@ +from libc.math cimport sqrt, exp + +from ..utils._typedefs cimport float64_t, float32_t, int32_t, intp_t + +cdef class DistanceMetric: + pass + +###################################################################### +# Inline distance functions +# +# We use these for the default (euclidean) case so that they can be +# inlined. This leads to faster computation for the most common case +cdef inline float64_t euclidean_dist64( + const float64_t* x1, + const float64_t* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return sqrt(d) + + +cdef inline float64_t euclidean_rdist64( + const float64_t* x1, + const float64_t* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return d + + +cdef inline float64_t euclidean_dist_to_rdist64(const float64_t dist) except -1 nogil: + return dist * dist + + +cdef inline float64_t euclidean_rdist_to_dist64(const float64_t dist) except -1 nogil: + return sqrt(dist) + + +###################################################################### +# DistanceMetric64 base class +cdef class DistanceMetric64(DistanceMetric): + # The following attributes are required for a few of the subclasses. + # we must define them here so that cython's limited polymorphism will work. + # Because we don't expect to instantiate a lot of these objects, the + # extra memory overhead of this setup should not be an issue. + cdef float64_t p + cdef const float64_t[::1] vec + cdef const float64_t[:, ::1] mat + cdef intp_t size + cdef object func + cdef object kwargs + + cdef float64_t dist( + self, + const float64_t* x1, + const float64_t* x2, + intp_t size, + ) except -1 nogil + + cdef float64_t rdist( + self, + const float64_t* x1, + const float64_t* x2, + intp_t size, + ) except -1 nogil + + cdef float64_t dist_csr( + self, + const float64_t* x1_data, + const int32_t* x1_indices, + const float64_t* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef float64_t rdist_csr( + self, + const float64_t* x1_data, + const int32_t* x1_indices, + const float64_t* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef int pdist( + self, + const float64_t[:, ::1] X, + float64_t[:, ::1] D, + ) except -1 + + cdef int cdist( + self, + const float64_t[:, ::1] X, + const float64_t[:, ::1] Y, + float64_t[:, ::1] D, + ) except -1 + + cdef int pdist_csr( + self, + const float64_t* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const intp_t size, + float64_t[:, ::1] D, + ) except -1 nogil + + cdef int cdist_csr( + self, + const float64_t* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const float64_t* x2_data, + const int32_t[::1] x2_indices, + const int32_t[::1] x2_indptr, + const intp_t size, + float64_t[:, ::1] D, + ) except -1 nogil + + cdef float64_t _rdist_to_dist(self, float64_t rdist) except -1 nogil + + cdef float64_t _dist_to_rdist(self, float64_t dist) except -1 nogil + +###################################################################### +# Inline distance functions +# +# We use these for the default (euclidean) case so that they can be +# inlined. This leads to faster computation for the most common case +cdef inline float64_t euclidean_dist32( + const float32_t* x1, + const float32_t* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return sqrt(d) + + +cdef inline float64_t euclidean_rdist32( + const float32_t* x1, + const float32_t* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return d + + +cdef inline float64_t euclidean_dist_to_rdist32(const float32_t dist) except -1 nogil: + return dist * dist + + +cdef inline float64_t euclidean_rdist_to_dist32(const float32_t dist) except -1 nogil: + return sqrt(dist) + + +###################################################################### +# DistanceMetric32 base class +cdef class DistanceMetric32(DistanceMetric): + # The following attributes are required for a few of the subclasses. + # we must define them here so that cython's limited polymorphism will work. + # Because we don't expect to instantiate a lot of these objects, the + # extra memory overhead of this setup should not be an issue. + cdef float64_t p + cdef const float64_t[::1] vec + cdef const float64_t[:, ::1] mat + cdef intp_t size + cdef object func + cdef object kwargs + + cdef float32_t dist( + self, + const float32_t* x1, + const float32_t* x2, + intp_t size, + ) except -1 nogil + + cdef float32_t rdist( + self, + const float32_t* x1, + const float32_t* x2, + intp_t size, + ) except -1 nogil + + cdef float32_t dist_csr( + self, + const float32_t* x1_data, + const int32_t* x1_indices, + const float32_t* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef float32_t rdist_csr( + self, + const float32_t* x1_data, + const int32_t* x1_indices, + const float32_t* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef int pdist( + self, + const float32_t[:, ::1] X, + float32_t[:, ::1] D, + ) except -1 + + cdef int cdist( + self, + const float32_t[:, ::1] X, + const float32_t[:, ::1] Y, + float32_t[:, ::1] D, + ) except -1 + + cdef int pdist_csr( + self, + const float32_t* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const intp_t size, + float32_t[:, ::1] D, + ) except -1 nogil + + cdef int cdist_csr( + self, + const float32_t* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const float32_t* x2_data, + const int32_t[::1] x2_indices, + const int32_t[::1] x2_indptr, + const intp_t size, + float32_t[:, ::1] D, + ) except -1 nogil + + cdef float32_t _rdist_to_dist(self, float32_t rdist) except -1 nogil + + cdef float32_t _dist_to_rdist(self, float32_t dist) except -1 nogil diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..313225088c776e8575bfb4cec47c1f17183fab03 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pxd.tp @@ -0,0 +1,152 @@ +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + ('64', 'float64_t', 'np.float64'), + ('32', 'float32_t', 'np.float32') +] + +}} +from libc.math cimport sqrt, exp + +from ..utils._typedefs cimport float64_t, float32_t, int32_t, intp_t + +cdef class DistanceMetric: + pass + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +###################################################################### +# Inline distance functions +# +# We use these for the default (euclidean) case so that they can be +# inlined. This leads to faster computation for the most common case +cdef inline float64_t euclidean_dist{{name_suffix}}( + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return sqrt(d) + + +cdef inline float64_t euclidean_rdist{{name_suffix}}( + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, +) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = (x1[j] - x2[j]) + d += tmp * tmp + return d + + +cdef inline float64_t euclidean_dist_to_rdist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) except -1 nogil: + return dist * dist + + +cdef inline float64_t euclidean_rdist_to_dist{{name_suffix}}(const {{INPUT_DTYPE_t}} dist) except -1 nogil: + return sqrt(dist) + + +###################################################################### +# DistanceMetric{{name_suffix}} base class +cdef class DistanceMetric{{name_suffix}}(DistanceMetric): + # The following attributes are required for a few of the subclasses. + # we must define them here so that cython's limited polymorphism will work. + # Because we don't expect to instantiate a lot of these objects, the + # extra memory overhead of this setup should not be an issue. + cdef float64_t p + cdef const float64_t[::1] vec + cdef const float64_t[:, ::1] mat + cdef intp_t size + cdef object func + cdef object kwargs + + cdef {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil + + cdef {{INPUT_DTYPE_t}} rdist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil + + cdef {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil + + cdef int pdist( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 + + cdef int cdist( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + const {{INPUT_DTYPE_t}}[:, ::1] Y, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 + + cdef int pdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const intp_t size, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 nogil + + cdef int cdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t[::1] x2_indices, + const int32_t[::1] x2_indptr, + const intp_t size, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 nogil + + cdef {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil + + cdef {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..b7d3d1f4d86a6b4817af36489d1846b74afe7e6d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_dist_metrics.pyx.tp @@ -0,0 +1,2811 @@ +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + ('64', 'float64_t', 'np.float64'), + ('32', 'float32_t', 'np.float32') +] + +}} +# By Jake Vanderplas (2013) +# written for the scikit-learn project +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +cimport numpy as cnp + +cnp.import_array() # required in order to use C-API + +from libc.math cimport fabs, sqrt, exp, pow, cos, sin, asin + +from scipy.sparse import csr_matrix, issparse +from ..utils._typedefs cimport float64_t, float32_t, int32_t, intp_t +from ..utils import check_array +from ..utils.fixes import parse_version, sp_base_version + +cdef inline double fmax(double a, double b) noexcept nogil: + return max(a, b) + + +###################################################################### +# newObj function +# this is a helper function for pickling +def newObj(obj): + return obj.__new__(obj) + + +BOOL_METRICS = [ + "hamming", + "jaccard", + "dice", + "rogerstanimoto", + "russellrao", + "sokalsneath", +] +DEPRECATED_METRICS = [] +if sp_base_version < parse_version("1.17"): + # Deprecated in SciPy 1.15 and removed in SciPy 1.17 + BOOL_METRICS += ["sokalmichener"] +if sp_base_version >= parse_version("1.15"): + DEPRECATED_METRICS.append("sokalmichener") +if sp_base_version < parse_version("1.11"): + # Deprecated in SciPy 1.9 and removed in SciPy 1.11 + BOOL_METRICS += ["kulsinski"] +if sp_base_version >= parse_version("1.9"): + DEPRECATED_METRICS.append("kulsinski") +if sp_base_version < parse_version("1.9"): + # Deprecated in SciPy 1.0 and removed in SciPy 1.9 + BOOL_METRICS += ["matching"] +if sp_base_version >= parse_version("1.0"): + DEPRECATED_METRICS.append("matching") + +def get_valid_metric_ids(L): + """Given an iterable of metric class names or class identifiers, + return a list of metric IDs which map to those classes. + + Example: + >>> L = get_valid_metric_ids([EuclideanDistance, 'ManhattanDistance']) + >>> sorted(L) + ['cityblock', 'euclidean', 'l1', 'l2', 'manhattan'] + """ + return [key for (key, val) in METRIC_MAPPING64.items() + if (val.__name__ in L) or (val in L)] + +cdef class DistanceMetric: + """Uniform interface for fast distance metric functions. + + The `DistanceMetric` class provides a convenient way to compute pairwise distances + between samples. It supports various distance metrics, such as Euclidean distance, + Manhattan distance, and more. + + The `pairwise` method can be used to compute pairwise distances between samples in + the input arrays. It returns a distance matrix representing the distances between + all pairs of samples. + + The :meth:`get_metric` method allows you to retrieve a specific metric using its + string identifier. + + Examples + -------- + >>> from sklearn.metrics import DistanceMetric + >>> dist = DistanceMetric.get_metric('euclidean') + >>> X = [[1, 2], [3, 4], [5, 6]] + >>> Y = [[7, 8], [9, 10]] + >>> dist.pairwise(X,Y) + array([[7.81..., 10.63...] + [5.65..., 8.48...] + [1.41..., 4.24...]]) + + .. rubric:: Available Metrics + + The following lists the string metric identifiers and the associated + distance metric classes: + + **Metrics intended for real-valued vector spaces:** + + ============== ==================== ======== =============================== + identifier class name args distance function + -------------- -------------------- -------- ------------------------------- + "euclidean" EuclideanDistance - ``sqrt(sum((x - y)^2))`` + "manhattan" ManhattanDistance - ``sum(|x - y|)`` + "chebyshev" ChebyshevDistance - ``max(|x - y|)`` + "minkowski" MinkowskiDistance p, w ``sum(w * |x - y|^p)^(1/p)`` + "seuclidean" SEuclideanDistance V ``sqrt(sum((x - y)^2 / V))`` + "mahalanobis" MahalanobisDistance V or VI ``sqrt((x - y)' V^-1 (x - y))`` + ============== ==================== ======== =============================== + + **Metrics intended for two-dimensional vector spaces:** Note that the haversine + distance metric requires data in the form of [latitude, longitude] and both + inputs and outputs are in units of radians. + + ============ ================== =============================================================== + identifier class name distance function + ------------ ------------------ --------------------------------------------------------------- + "haversine" HaversineDistance ``2 arcsin(sqrt(sin^2(0.5*dx) + cos(x1)cos(x2)sin^2(0.5*dy)))`` + ============ ================== =============================================================== + + + **Metrics intended for integer-valued vector spaces:** Though intended + for integer-valued vectors, these are also valid metrics in the case of + real-valued vectors. + + ============= ==================== ======================================== + identifier class name distance function + ------------- -------------------- ---------------------------------------- + "hamming" HammingDistance ``N_unequal(x, y) / N_tot`` + "canberra" CanberraDistance ``sum(|x - y| / (|x| + |y|))`` + "braycurtis" BrayCurtisDistance ``sum(|x - y|) / (sum(|x|) + sum(|y|))`` + ============= ==================== ======================================== + + **Metrics intended for boolean-valued vector spaces:** Any nonzero entry + is evaluated to "True". In the listings below, the following + abbreviations are used: + + - N: number of dimensions + - NTT: number of dims in which both values are True + - NTF: number of dims in which the first value is True, second is False + - NFT: number of dims in which the first value is False, second is True + - NFF: number of dims in which both values are False + - NNEQ: number of non-equal dimensions, NNEQ = NTF + NFT + - NNZ: number of nonzero dimensions, NNZ = NTF + NFT + NTT + + ================= ======================= =============================== + identifier class name distance function + ----------------- ----------------------- ------------------------------- + "jaccard" JaccardDistance NNEQ / NNZ + "matching" MatchingDistance NNEQ / N + "dice" DiceDistance NNEQ / (NTT + NNZ) + "kulsinski" KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N) + "rogerstanimoto" RogersTanimotoDistance 2 * NNEQ / (N + NNEQ) + "russellrao" RussellRaoDistance (N - NTT) / N + "sokalmichener" SokalMichenerDistance 2 * NNEQ / (N + NNEQ) + "sokalsneath" SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT) + ================= ======================= =============================== + + **User-defined distance:** + + =========== =============== ======= + identifier class name args + ----------- --------------- ------- + "pyfunc" PyFuncDistance func + =========== =============== ======= + + Here ``func`` is a function which takes two one-dimensional numpy + arrays, and returns a distance. Note that in order to be used within + the BallTree, the distance must be a true metric: + i.e. it must satisfy the following properties + + 1) Non-negativity: d(x, y) >= 0 + 2) Identity: d(x, y) = 0 if and only if x == y + 3) Symmetry: d(x, y) = d(y, x) + 4) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z) + + Because of the Python object overhead involved in calling the python + function, this will be fairly slow, but it will have the same + scaling as other distances. + """ + @classmethod + def get_metric(cls, metric, dtype=np.float64, **kwargs): + """Get the given distance metric from the string identifier. + + See the docstring of DistanceMetric for a list of available metrics. + + Parameters + ---------- + metric : str or class name + The string identifier or class name of the desired distance metric. + See the documentation of the `DistanceMetric` class for a list of + available metrics. + + dtype : {np.float32, np.float64}, default=np.float64 + The data type of the input on which the metric will be applied. + This affects the precision of the computed distances. + By default, it is set to `np.float64`. + + **kwargs + Additional keyword arguments that will be passed to the requested metric. + These arguments can be used to customize the behavior of the specific + metric. + + Returns + ------- + metric_obj : instance of the requested metric + An instance of the requested distance metric class. + """ + if dtype == np.float32: + specialized_class = DistanceMetric32 + elif dtype == np.float64: + specialized_class = DistanceMetric64 + else: + raise ValueError( + f"Unexpected dtype {dtype} provided. Please select a dtype from" + " {np.float32, np.float64}" + ) + + return specialized_class.get_metric(metric, **kwargs) + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +###################################################################### +# metric mappings +# These map from metric id strings to class names +METRIC_MAPPING{{name_suffix}} = { + 'euclidean': EuclideanDistance{{name_suffix}}, + 'l2': EuclideanDistance{{name_suffix}}, + 'minkowski': MinkowskiDistance{{name_suffix}}, + 'p': MinkowskiDistance{{name_suffix}}, + 'manhattan': ManhattanDistance{{name_suffix}}, + 'cityblock': ManhattanDistance{{name_suffix}}, + 'l1': ManhattanDistance{{name_suffix}}, + 'chebyshev': ChebyshevDistance{{name_suffix}}, + 'infinity': ChebyshevDistance{{name_suffix}}, + 'seuclidean': SEuclideanDistance{{name_suffix}}, + 'mahalanobis': MahalanobisDistance{{name_suffix}}, + 'hamming': HammingDistance{{name_suffix}}, + 'canberra': CanberraDistance{{name_suffix}}, + 'braycurtis': BrayCurtisDistance{{name_suffix}}, + 'matching': MatchingDistance{{name_suffix}}, + 'jaccard': JaccardDistance{{name_suffix}}, + 'dice': DiceDistance{{name_suffix}}, + 'kulsinski': KulsinskiDistance{{name_suffix}}, + 'rogerstanimoto': RogersTanimotoDistance{{name_suffix}}, + 'russellrao': RussellRaoDistance{{name_suffix}}, + 'sokalmichener': SokalMichenerDistance{{name_suffix}}, + 'sokalsneath': SokalSneathDistance{{name_suffix}}, + 'haversine': HaversineDistance{{name_suffix}}, + 'pyfunc': PyFuncDistance{{name_suffix}}, +} + +cdef inline object _buffer_to_ndarray{{name_suffix}}(const {{INPUT_DTYPE_t}}* x, intp_t n): + # Wrap a memory buffer with an ndarray. Warning: this is not robust. + # In particular, if x is deallocated before the returned array goes + # out of scope, this could cause memory errors. Since there is not + # a possibility of this for our use-case, this should be safe. + + # Note: this Segfaults unless np.import_array() is called above + # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0 + return cnp.PyArray_SimpleNewFromData(1, &n, cnp.NPY_FLOAT64, x) + + +cdef {{INPUT_DTYPE_t}} INF{{name_suffix}} = np.inf + + +###################################################################### +# Distance Metric Classes +cdef class DistanceMetric{{name_suffix}}(DistanceMetric): + """DistanceMetric class + + This class provides a uniform interface to fast distance metric + functions. The various metrics can be accessed via the :meth:`get_metric` + class method and the metric string identifier (see below). + + Examples + -------- + >>> from sklearn.metrics import DistanceMetric + >>> dist = DistanceMetric.get_metric('euclidean') + >>> X = [[0, 1, 2], + [3, 4, 5]] + >>> dist.pairwise(X) + array([[ 0. , 5.19615242], + [ 5.19615242, 0. ]]) + + Available Metrics + + The following lists the string metric identifiers and the associated + distance metric classes: + + **Metrics intended for real-valued vector spaces:** + + ============== ==================== ======== =============================== + identifier class name args distance function + -------------- -------------------- -------- ------------------------------- + "euclidean" EuclideanDistance - ``sqrt(sum((x - y)^2))`` + "manhattan" ManhattanDistance - ``sum(|x - y|)`` + "chebyshev" ChebyshevDistance - ``max(|x - y|)`` + "minkowski" MinkowskiDistance p, w ``sum(w * |x - y|^p)^(1/p)`` + "seuclidean" SEuclideanDistance V ``sqrt(sum((x - y)^2 / V))`` + "mahalanobis" MahalanobisDistance V or VI ``sqrt((x - y)' V^-1 (x - y))`` + ============== ==================== ======== =============================== + + **Metrics intended for two-dimensional vector spaces:** Note that the haversine + distance metric requires data in the form of [latitude, longitude] and both + inputs and outputs are in units of radians. + + ============ ================== =============================================================== + identifier class name distance function + ------------ ------------------ --------------------------------------------------------------- + "haversine" HaversineDistance ``2 arcsin(sqrt(sin^2(0.5*dx) + cos(x1)cos(x2)sin^2(0.5*dy)))`` + ============ ================== =============================================================== + + + **Metrics intended for integer-valued vector spaces:** Though intended + for integer-valued vectors, these are also valid metrics in the case of + real-valued vectors. + + ============= ==================== ======================================== + identifier class name distance function + ------------- -------------------- ---------------------------------------- + "hamming" HammingDistance ``N_unequal(x, y) / N_tot`` + "canberra" CanberraDistance ``sum(|x - y| / (|x| + |y|))`` + "braycurtis" BrayCurtisDistance ``sum(|x - y|) / (sum(|x|) + sum(|y|))`` + ============= ==================== ======================================== + + **Metrics intended for boolean-valued vector spaces:** Any nonzero entry + is evaluated to "True". In the listings below, the following + abbreviations are used: + + - N: number of dimensions + - NTT: number of dims in which both values are True + - NTF: number of dims in which the first value is True, second is False + - NFT: number of dims in which the first value is False, second is True + - NFF: number of dims in which both values are False + - NNEQ: number of non-equal dimensions, NNEQ = NTF + NFT + - NNZ: number of nonzero dimensions, NNZ = NTF + NFT + NTT + + ================= ======================= =============================== + identifier class name distance function + ----------------- ----------------------- ------------------------------- + "jaccard" JaccardDistance NNEQ / NNZ + "matching" MatchingDistance NNEQ / N + "dice" DiceDistance NNEQ / (NTT + NNZ) + "kulsinski" KulsinskiDistance (NNEQ + N - NTT) / (NNEQ + N) + "rogerstanimoto" RogersTanimotoDistance 2 * NNEQ / (N + NNEQ) + "russellrao" RussellRaoDistance (N - NTT) / N + "sokalmichener" SokalMichenerDistance 2 * NNEQ / (N + NNEQ) + "sokalsneath" SokalSneathDistance NNEQ / (NNEQ + 0.5 * NTT) + ================= ======================= =============================== + + **User-defined distance:** + + =========== =============== ======= + identifier class name args + ----------- --------------- ------- + "pyfunc" PyFuncDistance func + =========== =============== ======= + + Here ``func`` is a function which takes two one-dimensional numpy + arrays, and returns a distance. Note that in order to be used within + the BallTree, the distance must be a true metric: + i.e. it must satisfy the following properties + + 1) Non-negativity: d(x, y) >= 0 + 2) Identity: d(x, y) = 0 if and only if x == y + 3) Symmetry: d(x, y) = d(y, x) + 4) Triangle Inequality: d(x, y) + d(y, z) >= d(x, z) + + Because of the Python object overhead involved in calling the python + function, this will be fairly slow, but it will have the same + scaling as other distances. + """ + def __cinit__(self): + self.p = 2 + self.vec = np.zeros(1, dtype=np.float64, order='C') + self.mat = np.zeros((1, 1), dtype=np.float64, order='C') + self.size = 1 + + def __reduce__(self): + """ + reduce method used for pickling + """ + return (newObj, (self.__class__,), self.__getstate__()) + + def __getstate__(self): + """ + get state for pickling + """ + if self.__class__.__name__ == "PyFuncDistance{{name_suffix}}": + return (float(self.p), np.asarray(self.vec), np.asarray(self.mat), self.func, self.kwargs) + return (float(self.p), np.asarray(self.vec), np.asarray(self.mat)) + + def __setstate__(self, state): + """ + set state for pickling + """ + self.p = state[0] + self.vec = state[1] + self.mat = state[2] + if self.__class__.__name__ == "PyFuncDistance{{name_suffix}}": + self.func = state[3] + self.kwargs = state[4] + self.size = self.vec.shape[0] + + @classmethod + def get_metric(cls, metric, **kwargs): + """Get the given distance metric from the string identifier. + + See the docstring of DistanceMetric for a list of available metrics. + + Parameters + ---------- + metric : str or class name + The distance metric to use + **kwargs + additional arguments will be passed to the requested metric + """ + if isinstance(metric, DistanceMetric{{name_suffix}}): + return metric + + if callable(metric): + return PyFuncDistance{{name_suffix}}(metric, **kwargs) + + # Map the metric string ID to the metric class + if isinstance(metric, type) and issubclass(metric, DistanceMetric{{name_suffix}}): + pass + else: + try: + metric = METRIC_MAPPING{{name_suffix}}[metric] + except: + raise ValueError("Unrecognized metric '%s'" % metric) + + # In Minkowski special cases, return more efficient methods + if metric is MinkowskiDistance{{name_suffix}}: + p = kwargs.pop('p', 2) + w = kwargs.pop('w', None) + if p == 1 and w is None: + return ManhattanDistance{{name_suffix}}(**kwargs) + elif p == 2 and w is None: + return EuclideanDistance{{name_suffix}}(**kwargs) + elif np.isinf(p) and w is None: + return ChebyshevDistance{{name_suffix}}(**kwargs) + else: + return MinkowskiDistance{{name_suffix}}(p, w, **kwargs) + else: + return metric(**kwargs) + + def __init__(self): + if self.__class__ is DistanceMetric{{name_suffix}}: + raise NotImplementedError("DistanceMetric{{name_suffix}} is an abstract class") + + def _validate_data(self, X): + """Validate the input data. + + This should be overridden in a base class if a specific input format + is required. + """ + return + + cdef {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + """Compute the distance between vectors x1 and x2 + + This should be overridden in a base class. + """ + return -999 + + cdef {{INPUT_DTYPE_t}} rdist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + """Compute the rank-preserving surrogate distance between vectors x1 and x2. + + This can optionally be overridden in a base class. + + The rank-preserving surrogate distance is any measure that yields the same + rank as the distance, but is more efficient to compute. For example, the + rank-preserving surrogate distance of the Euclidean metric is the + squared-euclidean distance. + """ + return self.dist(x1, x2, size) + + cdef int pdist( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1: + """Compute the pairwise distances between points in X""" + cdef intp_t i1, i2 + for i1 in range(X.shape[0]): + for i2 in range(i1, X.shape[0]): + D[i1, i2] = self.dist(&X[i1, 0], &X[i2, 0], X.shape[1]) + D[i2, i1] = D[i1, i2] + return 0 + + + cdef int cdist( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + const {{INPUT_DTYPE_t}}[:, ::1] Y, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1: + """Compute the cross-pairwise distances between arrays X and Y""" + cdef intp_t i1, i2 + if X.shape[1] != Y.shape[1]: + raise ValueError('X and Y must have the same second dimension') + for i1 in range(X.shape[0]): + for i2 in range(Y.shape[0]): + D[i1, i2] = self.dist(&X[i1, 0], &Y[i2, 0], X.shape[1]) + return 0 + + cdef {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + """Compute the distance between vectors x1 and x2 represented + under the CSR format. + + This must be overridden in a subclass. + + Notes + ----- + 0. The implementation of this method in subclasses must be robust to the + presence of explicit zeros in the CSR representation. + + 1. The `data` arrays are passed using pointers to be able to support an + alternative representation of the CSR data structure for supporting + fused sparse-dense datasets pairs with minimum overhead. + + See the explanations in `SparseDenseDatasetsPair.__init__`. + + 2. An alternative signature would be: + + cdef {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + ) except -1 nogil: + + Where callers would use slicing on the original CSR data and indices + memoryviews: + + x1_start = X1_csr.indices_ptr[i] + x1_end = X1_csr.indices_ptr[i+1] + x2_start = X2_csr.indices_ptr[j] + x2_end = X2_csr.indices_ptr[j+1] + + self.dist_csr( + &x1_data[x1_start], + x1_indices[x1_start:x1_end], + &x2_data[x2_start], + x2_indices[x2_start:x2_end], + ) + + Yet, slicing on memoryview slows down execution as it takes the GIL. + See: https://github.com/scikit-learn/scikit-learn/issues/17299 + + Hence, to avoid slicing the data and indices arrays of the sparse + matrices containing respectively x1 and x2 (namely x{1,2}_{data,indices}) + are passed as well as their indices pointers (namely x{1,2}_{start,end}). + + 3. For reference about the CSR format, see section 3.4 of + Saad, Y. (2003), Iterative Methods for Sparse Linear Systems, SIAM. + https://www-users.cse.umn.edu/~saad/IterMethBook_2ndEd.pdf + """ + return -999 + + cdef {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + """Distance between rows of CSR matrices x1 and x2. + + This can optionally be overridden in a subclass. + + The rank-preserving surrogate distance is any measure that yields the same + rank as the distance, but is more efficient to compute. For example, the + rank-preserving surrogate distance of the Euclidean metric is the + squared-euclidean distance. + + Notes + ----- + The implementation of this method in subclasses must be robust to the + presence of explicit zeros in the CSR representation. + + More information about the motives for this method signature is given + in the docstring of dist_csr. + """ + return self.dist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + ) + + cdef int pdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const intp_t size, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 nogil: + """Pairwise distances between rows in CSR matrix X. + + Note that this implementation is twice faster than cdist_csr(X, X) + because it leverages the symmetry of the problem. + """ + cdef: + intp_t i1, i2 + intp_t n_x1 = x1_indptr.shape[0] - 1 + intp_t x1_start, x1_end, x2_start, x2_end + + for i1 in range(n_x1): + x1_start = x1_indptr[i1] + x1_end = x1_indptr[i1 + 1] + for i2 in range(i1, n_x1): + x2_start = x1_indptr[i2] + x2_end = x1_indptr[i2 + 1] + D[i1, i2] = D[i2, i1] = self.dist_csr( + x1_data, + &x1_indices[0], + x1_data, + &x1_indices[0], + x1_start, + x1_end, + x2_start, + x2_end, + size, + ) + return 0 + + cdef int cdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t[::1] x1_indices, + const int32_t[::1] x1_indptr, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t[::1] x2_indices, + const int32_t[::1] x2_indptr, + const intp_t size, + {{INPUT_DTYPE_t}}[:, ::1] D, + ) except -1 nogil: + """Compute the cross-pairwise distances between arrays X and Y + represented in the CSR format.""" + cdef: + intp_t i1, i2 + intp_t n_x1 = x1_indptr.shape[0] - 1 + intp_t n_x2 = x2_indptr.shape[0] - 1 + intp_t x1_start, x1_end, x2_start, x2_end + + for i1 in range(n_x1): + x1_start = x1_indptr[i1] + x1_end = x1_indptr[i1 + 1] + for i2 in range(n_x2): + x2_start = x2_indptr[i2] + x2_end = x2_indptr[i2 + 1] + + D[i1, i2] = self.dist_csr( + x1_data, + &x1_indices[0], + x2_data, + &x2_indices[0], + x1_start, + x1_end, + x2_start, + x2_end, + size, + ) + return 0 + + cdef {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + """Convert the rank-preserving surrogate distance to the distance""" + return rdist + + cdef {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + """Convert the distance to the rank-preserving surrogate distance""" + return dist + + def rdist_to_dist(self, rdist): + """Convert the rank-preserving surrogate distance to the distance. + + The surrogate distance is any measure that yields the same rank as the + distance, but is more efficient to compute. For example, the + rank-preserving surrogate distance of the Euclidean metric is the + squared-euclidean distance. + + Parameters + ---------- + rdist : double + Surrogate distance. + + Returns + ------- + double + True distance. + """ + return rdist + + def dist_to_rdist(self, dist): + """Convert the true distance to the rank-preserving surrogate distance. + + The surrogate distance is any measure that yields the same rank as the + distance, but is more efficient to compute. For example, the + rank-preserving surrogate distance of the Euclidean metric is the + squared-euclidean distance. + + Parameters + ---------- + dist : double + True distance. + + Returns + ------- + double + Surrogate distance. + """ + return dist + + def _pairwise_dense_dense(self, X, Y): + cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr + cdef const {{INPUT_DTYPE_t}}[:, ::1] Yarr + cdef {{INPUT_DTYPE_t}}[:, ::1] Darr + + Xarr = np.asarray(X, dtype={{INPUT_DTYPE}}, order='C') + self._validate_data(Xarr) + if X is Y: + Darr = np.empty((Xarr.shape[0], Xarr.shape[0]), dtype={{INPUT_DTYPE}}, order='C') + self.pdist(Xarr, Darr) + else: + Yarr = np.asarray(Y, dtype={{INPUT_DTYPE}}, order='C') + self._validate_data(Yarr) + Darr = np.empty((Xarr.shape[0], Yarr.shape[0]), dtype={{INPUT_DTYPE}}, order='C') + self.cdist(Xarr, Yarr, Darr) + return np.asarray(Darr) + + def _pairwise_sparse_sparse(self, X: csr_matrix , Y: csr_matrix): + cdef: + intp_t n_X, n_features + const {{INPUT_DTYPE_t}}[::1] X_data + const int32_t[::1] X_indices + const int32_t[::1] X_indptr + + intp_t n_Y + const {{INPUT_DTYPE_t}}[::1] Y_data + const int32_t[::1] Y_indices + const int32_t[::1] Y_indptr + + {{INPUT_DTYPE_t}}[:, ::1] Darr + + X_csr = X.tocsr() + n_X, n_features = X_csr.shape + X_data = np.asarray(X_csr.data, dtype={{INPUT_DTYPE}}) + X_indices = np.asarray(X_csr.indices, dtype=np.int32) + X_indptr = np.asarray(X_csr.indptr, dtype=np.int32) + if X is Y: + Darr = np.empty((n_X, n_X), dtype={{INPUT_DTYPE}}, order='C') + self.pdist_csr( + x1_data=&X_data[0], + x1_indices=X_indices, + x1_indptr=X_indptr, + size=n_features, + D=Darr, + ) + else: + Y_csr = Y.tocsr() + n_Y, _ = Y_csr.shape + Y_data = np.asarray(Y_csr.data, dtype={{INPUT_DTYPE}}) + Y_indices = np.asarray(Y_csr.indices, dtype=np.int32) + Y_indptr = np.asarray(Y_csr.indptr, dtype=np.int32) + + Darr = np.empty((n_X, n_Y), dtype={{INPUT_DTYPE}}, order='C') + self.cdist_csr( + x1_data=&X_data[0], + x1_indices=X_indices, + x1_indptr=X_indptr, + x2_data=&Y_data[0], + x2_indices=Y_indices, + x2_indptr=Y_indptr, + size=n_features, + D=Darr, + ) + return np.asarray(Darr) + + def _pairwise_sparse_dense(self, X: csr_matrix, Y): + cdef: + intp_t n_X = X.shape[0] + intp_t n_features = X.shape[1] + const {{INPUT_DTYPE_t}}[::1] X_data = np.asarray( + X.data, dtype={{INPUT_DTYPE}}, + ) + const int32_t[::1] X_indices = np.asarray( + X.indices, dtype=np.int32, + ) + const int32_t[::1] X_indptr = np.asarray( + X.indptr, dtype=np.int32, + ) + + const {{INPUT_DTYPE_t}}[:, ::1] Y_data = np.asarray( + Y, dtype={{INPUT_DTYPE}}, order="C", + ) + intp_t n_Y = Y_data.shape[0] + const int32_t[::1] Y_indices = ( + np.arange(n_features, dtype=np.int32) + ) + + {{INPUT_DTYPE_t}}[:, ::1] Darr = np.empty((n_X, n_Y), dtype={{INPUT_DTYPE}}, order='C') + + intp_t i1, i2 + intp_t x1_start, x1_end + {{INPUT_DTYPE_t}} * x2_data + + with nogil: + # Use the exact same adaptation for CSR than in SparseDenseDatasetsPair + # for supporting the sparse-dense case with minimal overhead. + # Note: at this point this method is only a convenience method + # used in the tests via the DistanceMetric.pairwise method. + # Therefore, there is no need to attempt parallelization of those + # nested for-loops. + # Efficient parallel computation of pairwise distances can be + # achieved via the PairwiseDistances class instead. The latter + # internally calls into vector-wise distance computation from + # the DistanceMetric subclass while benefiting from the generic + # Cython/OpenMP parallelization template for the generic pairwise + # distance + reduction computational pattern. + for i1 in range(n_X): + x1_start = X_indptr[i1] + x1_end = X_indptr[i1 + 1] + for i2 in range(n_Y): + x2_data = &Y_data[0, 0] + i2 * n_features + + Darr[i1, i2] = self.dist_csr( + x1_data=&X_data[0], + x1_indices=&X_indices[0], + x2_data=x2_data, + x2_indices=&Y_indices[0], + x1_start=x1_start, + x1_end=x1_end, + x2_start=0, + x2_end=n_features, + size=n_features, + ) + + return np.asarray(Darr) + + def _pairwise_dense_sparse(self, X, Y: csr_matrix): + # We could have implemented this method using _pairwise_dense_sparse by + # swapping argument and by transposing the results, but this would + # have come with an extra copy to ensure C-contiguity of the result. + cdef: + intp_t n_X = X.shape[0] + intp_t n_features = X.shape[1] + + const {{INPUT_DTYPE_t}}[:, ::1] X_data = np.asarray( + X, dtype={{INPUT_DTYPE}}, order="C", + ) + const int32_t[::1] X_indices = np.arange( + n_features, dtype=np.int32, + ) + + intp_t n_Y = Y.shape[0] + const {{INPUT_DTYPE_t}}[::1] Y_data = np.asarray( + Y.data, dtype={{INPUT_DTYPE}}, + ) + const int32_t[::1] Y_indices = np.asarray( + Y.indices, dtype=np.int32, + ) + const int32_t[::1] Y_indptr = np.asarray( + Y.indptr, dtype=np.int32, + ) + + {{INPUT_DTYPE_t}}[:, ::1] Darr = np.empty((n_X, n_Y), dtype={{INPUT_DTYPE}}, order='C') + + intp_t i1, i2 + {{INPUT_DTYPE_t}} * x1_data + + intp_t x2_start, x2_end + + with nogil: + # Use the exact same adaptation for CSR than in SparseDenseDatasetsPair + # for supporting the dense-sparse case with minimal overhead. + # Note: at this point this method is only a convenience method + # used in the tests via the DistanceMetric.pairwise method. + # Therefore, there is no need to attempt parallelization of those + # nested for-loops. + # Efficient parallel computation of pairwise distances can be + # achieved via the PairwiseDistances class instead. The latter + # internally calls into vector-wise distance computation from + # the DistanceMetric subclass while benefiting from the generic + # Cython/OpenMP parallelization template for the generic pairwise + # distance + reduction computational pattern. + for i1 in range(n_X): + x1_data = &X_data[0, 0] + i1 * n_features + for i2 in range(n_Y): + x2_start = Y_indptr[i2] + x2_end = Y_indptr[i2 + 1] + + Darr[i1, i2] = self.dist_csr( + x1_data=x1_data, + x1_indices=&X_indices[0], + x2_data=&Y_data[0], + x2_indices=&Y_indices[0], + x1_start=0, + x1_end=n_features, + x2_start=x2_start, + x2_end=x2_end, + size=n_features, + ) + + return np.asarray(Darr) + + + def pairwise(self, X, Y=None): + """Compute the pairwise distances between X and Y + + This is a convenience routine for the sake of testing. For many + metrics, the utilities in scipy.spatial.distance.cdist and + scipy.spatial.distance.pdist will be faster. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + If not specified, then Y=X. + + Returns + ------- + dist : ndarray of shape (n_samples_X, n_samples_Y) + The distance matrix of pairwise distances between points in X and Y. + """ + X = check_array(X, accept_sparse=['csr']) + + if Y is None: + Y = X + else: + Y = check_array(Y, accept_sparse=['csr']) + + X_is_sparse = issparse(X) + Y_is_sparse = issparse(Y) + + if not X_is_sparse and not Y_is_sparse: + return self._pairwise_dense_dense(X, Y) + + if X_is_sparse and Y_is_sparse: + return self._pairwise_sparse_sparse(X, Y) + + if X_is_sparse and not Y_is_sparse: + return self._pairwise_sparse_dense(X, Y) + + return self._pairwise_dense_sparse(X, Y) + +#------------------------------------------------------------ +# Euclidean Distance +# d = sqrt(sum(x_i^2 - y_i^2)) +cdef class EuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Euclidean Distance metric + + .. math:: + D(x, y) = \sqrt{ \sum_i (x_i - y_i) ^ 2 } + """ + def __init__(self): + self.p = 2 + + cdef inline {{INPUT_DTYPE_t}} dist(self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return euclidean_dist{{name_suffix}}(x1, x2, size) + + cdef inline {{INPUT_DTYPE_t}} rdist(self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return euclidean_rdist{{name_suffix}}(x1, x2, size) + + cdef inline {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + return sqrt(rdist) + + cdef inline {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + cdef inline {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + float64_t unsquared = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + unsquared = x1_data[i1] - x2_data[i2] + d = d + (unsquared * unsquared) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + unsquared = x1_data[i1] + d = d + (unsquared * unsquared) + i1 = i1 + 1 + else: + unsquared = x2_data[i2] + d = d + (unsquared * unsquared) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + unsquared = x2_data[i2] + d = d + (unsquared * unsquared) + i2 = i2 + 1 + else: + while i1 < x1_end: + unsquared = x1_data[i1] + d = d + (unsquared * unsquared) + i1 = i1 + 1 + + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + return sqrt( + self.rdist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + )) + +#------------------------------------------------------------ +# SEuclidean Distance +# d = sqrt(sum((x_i - y_i2)^2 / v_i)) +cdef class SEuclideanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Standardized Euclidean Distance metric + + .. math:: + D(x, y) = \sqrt{ \sum_i \frac{ (x_i - y_i) ^ 2}{V_i} } + """ + def __init__(self, V): + self.vec = np.asarray(V, dtype=np.float64) + self.size = self.vec.shape[0] + self.p = 2 + + def _validate_data(self, X): + if X.shape[1] != self.size: + raise ValueError('SEuclidean dist: size of V does not match') + + cdef inline {{INPUT_DTYPE_t}} rdist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t tmp, d=0 + cdef intp_t j + for j in range(size): + tmp = x1[j] - x2[j] + d += (tmp * tmp / self.vec[j]) + return d + + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return sqrt(self.rdist(x1, x2, size)) + + cdef inline {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + return sqrt(rdist) + + cdef inline {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + cdef inline {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + float64_t unsquared = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + unsquared = x1_data[i1] - x2_data[i2] + d = d + (unsquared * unsquared) / self.vec[ix1] + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + unsquared = x1_data[i1] + d = d + (unsquared * unsquared) / self.vec[ix1] + i1 = i1 + 1 + else: + unsquared = x2_data[i2] + d = d + (unsquared * unsquared) / self.vec[ix2] + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + ix2 = x2_indices[i2] + unsquared = x2_data[i2] + d = d + (unsquared * unsquared) / self.vec[ix2] + i2 = i2 + 1 + else: + while i1 < x1_end: + ix1 = x1_indices[i1] + unsquared = x1_data[i1] + d = d + (unsquared * unsquared) / self.vec[ix1] + i1 = i1 + 1 + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + return sqrt( + self.rdist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + )) + +#------------------------------------------------------------ +# Manhattan Distance +# d = sum(abs(x_i - y_i)) +cdef class ManhattanDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Manhattan/City-block Distance metric + + .. math:: + D(x, y) = \sum_i |x_i - y_i| + """ + def __init__(self): + self.p = 1 + + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t d = 0 + cdef intp_t j + for j in range(size): + d += fabs(x1[j] - x2[j]) + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + {{INPUT_DTYPE_t}} d = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d = d + fabs(x1_data[i1] - x2_data[i2]) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d = d + fabs(x1_data[i1]) + i1 = i1 + 1 + else: + d = d + fabs(x2_data[i2]) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + d = d + fabs(x2_data[i2]) + i2 = i2 + 1 + else: + while i1 < x1_end: + d = d + fabs(x1_data[i1]) + i1 = i1 + 1 + + return d + + +#------------------------------------------------------------ +# Chebyshev Distance +# d = max_i(abs(x_i - y_i)) +cdef class ChebyshevDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + """Chebyshev/Infinity Distance + + .. math:: + D(x, y) = max_i (|x_i - y_i|) + + Examples + -------- + >>> from sklearn.metrics.dist_metrics import DistanceMetric + >>> dist = DistanceMetric.get_metric('chebyshev') + >>> X = [[0, 1, 2], + ... [3, 4, 5]] + >>> Y = [[-1, 0, 1], + ... [3, 4, 5]] + >>> dist.pairwise(X, Y) + array([[1.732..., 5.196...], + [6.928..., 0.... ]]) + """ + def __init__(self): + self.p = INF{{name_suffix}} + + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t d = 0 + cdef intp_t j + for j in range(size): + d = fmax(d, fabs(x1[j] - x2[j])) + return d + + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d = fmax(d, fabs(x1_data[i1] - x2_data[i2])) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d = fmax(d, fabs(x1_data[i1])) + i1 = i1 + 1 + else: + d = fmax(d, fabs(x2_data[i2])) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + d = fmax(d, fabs(x2_data[i2])) + i2 = i2 + 1 + else: + while i1 < x1_end: + d = fmax(d, fabs(x1_data[i1])) + i1 = i1 + 1 + + return d + + +#------------------------------------------------------------ +# Minkowski Distance +cdef class MinkowskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Minkowski Distance + + .. math:: + D(x, y) = {||u-v||}_p + + when w is None. + + Here is the more general expanded expression for the weighted case: + + .. math:: + D(x, y) = [\sum_i w_i *|x_i - y_i|^p] ^ (1/p) + + Parameters + ---------- + p : float + The order of the p-norm of the difference (see above). + + .. versionchanged:: 1.4.0 + Minkowski distance allows `p` to be `0 0 and finite. + When :math:`p \in (0,1)`, it isn't a true metric but is permissible when + the triangular inequality isn't necessary. + For p = infinity, use ChebyshevDistance. + Note that for p=1, ManhattanDistance is more efficient, and for + p=2, EuclideanDistance is more efficient. + + """ + def __init__(self, p, w=None): + if p <= 0: + raise ValueError("p must be greater than 0") + elif np.isinf(p): + raise ValueError("MinkowskiDistance requires finite p. " + "For p=inf, use ChebyshevDistance.") + + self.p = p + if w is not None: + w_array = check_array( + w, ensure_2d=False, dtype=np.float64, input_name="w" + ) + if (w_array < 0).any(): + raise ValueError("w cannot contain negative weights") + self.vec = w_array + self.size = self.vec.shape[0] + else: + self.vec = np.asarray([], dtype=np.float64) + self.size = 0 + + def _validate_data(self, X): + if self.size > 0 and X.shape[1] != self.size: + raise ValueError("MinkowskiDistance: the size of w must match " + f"the number of features ({X.shape[1]}). " + f"Currently len(w)={self.size}.") + + cdef inline {{INPUT_DTYPE_t}} rdist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t d=0 + cdef intp_t j + cdef bint has_w = self.size > 0 + if has_w: + for j in range(size): + d += (self.vec[j] * pow(fabs(x1[j] - x2[j]), self.p)) + else: + for j in range(size): + d += (pow(fabs(x1[j] - x2[j]), self.p)) + return d + + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return pow(self.rdist(x1, x2, size), 1. / self.p) + + cdef inline {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + return pow(rdist, 1. / self.p) + + cdef inline {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + return pow(dist, self.p) + + def rdist_to_dist(self, rdist): + return rdist ** (1. / self.p) + + def dist_to_rdist(self, dist): + return dist ** self.p + + cdef inline {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + bint has_w = self.size > 0 + + if has_w: + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d = d + (self.vec[ix1] * pow(fabs( + x1_data[i1] - x2_data[i2] + ), self.p)) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d = d + (self.vec[ix1] * pow(fabs(x1_data[i1]), self.p)) + i1 = i1 + 1 + else: + d = d + (self.vec[ix2] * pow(fabs(x2_data[i2]), self.p)) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + ix2 = x2_indices[i2] + d = d + (self.vec[ix2] * pow(fabs(x2_data[i2]), self.p)) + i2 = i2 + 1 + else: + while i1 < x1_end: + ix1 = x1_indices[i1] + d = d + (self.vec[ix1] * pow(fabs(x1_data[i1]), self.p)) + i1 = i1 + 1 + + return d + else: + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d = d + (pow(fabs( + x1_data[i1] - x2_data[i2] + ), self.p)) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d = d + (pow(fabs(x1_data[i1]), self.p)) + i1 = i1 + 1 + else: + d = d + (pow(fabs(x2_data[i2]), self.p)) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + d = d + (pow(fabs(x2_data[i2]), self.p)) + i2 = i2 + 1 + else: + while i1 < x1_end: + d = d + (pow(fabs(x1_data[i1]), self.p)) + i1 = i1 + 1 + + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + return pow( + self.rdist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + ), + 1 / self.p + ) + +#------------------------------------------------------------ +# Mahalanobis Distance +# d = sqrt( (x - y)^T V^-1 (x - y) ) +cdef class MahalanobisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + """Mahalanobis Distance + + .. math:: + D(x, y) = \sqrt{ (x - y)^T V^{-1} (x - y) } + + Parameters + ---------- + V : array-like + Symmetric positive-definite covariance matrix. + The inverse of this matrix will be explicitly computed. + VI : array-like + optionally specify the inverse directly. If VI is passed, + then V is not referenced. + """ + cdef float64_t[::1] buffer + + def __init__(self, V=None, VI=None): + if VI is None: + if V is None: + raise ValueError("Must provide either V or VI " + "for Mahalanobis distance") + VI = np.linalg.inv(V) + if VI.ndim != 2 or VI.shape[0] != VI.shape[1]: + raise ValueError("V/VI must be square") + + self.mat = np.asarray(VI, dtype=np.float64, order='C') + + self.size = self.mat.shape[0] + + # We need to create a buffer to store the vectors' coordinates' differences + self.buffer = np.zeros(self.size, dtype=np.float64) + + def __setstate__(self, state): + super().__setstate__(state) + self.size = self.mat.shape[0] + self.buffer = np.zeros(self.size, dtype=np.float64) + + def _validate_data(self, X): + if X.shape[1] != self.size: + raise ValueError('Mahalanobis dist: size of V does not match') + + cdef inline {{INPUT_DTYPE_t}} rdist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t tmp, d = 0 + cdef intp_t i, j + + # compute (x1 - x2).T * VI * (x1 - x2) + for i in range(size): + self.buffer[i] = x1[i] - x2[i] + + for i in range(size): + tmp = 0 + for j in range(size): + tmp += self.mat[i, j] * self.buffer[j] + d += tmp * self.buffer[i] + return d + + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return sqrt(self.rdist(x1, x2, size)) + + cdef inline {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + return sqrt(rdist) + + cdef inline {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + return dist * dist + + def rdist_to_dist(self, rdist): + return np.sqrt(rdist) + + def dist_to_rdist(self, dist): + return dist ** 2 + + cdef inline {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t tmp, d = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + self.buffer[ix1] = x1_data[i1] - x2_data[i2] + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + self.buffer[ix1] = x1_data[i1] + i1 = i1 + 1 + else: + self.buffer[ix2] = - x2_data[i2] + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + ix2 = x2_indices[i2] + self.buffer[ix2] = - x2_data[i2] + i2 = i2 + 1 + else: + while i1 < x1_end: + ix1 = x1_indices[i1] + self.buffer[ix1] = x1_data[i1] + i1 = i1 + 1 + + for i in range(size): + tmp = 0 + for j in range(size): + tmp += self.mat[i, j] * self.buffer[j] + d += tmp * self.buffer[i] + + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + return sqrt( + self.rdist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + )) + +#------------------------------------------------------------ +# Hamming Distance +# d = N_unequal(x, y) / N_tot +cdef class HammingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Hamming Distance + + Hamming distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \frac{1}{N} \sum_i \delta_{x_i, y_i} + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int n_unequal = 0 + cdef intp_t j + for j in range(size): + if x1[j] != x2[j]: + n_unequal += 1 + return float(n_unequal) / size + + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d += (x1_data[i1] != x2_data[i2]) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d += (x1_data[i1] != 0) + i1 = i1 + 1 + else: + d += (x2_data[i2] != 0) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + d += (x2_data[i2] != 0) + i2 = i2 + 1 + else: + while i1 < x1_end: + d += (x1_data[i1] != 0) + i1 = i1 + 1 + + d /= size + + return d + + +#------------------------------------------------------------ +# Canberra Distance +# D(x, y) = sum[ abs(x_i - y_i) / (abs(x_i) + abs(y_i)) ] +cdef class CanberraDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Canberra Distance + + Canberra distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \sum_i \frac{|x_i - y_i|}{|x_i| + |y_i|} + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t denom, d = 0 + cdef intp_t j + for j in range(size): + denom = fabs(x1[j]) + fabs(x2[j]) + if denom > 0: + d += fabs(x1[j] - x2[j]) / denom + return d + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t d = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + d += ( + fabs(x1_data[i1] - x2_data[i2]) / + (fabs(x1_data[i1]) + fabs(x2_data[i2])) + ) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + d += 1. + i1 = i1 + 1 + else: + d += 1. + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + d += 1. + i2 = i2 + 1 + else: + while i1 < x1_end: + d += 1. + i1 = i1 + 1 + + return d + +#------------------------------------------------------------ +# Bray-Curtis Distance +# D(x, y) = sum[abs(x_i - y_i)] / sum[abs(x_i) + abs(y_i)] +cdef class BrayCurtisDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Bray-Curtis Distance + + Bray-Curtis distance is meant for discrete-valued vectors, though it is + a valid metric for real-valued vectors. + + .. math:: + D(x, y) = \frac{\sum_i |x_i - y_i|}{\sum_i(|x_i| + |y_i|)} + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t num = 0, denom = 0 + cdef intp_t j + for j in range(size): + num += fabs(x1[j] - x2[j]) + denom += fabs(x1[j]) + fabs(x2[j]) + if denom > 0: + return num / denom + else: + return 0.0 + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t num = 0.0 + float64_t denom = 0.0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + num += fabs(x1_data[i1] - x2_data[i2]) + denom += fabs(x1_data[i1]) + fabs(x2_data[i2]) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + num += fabs(x1_data[i1]) + denom += fabs(x1_data[i1]) + i1 = i1 + 1 + else: + num += fabs(x2_data[i2]) + denom += fabs(x2_data[i2]) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + num += fabs(x1_data[i1]) + denom += fabs(x1_data[i1]) + i2 = i2 + 1 + else: + while i1 < x1_end: + num += fabs(x2_data[i2]) + denom += fabs(x2_data[i2]) + i1 = i1 + 1 + + return num / denom + +#------------------------------------------------------------ +# Jaccard Distance (boolean) +# D(x, y) = N_unequal(x, y) / N_nonzero(x, y) +cdef class JaccardDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Jaccard Distance + + Jaccard Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = (N_TF + N_FT) / (N_TT + N_TF + N_FT) + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_eq = 0, nnz = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + nnz += (tf1 or tf2) + n_eq += (tf1 and tf2) + # Based on https://github.com/scipy/scipy/pull/7373 + # When comparing two all-zero vectors, scipy>=1.2.0 jaccard metric + # was changed to return 0, instead of nan. + if nnz == 0: + return 0 + return (nnz - n_eq) * 1.0 / nnz + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_tt = 0, nnz = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + nnz += (tf1 or tf2) + n_tt += (tf1 and tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + nnz += tf1 + i1 = i1 + 1 + else: + nnz += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + nnz += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + nnz += tf1 + i1 = i1 + 1 + + # Based on https://github.com/scipy/scipy/pull/7373 + # When comparing two all-zero vectors, scipy>=1.2.0 jaccard metric + # was changed to return 0, instead of nan. + if nnz == 0: + return 0 + return (nnz - n_tt) * 1.0 / nnz + +#------------------------------------------------------------ +# Matching Distance (boolean) +# D(x, y) = n_neq / n +cdef class MatchingDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Matching Distance + + Matching Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = (N_TF + N_FT) / N + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_neq = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return n_neq * 1. / size + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + if ix1 == ix2: + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += (x1_data[i1] != 0) + i1 = i1 + 1 + else: + n_neq += (x2_data[i2] != 0) + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + n_neq += (x2_data[i2] != 0) + i2 = i2 + 1 + else: + while i1 < x1_end: + n_neq += (x1_data[i1] != 0) + i1 = i1 + 1 + + return n_neq * 1.0 / size + +#------------------------------------------------------------ +# Dice Distance (boolean) +# D(x, y) = n_neq / (2 * ntt + n_neq) +cdef class DiceDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Dice Distance + + Dice Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = (N_TF + N_FT) / (2 * N_TT + N_TF + N_FT) + + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_neq = 0, n_tt = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_tt += (tf1 and tf2) + n_neq += (tf1 != tf2) + return n_neq / (2.0 * n_tt + n_neq) + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_tt = 0, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_tt += (tf1 and tf2) + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += tf1 + i1 = i1 + 1 + else: + n_neq += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + n_neq += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + n_neq += tf1 + i1 = i1 + 1 + + return n_neq / (2.0 * n_tt + n_neq) + + +#------------------------------------------------------------ +# Kulsinski Distance (boolean) +# D(x, y) = (ntf + nft - ntt + n) / (n_neq + n) +cdef class KulsinskiDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Kulsinski Distance + + Kulsinski Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = 1 - N_TT / (N + N_TF + N_FT) + + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_tt = 0, n_neq = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + n_tt += (tf1 and tf2) + return (n_neq - n_tt + size) * 1.0 / (n_neq + size) + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_tt = 0, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_tt += (tf1 and tf2) + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += tf1 + i1 = i1 + 1 + else: + n_neq += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + n_neq += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + n_neq += tf1 + i1 = i1 + 1 + + return (n_neq - n_tt + size) * 1.0 / (n_neq + size) + +#------------------------------------------------------------ +# Rogers-Tanimoto Distance (boolean) +# D(x, y) = 2 * n_neq / (n + n_neq) +cdef class RogersTanimotoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Rogers-Tanimoto Distance + + Rogers-Tanimoto Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = 2 (N_TF + N_FT) / (N + N_TF + N_FT) + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_neq = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return (2.0 * n_neq) / (size + n_neq) + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += tf1 + i1 = i1 + 1 + else: + n_neq += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + n_neq += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + n_neq += tf1 + i1 = i1 + 1 + + return (2.0 * n_neq) / (size + n_neq) + +#------------------------------------------------------------ +# Russell-Rao Distance (boolean) +# D(x, y) = (n - ntt) / n +cdef class RussellRaoDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Russell-Rao Distance + + Russell-Rao Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = (N - N_TT) / N + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_tt = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_tt += (tf1 and tf2) + return (size - n_tt) * 1. / size + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_tt = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_tt += (tf1 and tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + i1 = i1 + 1 + else: + i2 = i2 + 1 + + # We don't need to go through all the longest + # vector because tf1 or tf2 will be false + # and thus n_tt won't be increased. + + return (size - n_tt) * 1. / size + + + +#------------------------------------------------------------ +# Sokal-Michener Distance (boolean) +# D(x, y) = 2 * n_neq / (n + n_neq) +cdef class SokalMichenerDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Sokal-Michener Distance + + Sokal-Michener Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = 2 (N_TF + N_FT) / (N + N_TF + N_FT) + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_neq = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + return (2.0 * n_neq) / (size + n_neq) + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += tf1 + i1 = i1 + 1 + else: + n_neq += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + n_neq += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + n_neq += tf1 + i1 = i1 + 1 + + return (2.0 * n_neq) / (size + n_neq) + +#------------------------------------------------------------ +# Sokal-Sneath Distance (boolean) +# D(x, y) = n_neq / (0.5 * n_tt + n_neq) +cdef class SokalSneathDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + r"""Sokal-Sneath Distance + + Sokal-Sneath Distance is a dissimilarity measure for boolean-valued + vectors. All nonzero entries will be treated as True, zero entries will + be treated as False. + + D(x, y) = (N_TF + N_FT) / (N_TT / 2 + N_FT + N_TF) + """ + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef int tf1, tf2, n_tt = 0, n_neq = 0 + cdef intp_t j + for j in range(size): + tf1 = x1[j] != 0 + tf2 = x2[j] != 0 + n_neq += (tf1 != tf2) + n_tt += (tf1 and tf2) + return n_neq / (0.5 * n_tt + n_neq) + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + intp_t tf1, tf2, n_tt = 0, n_neq = 0 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + tf1 = x1_data[i1] != 0 + tf2 = x2_data[i2] != 0 + + if ix1 == ix2: + n_tt += (tf1 and tf2) + n_neq += (tf1 != tf2) + i1 = i1 + 1 + i2 = i2 + 1 + elif ix1 < ix2: + n_neq += tf1 + i1 = i1 + 1 + else: + n_neq += tf2 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + tf2 = x2_data[i2] != 0 + n_neq += tf2 + i2 = i2 + 1 + else: + while i1 < x1_end: + tf1 = x1_data[i1] != 0 + n_neq += tf1 + i1 = i1 + 1 + + return n_neq / (0.5 * n_tt + n_neq) + + +#------------------------------------------------------------ +# Haversine Distance (2 dimensional) +# D(x, y) = 2 arcsin{sqrt[sin^2 ((x1 - y1) / 2) +# + cos(x1) cos(y1) sin^2 ((x2 - y2) / 2)]} +cdef class HaversineDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + """Haversine (Spherical) Distance + + The Haversine distance is the angular distance between two points on + the surface of a sphere. The first distance of each point is assumed + to be the latitude, the second is the longitude, given in radians. + The dimension of the points must be 2: + + D(x, y) = 2 arcsin[sqrt{sin^2((x1 - y1) / 2) + cos(x1)cos(y1)sin^2((x2 - y2) / 2)}] + + """ + + def _validate_data(self, X): + if X.shape[1] != 2: + raise ValueError("Haversine distance only valid " + "in 2 dimensions") + + cdef inline {{INPUT_DTYPE_t}} rdist(self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + cdef float64_t sin_0 = sin(0.5 * ((x1[0]) - (x2[0]))) + cdef float64_t sin_1 = sin(0.5 * ((x1[1]) - (x2[1]))) + return (sin_0 * sin_0 + cos(x1[0]) * cos(x2[0]) * sin_1 * sin_1) + + cdef inline {{INPUT_DTYPE_t}} dist(self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return 2 * asin(sqrt(self.rdist(x1, x2, size))) + + cdef inline {{INPUT_DTYPE_t}} _rdist_to_dist(self, {{INPUT_DTYPE_t}} rdist) except -1 nogil: + return 2 * asin(sqrt(rdist)) + + cdef inline {{INPUT_DTYPE_t}} _dist_to_rdist(self, {{INPUT_DTYPE_t}} dist) except -1 nogil: + cdef float64_t tmp = sin(0.5 * dist) + return tmp * tmp + + def rdist_to_dist(self, rdist): + return 2 * np.arcsin(np.sqrt(rdist)) + + def dist_to_rdist(self, dist): + tmp = np.sin(0.5 * dist) + return tmp * tmp + + cdef inline {{INPUT_DTYPE_t}} dist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + return 2 * asin(sqrt(self.rdist_csr( + x1_data, + x1_indices, + x2_data, + x2_indices, + x1_start, + x1_end, + x2_start, + x2_end, + size, + ))) + + cdef inline {{INPUT_DTYPE_t}} rdist_csr( + self, + const {{INPUT_DTYPE_t}}* x1_data, + const int32_t* x1_indices, + const {{INPUT_DTYPE_t}}* x2_data, + const int32_t* x2_indices, + const int32_t x1_start, + const int32_t x1_end, + const int32_t x2_start, + const int32_t x2_end, + const intp_t size, + ) except -1 nogil: + + cdef: + intp_t ix1, ix2 + intp_t i1 = x1_start + intp_t i2 = x2_start + + float64_t x1_0 = 0 + float64_t x1_1 = 0 + float64_t x2_0 = 0 + float64_t x2_1 = 0 + float64_t sin_0 + float64_t sin_1 + + while i1 < x1_end and i2 < x2_end: + ix1 = x1_indices[i1] + ix2 = x2_indices[i2] + + # Find the components in the 2D vectors to work with + x1_component = ix1 if (x1_start == 0) else ix1 % x1_start + x2_component = ix2 if (x2_start == 0) else ix2 % x2_start + + if x1_component == 0: + x1_0 = x1_data[i1] + else: + x1_1 = x1_data[i1] + + if x2_component == 0: + x2_0 = x2_data[i2] + else: + x2_1 = x2_data[i2] + + i1 = i1 + 1 + i2 = i2 + 1 + + if i1 == x1_end: + while i2 < x2_end: + ix2 = x2_indices[i2] + x2_component = ix2 if (x2_start == 0) else ix2 % x2_start + if x2_component == 0: + x2_0 = x2_data[i2] + else: + x2_1 = x2_data[i2] + i2 = i2 + 1 + else: + while i1 < x1_end: + ix1 = x1_indices[i1] + x1_component = ix1 if (x1_start == 0) else ix1 % x1_start + if x1_component == 0: + x1_0 = x1_data[i1] + else: + x1_1 = x1_data[i1] + i1 = i1 + 1 + + sin_0 = sin(0.5 * (x1_0 - x2_0)) + sin_1 = sin(0.5 * (x1_1 - x2_1)) + + return (sin_0 * sin_0 + cos(x1_0) * cos(x2_0) * sin_1 * sin_1) + +#------------------------------------------------------------ +# User-defined distance +# +cdef class PyFuncDistance{{name_suffix}}(DistanceMetric{{name_suffix}}): + """PyFunc Distance + + A user-defined distance + + Parameters + ---------- + func : function + func should take two numpy arrays as input, and return a distance. + """ + def __init__(self, func, **kwargs): + self.func = func + self.kwargs = kwargs + + # in cython < 0.26, GIL was required to be acquired during definition of + # the function and inside the body of the function. This behaviour is not + # allowed in cython >= 0.26 since it is a redundant GIL acquisition. The + # only way to be back compatible is to inherit `dist` from the base class + # without GIL and called an inline `_dist` which acquire GIL. + cdef inline {{INPUT_DTYPE_t}} dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 nogil: + return self._dist(x1, x2, size) + + cdef inline {{INPUT_DTYPE_t}} _dist( + self, + const {{INPUT_DTYPE_t}}* x1, + const {{INPUT_DTYPE_t}}* x2, + intp_t size, + ) except -1 with gil: + cdef: + object x1arr = _buffer_to_ndarray{{name_suffix}}(x1, size) + object x2arr = _buffer_to_ndarray{{name_suffix}}(x2, size) + d = self.func(x1arr, x2arr, **self.kwargs) + try: + # Cython generates code here that results in a TypeError + # if d is the wrong type. + return d + except TypeError: + raise TypeError("Custom distance function must accept two " + "vectors and return a float.") + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6b532e0fa8ff07a27111f86d2ccc36b8d48879b5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/__init__.py @@ -0,0 +1,112 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +# +# Pairwise Distances Reductions +# ============================= +# +# Overview +# -------- +# +# This module provides routines to compute pairwise distances between a set +# of row vectors of X and another set of row vectors of Y and apply a +# reduction on top. The canonical example is the brute-force computation +# of the top k nearest neighbors by leveraging the arg-k-min reduction. +# +# The reduction takes a matrix of pairwise distances between rows of X and Y +# as input and outputs an aggregate data-structure for each row of X. The +# aggregate values are typically smaller than the number of rows in Y, hence +# the term reduction. +# +# For computational reasons, the reduction are performed on the fly on chunks +# of rows of X and Y so as to keep intermediate data-structures in CPU cache +# and avoid unnecessary round trips of large distance arrays with the RAM +# that would otherwise severely degrade the speed by making the overall +# processing memory-bound. +# +# Finally, the routines follow a generic parallelization template to process +# chunks of data with OpenMP loops (via Cython prange), either on rows of X +# or rows of Y depending on their respective sizes. +# +# +# Dispatching to specialized implementations +# ------------------------------------------ +# +# Dispatchers are meant to be used in the Python code. Under the hood, a +# dispatcher must only define the logic to choose at runtime to the correct +# dtype-specialized :class:`BaseDistancesReductionDispatcher` implementation based +# on the dtype of X and of Y. +# +# +# High-level diagram +# ------------------ +# +# Legend: +# +# A ---⊳ B: A inherits from B +# A ---x B: A dispatches to B +# +# +# (base dispatcher) +# BaseDistancesReductionDispatcher +# ∆ +# | +# | +# +------------------+---------------+---------------+------------------+ +# | | | | +# | (dispatcher) (dispatcher) | +# | ArgKmin RadiusNeighbors | +# | | | | +# | | | | +# | | (float{32,64} implem.) | | +# | | BaseDistancesReduction{32,64} | | +# | | ∆ | | +# (dispatcher) | | | (dispatcher) +# ArgKminClassMode | | | RadiusNeighborsClassMode +# | | +----------+----------+ | | +# | | | | | | +# | | | | | | +# | x | | x | +# | +-------⊳ ArgKmin{32,64} RadiusNeighbors{32,64} ⊲---+ | +# x | | ∆ ∆ | | x +# ArgKminClassMode{32,64} | | | | RadiusNeighborsClassMode{32,64} +# ===================================== Specializations ============================================ +# | | | | +# | | | | +# x | | x +# EuclideanArgKmin{32,64} EuclideanRadiusNeighbors{32,64} +# +# +# For instance :class:`ArgKmin` dispatches to: +# - :class:`ArgKmin64` if X and Y are two `float64` array-likes +# - :class:`ArgKmin32` if X and Y are two `float32` array-likes +# +# In addition, if the metric parameter is set to "euclidean" or "sqeuclidean", +# then some direct subclass of `BaseDistancesReduction{32,64}` further dispatches +# to one of their subclass for euclidean-specialized implementation. For instance, +# :class:`ArgKmin64` dispatches to :class:`EuclideanArgKmin64`. +# +# Those Euclidean-specialized implementations relies on optimal implementations of +# a decomposition of the squared euclidean distance matrix into a sum of three terms +# (see :class:`MiddleTermComputer{32,64}`). +# + +from ._dispatcher import ( + ArgKmin, + ArgKminClassMode, + BaseDistancesReductionDispatcher, + RadiusNeighbors, + RadiusNeighborsClassMode, + sqeuclidean_row_norms, +) + +__all__ = [ + "ArgKmin", + "ArgKminClassMode", + "BaseDistancesReductionDispatcher", + "RadiusNeighbors", + "RadiusNeighborsClassMode", + "sqeuclidean_row_norms", +] + +# ruff: noqa: E501 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..f3a9ce96e64c00f2818b43d147baaa363d6895ee --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pxd.tp @@ -0,0 +1,31 @@ +from ...utils._typedefs cimport intp_t, float64_t + +{{for name_suffix in ['64', '32']}} + +from ._base cimport BaseDistancesReduction{{name_suffix}} +from ._middle_term_computer cimport MiddleTermComputer{{name_suffix}} + +cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): + """float{{name_suffix}} implementation of the ArgKmin.""" + + cdef: + intp_t k + + intp_t[:, ::1] argkmin_indices + float64_t[:, ::1] argkmin_distances + + # Used as array of pointers to private datastructures used in threads. + float64_t ** heaps_r_distances_chunks + intp_t ** heaps_indices_chunks + + +cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): + """EuclideanDistance-specialisation of ArgKmin{{name_suffix}}.""" + cdef: + MiddleTermComputer{{name_suffix}} middle_term_computer + const float64_t[::1] X_norm_squared + const float64_t[::1] Y_norm_squared + + bint use_squared_distances + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..c21717554e94b22d48558811534ecbc08fe6dc52 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.pyx.tp @@ -0,0 +1,512 @@ +from libc.stdlib cimport free, malloc +from libc.float cimport DBL_MAX +from cython cimport final +from cython.parallel cimport parallel, prange + +from ...utils._heap cimport heap_push +from ...utils._sorting cimport simultaneous_sort +from ...utils._typedefs cimport intp_t, float64_t + +import numpy as np +import warnings + +from numbers import Integral +from scipy.sparse import issparse +from ...utils import check_array, check_scalar +from ...utils.fixes import _in_unstable_openblas_configuration +from ...utils.parallel import _get_threadpool_controller + +{{for name_suffix in ['64', '32']}} + +from ._base cimport ( + BaseDistancesReduction{{name_suffix}}, + _sqeuclidean_row_norms{{name_suffix}}, +) + +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + +from ._middle_term_computer cimport MiddleTermComputer{{name_suffix}} + + +cdef class ArgKmin{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): + """float{{name_suffix}} implementation of the ArgKmin.""" + + @classmethod + def compute( + cls, + X, + Y, + intp_t k, + metric="euclidean", + chunk_size=None, + dict metric_kwargs=None, + str strategy=None, + bint return_distance=False, + ): + """Compute the argkmin reduction. + + This classmethod is responsible for introspecting the arguments + values to dispatch to the most appropriate implementation of + :class:`ArgKmin{{name_suffix}}`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + + No instance should directly be created outside of this class method. + """ + # Limit the number of threads in second level of nested parallelism for BLAS + # to avoid threads over-subscription (in DOT or GEMM for instance). + with _get_threadpool_controller().limit(limits=1, user_api='blas'): + if metric in ("euclidean", "sqeuclidean"): + # Specialized implementation of ArgKmin for the Euclidean distance + # for the dense-dense and sparse-sparse cases. + # This implementation computes the distances by chunk using + # a decomposition of the Squared Euclidean distance. + # This specialisation has an improved arithmetic intensity for both + # the dense and sparse settings, allowing in most case speed-ups of + # several orders of magnitude compared to the generic ArgKmin + # implementation. + # Note that squared norms of X and Y are precomputed in the + # constructor of this class by issuing BLAS calls that may use + # multithreading (depending on the BLAS implementation), hence calling + # the constructor needs to be protected under the threadpool_limits + # context, along with the main calls to _parallel_on_Y and + # _parallel_on_X. + # For more information see MiddleTermComputer. + use_squared_distances = metric == "sqeuclidean" + pda = EuclideanArgKmin{{name_suffix}}( + X=X, Y=Y, k=k, + use_squared_distances=use_squared_distances, + chunk_size=chunk_size, + strategy=strategy, + metric_kwargs=metric_kwargs, + ) + else: + # Fall back on a generic implementation that handles most scipy + # metrics by computing the distances between 2 vectors at a time. + pda = ArgKmin{{name_suffix}}( + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric, metric_kwargs), + k=k, + chunk_size=chunk_size, + strategy=strategy, + ) + + if pda.execute_in_parallel_on_Y: + pda._parallel_on_Y() + else: + pda._parallel_on_X() + + return pda._finalize_results(return_distance) + + def __init__( + self, + DatasetsPair{{name_suffix}} datasets_pair, + chunk_size=None, + strategy=None, + intp_t k=1, + ): + super().__init__( + datasets_pair=datasets_pair, + chunk_size=chunk_size, + strategy=strategy, + ) + self.k = check_scalar(k, "k", Integral, min_val=1) + + # Allocating pointers to datastructures but not the datastructures themselves. + # There are as many pointers as effective threads. + # + # For the sake of explicitness: + # - when parallelizing on X, the pointers of those heaps are referencing + # (with proper offsets) addresses of the two main heaps (see below) + # - when parallelizing on Y, the pointers of those heaps are referencing + # small heaps which are thread-wise-allocated and whose content will be + # merged with the main heaps'. + self.heaps_r_distances_chunks = malloc( + sizeof(float64_t *) * self.chunks_n_threads + ) + self.heaps_indices_chunks = malloc( + sizeof(intp_t *) * self.chunks_n_threads + ) + + # Main heaps which will be returned as results by `ArgKmin{{name_suffix}}.compute`. + self.argkmin_indices = np.full((self.n_samples_X, self.k), 0, dtype=np.intp) + self.argkmin_distances = np.full((self.n_samples_X, self.k), DBL_MAX, dtype=np.float64) + + def __dealloc__(self): + if self.heaps_indices_chunks is not NULL: + free(self.heaps_indices_chunks) + + if self.heaps_r_distances_chunks is not NULL: + free(self.heaps_r_distances_chunks) + + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + intp_t i, j + intp_t n_samples_X = X_end - X_start + intp_t n_samples_Y = Y_end - Y_start + float64_t *heaps_r_distances = self.heaps_r_distances_chunks[thread_num] + intp_t *heaps_indices = self.heaps_indices_chunks[thread_num] + + # Pushing the distances and their associated indices on a heap + # which by construction will keep track of the argkmin. + for i in range(n_samples_X): + for j in range(n_samples_Y): + heap_push( + values=heaps_r_distances + i * self.k, + indices=heaps_indices + i * self.k, + size=self.k, + val=self.datasets_pair.surrogate_dist(X_start + i, Y_start + j), + val_idx=Y_start + j, + ) + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + # As this strategy is embarrassingly parallel, we can set each + # thread's heaps pointer to the proper position on the main heaps. + self.heaps_r_distances_chunks[thread_num] = &self.argkmin_distances[X_start, 0] + self.heaps_indices_chunks[thread_num] = &self.argkmin_indices[X_start, 0] + + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + cdef: + intp_t idx + + # Sorting the main heaps portion associated to `X[X_start:X_end]` + # in ascending order w.r.t the distances. + for idx in range(X_end - X_start): + simultaneous_sort( + self.heaps_r_distances_chunks[thread_num] + idx * self.k, + self.heaps_indices_chunks[thread_num] + idx * self.k, + self.k + ) + + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil: + cdef: + # Maximum number of scalar elements (the last chunks can be smaller) + intp_t heaps_size = self.X_n_samples_chunk * self.k + intp_t thread_num + + # The allocation is done in parallel for data locality purposes: this way + # the heaps used in each threads are allocated in pages which are closer + # to the CPU core used by the thread. + # See comments about First Touch Placement Policy: + # https://www.openmp.org/wp-content/uploads/openmp-webinar-vanderPas-20210318.pdf #noqa + for thread_num in prange(self.chunks_n_threads, schedule='static', nogil=True, + num_threads=self.chunks_n_threads): + # As chunks of X are shared across threads, so must their + # heaps. To solve this, each thread has its own heaps + # which are then synchronised back in the main ones. + self.heaps_r_distances_chunks[thread_num] = malloc( + heaps_size * sizeof(float64_t) + ) + self.heaps_indices_chunks[thread_num] = malloc( + heaps_size * sizeof(intp_t) + ) + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + # Initialising heaps (memset can't be used here) + for idx in range(self.X_n_samples_chunk * self.k): + self.heaps_r_distances_chunks[thread_num][idx] = DBL_MAX + self.heaps_indices_chunks[thread_num][idx] = -1 + + @final + cdef void _parallel_on_Y_synchronize( + self, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + cdef: + intp_t idx, jdx, thread_num + with nogil, parallel(num_threads=self.effective_n_threads): + # Synchronising the thread heaps with the main heaps. + # This is done in parallel sample-wise (no need for locks). + # + # This might break each thread's data locality as each heap which + # was allocated in a thread is being now being used in several threads. + # + # Still, this parallel pattern has shown to be efficient in practice. + for idx in prange(X_end - X_start, schedule="static"): + for thread_num in range(self.chunks_n_threads): + for jdx in range(self.k): + heap_push( + values=&self.argkmin_distances[X_start + idx, 0], + indices=&self.argkmin_indices[X_start + idx, 0], + size=self.k, + val=self.heaps_r_distances_chunks[thread_num][idx * self.k + jdx], + val_idx=self.heaps_indices_chunks[thread_num][idx * self.k + jdx], + ) + + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil: + cdef: + intp_t idx, thread_num + + with nogil, parallel(num_threads=self.chunks_n_threads): + # Deallocating temporary datastructures + for thread_num in prange(self.chunks_n_threads, schedule='static'): + free(self.heaps_r_distances_chunks[thread_num]) + free(self.heaps_indices_chunks[thread_num]) + + # Sorting the main in ascending order w.r.t the distances. + # This is done in parallel sample-wise (no need for locks). + for idx in prange(self.n_samples_X, schedule='static'): + simultaneous_sort( + &self.argkmin_distances[idx, 0], + &self.argkmin_indices[idx, 0], + self.k, + ) + return + + cdef void compute_exact_distances(self) noexcept nogil: + cdef: + intp_t i, j + float64_t[:, ::1] distances = self.argkmin_distances + for i in prange(self.n_samples_X, schedule='static', nogil=True, + num_threads=self.effective_n_threads): + for j in range(self.k): + distances[i, j] = self.datasets_pair.distance_metric._rdist_to_dist( + # Guard against potential -0., causing nan production. + max(distances[i, j], 0.) + ) + + def _finalize_results(self, bint return_distance=False): + if return_distance: + # We need to recompute distances because we relied on + # surrogate distances for the reduction. + self.compute_exact_distances() + + # Values are returned identically to the way `KNeighborsMixin.kneighbors` + # returns values. This is counter-intuitive but this allows not using + # complex adaptations where `ArgKmin.compute` is called. + return np.asarray(self.argkmin_distances), np.asarray(self.argkmin_indices) + + return np.asarray(self.argkmin_indices) + + +cdef class EuclideanArgKmin{{name_suffix}}(ArgKmin{{name_suffix}}): + """EuclideanDistance-specialisation of ArgKmin{{name_suffix}}.""" + + @classmethod + def is_usable_for(cls, X, Y, metric) -> bool: + return (ArgKmin{{name_suffix}}.is_usable_for(X, Y, metric) and + not _in_unstable_openblas_configuration()) + + def __init__( + self, + X, + Y, + intp_t k, + bint use_squared_distances=False, + chunk_size=None, + strategy=None, + metric_kwargs=None, + ): + if ( + isinstance(metric_kwargs, dict) and + (metric_kwargs.keys() - {"X_norm_squared", "Y_norm_squared"}) + ): + warnings.warn( + f"Some metric_kwargs have been passed ({metric_kwargs}) but aren't " + f"usable for this case (EuclideanArgKmin64) and will be ignored.", + UserWarning, + stacklevel=3, + ) + + super().__init__( + # The datasets pair here is used for exact distances computations + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric="euclidean"), + chunk_size=chunk_size, + strategy=strategy, + k=k, + ) + cdef: + intp_t dist_middle_terms_chunks_size = self.Y_n_samples_chunk * self.X_n_samples_chunk + + self.middle_term_computer = MiddleTermComputer{{name_suffix}}.get_for( + X, + Y, + self.effective_n_threads, + self.chunks_n_threads, + dist_middle_terms_chunks_size, + n_features=X.shape[1], + chunk_size=self.chunk_size, + ) + + if metric_kwargs is not None and "Y_norm_squared" in metric_kwargs: + self.Y_norm_squared = check_array( + metric_kwargs.pop("Y_norm_squared"), + ensure_2d=False, + input_name="Y_norm_squared", + dtype=np.float64, + ) + else: + self.Y_norm_squared = _sqeuclidean_row_norms{{name_suffix}}( + Y, + self.effective_n_threads, + ) + + if metric_kwargs is not None and "X_norm_squared" in metric_kwargs: + self.X_norm_squared = check_array( + metric_kwargs.pop("X_norm_squared"), + ensure_2d=False, + input_name="X_norm_squared", + dtype=np.float64, + ) + else: + # Do not recompute norms if datasets are identical. + self.X_norm_squared = ( + self.Y_norm_squared if X is Y else + _sqeuclidean_row_norms{{name_suffix}}( + X, + self.effective_n_threads, + ) + ) + + self.use_squared_distances = use_squared_distances + + @final + cdef void compute_exact_distances(self) noexcept nogil: + if not self.use_squared_distances: + ArgKmin{{name_suffix}}.compute_exact_distances(self) + + @final + cdef void _parallel_on_X_parallel_init( + self, + intp_t thread_num, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_X_parallel_init(self, thread_num) + self.middle_term_computer._parallel_on_X_parallel_init(thread_num) + + @final + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_X_init_chunk(self, thread_num, X_start, X_end) + self.middle_term_computer._parallel_on_X_init_chunk(thread_num, X_start, X_end) + + @final + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + self.middle_term_computer._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num, + ) + + @final + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_Y_init(self) + self.middle_term_computer._parallel_on_Y_init() + + @final + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_Y_parallel_init(self, thread_num, X_start, X_end) + self.middle_term_computer._parallel_on_Y_parallel_init(thread_num, X_start, X_end) + + @final + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + ArgKmin{{name_suffix}}._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + self.middle_term_computer._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num + ) + + @final + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + intp_t i, j + float64_t sqeuclidean_dist_i_j + intp_t n_X = X_end - X_start + intp_t n_Y = Y_end - Y_start + float64_t * dist_middle_terms = self.middle_term_computer._compute_dist_middle_terms( + X_start, X_end, Y_start, Y_end, thread_num + ) + float64_t * heaps_r_distances = self.heaps_r_distances_chunks[thread_num] + intp_t * heaps_indices = self.heaps_indices_chunks[thread_num] + + # Pushing the distance and their associated indices on heaps + # which keep tracks of the argkmin. + for i in range(n_X): + for j in range(n_Y): + sqeuclidean_dist_i_j = ( + self.X_norm_squared[i + X_start] + + dist_middle_terms[i * n_Y + j] + + self.Y_norm_squared[j + Y_start] + ) + + # Catastrophic cancellation might cause -0. to be present, + # e.g. when computing d(x_i, y_i) when X is Y. + sqeuclidean_dist_i_j = max(0., sqeuclidean_dist_i_j) + + heap_push( + values=heaps_r_distances + i * self.k, + indices=heaps_indices + i * self.k, + size=self.k, + val=sqeuclidean_dist_i_j, + val_idx=j + Y_start, + ) + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..51fb745dca78408b7829a8aeb324bb7f99631c6b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin_classmode.pyx.tp @@ -0,0 +1,182 @@ +from cython cimport floating, integral +from cython.parallel cimport parallel, prange +from libcpp.map cimport map as cpp_map, pair as cpp_pair +from libc.stdlib cimport free + +from ...utils._typedefs cimport intp_t, float64_t +from ...utils.parallel import _get_threadpool_controller + +import numpy as np +from scipy.sparse import issparse +from ._classmode cimport WeightingStrategy + +{{for name_suffix in ["32", "64"]}} +from ._argkmin cimport ArgKmin{{name_suffix}} +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + +cdef class ArgKminClassMode{{name_suffix}}(ArgKmin{{name_suffix}}): + """ + {{name_suffix}}bit implementation of ArgKminClassMode. + """ + cdef: + const intp_t[:] Y_labels, + const intp_t[:] unique_Y_labels + float64_t[:, :] class_scores + cpp_map[intp_t, intp_t] labels_to_index + WeightingStrategy weight_type + + @classmethod + def compute( + cls, + X, + Y, + intp_t k, + weights, + Y_labels, + unique_Y_labels, + str metric="euclidean", + chunk_size=None, + dict metric_kwargs=None, + str strategy=None, + ): + """Compute the argkmin reduction with Y_labels. + + This classmethod is responsible for introspecting the arguments + values to dispatch to the most appropriate implementation of + :class:`ArgKminClassMode{{name_suffix}}`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + + No instance _must_ directly be created outside of this class method. + """ + # Use a generic implementation that handles most scipy + # metrics by computing the distances between 2 vectors at a time. + pda = ArgKminClassMode{{name_suffix}}( + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric, metric_kwargs), + k=k, + chunk_size=chunk_size, + strategy=strategy, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + # Limit the number of threads in second level of nested parallelism for BLAS + # to avoid threads over-subscription (in GEMM for instance). + with _get_threadpool_controller().limit(limits=1, user_api="blas"): + if pda.execute_in_parallel_on_Y: + pda._parallel_on_Y() + else: + pda._parallel_on_X() + + return pda._finalize_results() + + def __init__( + self, + DatasetsPair{{name_suffix}} datasets_pair, + const intp_t[:] Y_labels, + const intp_t[:] unique_Y_labels, + chunk_size=None, + strategy=None, + intp_t k=1, + weights=None, + ): + super().__init__( + datasets_pair=datasets_pair, + chunk_size=chunk_size, + strategy=strategy, + k=k, + ) + + if weights == "uniform": + self.weight_type = WeightingStrategy.uniform + elif weights == "distance": + self.weight_type = WeightingStrategy.distance + else: + self.weight_type = WeightingStrategy.callable + self.Y_labels = Y_labels + + self.unique_Y_labels = unique_Y_labels + + cdef intp_t idx, neighbor_class_idx + # Map from set of unique labels to their indices in `class_scores` + # Buffer used in building a histogram for one-pass weighted mode + self.class_scores = np.zeros( + (self.n_samples_X, unique_Y_labels.shape[0]), dtype=np.float64, + ) + + def _finalize_results(self): + probabilities = np.asarray(self.class_scores) + probabilities /= probabilities.sum(axis=1, keepdims=True) + return probabilities + + cdef inline void weighted_histogram_mode( + self, + intp_t sample_index, + intp_t* indices, + float64_t* distances, + ) noexcept nogil: + cdef: + intp_t neighbor_idx, neighbor_class_idx, label_index, multi_output_index + float64_t score_incr = 1 + # TODO: Implement other WeightingStrategy values + bint use_distance_weighting = ( + self.weight_type == WeightingStrategy.distance + ) + + # Iterate through the sample k-nearest neighbours + for neighbor_rank in range(self.k): + # Absolute indice of the neighbor_rank-th Nearest Neighbors + # in range [0, n_samples_Y) + # TODO: inspect if it worth permuting this condition + # and the for-loop above for improved branching. + if use_distance_weighting: + score_incr = 1 / distances[neighbor_rank] + neighbor_idx = indices[neighbor_rank] + neighbor_class_idx = self.Y_labels[neighbor_idx] + self.class_scores[sample_index][neighbor_class_idx] += score_incr + return + + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + cdef: + intp_t idx, sample_index + for idx in range(X_end - X_start): + # One-pass top-one weighted mode + # Compute the absolute index in [0, n_samples_X) + sample_index = X_start + idx + self.weighted_histogram_mode( + sample_index, + &self.heaps_indices_chunks[thread_num][idx * self.k], + &self.heaps_r_distances_chunks[thread_num][idx * self.k], + ) + return + + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil: + cdef: + intp_t sample_index, thread_num + + with nogil, parallel(num_threads=self.chunks_n_threads): + # Deallocating temporary datastructures + for thread_num in prange(self.chunks_n_threads, schedule='static'): + free(self.heaps_r_distances_chunks[thread_num]) + free(self.heaps_indices_chunks[thread_num]) + + for sample_index in prange(self.n_samples_X, schedule='static'): + self.weighted_histogram_mode( + sample_index, + &self.argkmin_indices[sample_index][0], + &self.argkmin_distances[sample_index][0], + ) + return + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..9578129993c37d392853f97ede19b5ce201a422f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pxd.tp @@ -0,0 +1,135 @@ +from cython cimport final + +from ...utils._typedefs cimport intp_t, float64_t + +{{for name_suffix in ['64', '32']}} + +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + + +cpdef float64_t[::1] _sqeuclidean_row_norms{{name_suffix}}( + X, + intp_t num_threads, +) + +cdef class BaseDistancesReduction{{name_suffix}}: + """ + Base float{{name_suffix}} implementation template of the pairwise-distances + reduction backends. + + Implementations inherit from this template and may override the several + defined hooks as needed in order to easily extend functionality with + minimal redundant code. + """ + + cdef: + readonly DatasetsPair{{name_suffix}} datasets_pair + + # The number of threads that can be used is stored in effective_n_threads. + # + # The number of threads to use in the parallelization strategy + # (i.e. parallel_on_X or parallel_on_Y) can be smaller than effective_n_threads: + # for small datasets, fewer threads might be needed to loop over pair of chunks. + # + # Hence, the number of threads that _will_ be used for looping over chunks + # is stored in chunks_n_threads, allowing solely using what we need. + # + # Thus, an invariant is: + # + # chunks_n_threads <= effective_n_threads + # + intp_t effective_n_threads + intp_t chunks_n_threads + + intp_t n_samples_chunk, chunk_size + + intp_t n_samples_X, X_n_samples_chunk, X_n_chunks, X_n_samples_last_chunk + intp_t n_samples_Y, Y_n_samples_chunk, Y_n_chunks, Y_n_samples_last_chunk + + bint execute_in_parallel_on_Y + + @final + cdef void _parallel_on_X(self) noexcept nogil + + @final + cdef void _parallel_on_Y(self) noexcept nogil + + # Placeholder methods which have to be implemented + + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + + # Placeholder methods which can be implemented + + cdef void compute_exact_distances(self) noexcept nogil + + cdef void _parallel_on_X_parallel_init( + self, + intp_t thread_num, + ) noexcept nogil + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_X_parallel_finalize( + self, + intp_t thread_num + ) noexcept nogil + + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + cdef void _parallel_on_Y_synchronize( + self, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..2bbfd74e2c2c399297f7836ffb6b973f8318a9e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.pyx.tp @@ -0,0 +1,504 @@ +from cython cimport final +from cython.operator cimport dereference as deref +from cython.parallel cimport parallel, prange +from libcpp.vector cimport vector + +from ...utils._cython_blas cimport _dot +from ...utils._openmp_helpers cimport omp_get_thread_num +from ...utils._typedefs cimport intp_t, float32_t, float64_t, int32_t + +import numpy as np + +from scipy.sparse import issparse +from numbers import Integral +from sklearn import get_config +from sklearn.utils import check_scalar +from ...utils._openmp_helpers import _openmp_effective_n_threads + +##################### + +cdef float64_t[::1] _sqeuclidean_row_norms64_dense( + const float64_t[:, ::1] X, + intp_t num_threads, +): + """Compute the squared euclidean norm of the rows of X in parallel. + + This is faster than using np.einsum("ij, ij->i") even when using a single thread. + """ + cdef: + # Casting for X to remove the const qualifier is needed because APIs + # exposed via scipy.linalg.cython_blas aren't reflecting the arguments' + # const qualifier. + # See: https://github.com/scipy/scipy/issues/14262 + float64_t * X_ptr = &X[0, 0] + intp_t idx = 0 + intp_t n = X.shape[0] + intp_t d = X.shape[1] + float64_t[::1] squared_row_norms = np.empty(n, dtype=np.float64) + + for idx in prange(n, schedule='static', nogil=True, num_threads=num_threads): + squared_row_norms[idx] = _dot(d, X_ptr + idx * d, 1, X_ptr + idx * d, 1) + + return squared_row_norms + + +cdef float64_t[::1] _sqeuclidean_row_norms32_dense( + const float32_t[:, ::1] X, + intp_t num_threads, +): + """Compute the squared euclidean norm of the rows of X in parallel. + + This is faster than using np.einsum("ij, ij->i") even when using a single thread. + """ + cdef: + # Casting for X to remove the const qualifier is needed because APIs + # exposed via scipy.linalg.cython_blas aren't reflecting the arguments' + # const qualifier. + # See: https://github.com/scipy/scipy/issues/14262 + float32_t * X_ptr = &X[0, 0] + intp_t i = 0, j = 0 + intp_t thread_num + intp_t n = X.shape[0] + intp_t d = X.shape[1] + float64_t[::1] squared_row_norms = np.empty(n, dtype=np.float64) + + # To upcast the i-th row of X from float32 to float64 + vector[vector[float64_t]] X_i_upcast = vector[vector[float64_t]]( + num_threads, vector[float64_t](d) + ) + + with nogil, parallel(num_threads=num_threads): + thread_num = omp_get_thread_num() + + for i in prange(n, schedule='static'): + # Upcasting the i-th row of X from float32 to float64 + for j in range(d): + X_i_upcast[thread_num][j] = deref(X_ptr + i * d + j) + + squared_row_norms[i] = _dot( + d, X_i_upcast[thread_num].data(), 1, + X_i_upcast[thread_num].data(), 1, + ) + + return squared_row_norms + + +cdef float64_t[::1] _sqeuclidean_row_norms64_sparse( + const float64_t[:] X_data, + const int32_t[:] X_indptr, + intp_t num_threads, +): + cdef: + intp_t n = X_indptr.shape[0] - 1 + int32_t X_i_ptr, idx = 0 + float64_t[::1] squared_row_norms = np.zeros(n, dtype=np.float64) + + for idx in prange(n, schedule='static', nogil=True, num_threads=num_threads): + for X_i_ptr in range(X_indptr[idx], X_indptr[idx+1]): + squared_row_norms[idx] += X_data[X_i_ptr] * X_data[X_i_ptr] + + return squared_row_norms + + +{{for name_suffix in ["64", "32"]}} + +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + + +cpdef float64_t[::1] _sqeuclidean_row_norms{{name_suffix}}( + X, + intp_t num_threads, +): + if issparse(X): + # TODO: remove this instruction which is a cast in the float32 case + # by moving squared row norms computations in MiddleTermComputer. + X_data = np.asarray(X.data, dtype=np.float64) + X_indptr = np.asarray(X.indptr, dtype=np.int32) + return _sqeuclidean_row_norms64_sparse(X_data, X_indptr, num_threads) + else: + return _sqeuclidean_row_norms{{name_suffix}}_dense(X, num_threads) + + +cdef class BaseDistancesReduction{{name_suffix}}: + """ + Base float{{name_suffix}} implementation template of the pairwise-distances + reduction backends. + + Implementations inherit from this template and may override the several + defined hooks as needed in order to easily extend functionality with + minimal redundant code. + """ + + def __init__( + self, + DatasetsPair{{name_suffix}} datasets_pair, + chunk_size=None, + strategy=None, + ): + cdef: + intp_t X_n_full_chunks, Y_n_full_chunks + + if chunk_size is None: + chunk_size = get_config().get("pairwise_dist_chunk_size", 256) + + self.chunk_size = check_scalar(chunk_size, "chunk_size", Integral, min_val=20) + + self.effective_n_threads = _openmp_effective_n_threads() + + self.datasets_pair = datasets_pair + + self.n_samples_X = datasets_pair.n_samples_X() + self.X_n_samples_chunk = min(self.n_samples_X, self.chunk_size) + X_n_full_chunks = self.n_samples_X // self.X_n_samples_chunk + X_n_samples_remainder = self.n_samples_X % self.X_n_samples_chunk + self.X_n_chunks = X_n_full_chunks + (X_n_samples_remainder != 0) + + if X_n_samples_remainder != 0: + self.X_n_samples_last_chunk = X_n_samples_remainder + else: + self.X_n_samples_last_chunk = self.X_n_samples_chunk + + self.n_samples_Y = datasets_pair.n_samples_Y() + self.Y_n_samples_chunk = min(self.n_samples_Y, self.chunk_size) + Y_n_full_chunks = self.n_samples_Y // self.Y_n_samples_chunk + Y_n_samples_remainder = self.n_samples_Y % self.Y_n_samples_chunk + self.Y_n_chunks = Y_n_full_chunks + (Y_n_samples_remainder != 0) + + if Y_n_samples_remainder != 0: + self.Y_n_samples_last_chunk = Y_n_samples_remainder + else: + self.Y_n_samples_last_chunk = self.Y_n_samples_chunk + + if strategy is None: + strategy = get_config().get("pairwise_dist_parallel_strategy", 'auto') + + if strategy not in ('parallel_on_X', 'parallel_on_Y', 'auto'): + raise RuntimeError(f"strategy must be 'parallel_on_X, 'parallel_on_Y', " + f"or 'auto', but currently strategy='{self.strategy}'.") + + if strategy == 'auto': + # This is a simple heuristic whose constant for the + # comparison has been chosen based on experiments. + # parallel_on_X has less synchronization overhead than + # parallel_on_Y and should therefore be used whenever + # n_samples_X is large enough to not starve any of the + # available hardware threads. + if self.n_samples_Y < self.n_samples_X: + # No point to even consider parallelizing on Y in this case. This + # is in particular important to do this on machines with a large + # number of hardware threads. + strategy = 'parallel_on_X' + elif 4 * self.chunk_size * self.effective_n_threads < self.n_samples_X: + # If Y is larger than X, but X is still large enough to allow for + # parallelism, we might still want to favor parallelizing on X. + strategy = 'parallel_on_X' + else: + strategy = 'parallel_on_Y' + + self.execute_in_parallel_on_Y = strategy == "parallel_on_Y" + + # Not using less, not using more. + self.chunks_n_threads = min( + self.Y_n_chunks if self.execute_in_parallel_on_Y else self.X_n_chunks, + self.effective_n_threads, + ) + + @final + cdef void _parallel_on_X(self) noexcept nogil: + """Perform computation and reduction in parallel on chunks of X. + + This strategy dispatches tasks statically on threads. Each task + processes exactly only one chunk of X, computing and reducing + distances matrices between vectors of this chunk and vectors of all + chunks of Y, one chunk of Y at a time. + + This strategy is embarrassingly parallel with no intermediate data + structures synchronization at all. + + Private datastructures are modified internally by threads. + + Private template methods can be implemented on subclasses to + interact with those datastructures at various stages. + """ + cdef: + intp_t Y_start, Y_end, X_start, X_end, X_chunk_idx, Y_chunk_idx + intp_t thread_num + + with nogil, parallel(num_threads=self.chunks_n_threads): + thread_num = omp_get_thread_num() + + # Allocating thread datastructures + self._parallel_on_X_parallel_init(thread_num) + + for X_chunk_idx in prange(self.X_n_chunks, schedule='static'): + X_start = X_chunk_idx * self.X_n_samples_chunk + if X_chunk_idx == self.X_n_chunks - 1: + X_end = X_start + self.X_n_samples_last_chunk + else: + X_end = X_start + self.X_n_samples_chunk + + # Reinitializing thread datastructures for the new X chunk + self._parallel_on_X_init_chunk(thread_num, X_start, X_end) + + for Y_chunk_idx in range(self.Y_n_chunks): + Y_start = Y_chunk_idx * self.Y_n_samples_chunk + if Y_chunk_idx == self.Y_n_chunks - 1: + Y_end = Y_start + self.Y_n_samples_last_chunk + else: + Y_end = Y_start + self.Y_n_samples_chunk + + self._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + + self._compute_and_reduce_distances_on_chunks( + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + + # Adjusting thread datastructures on the full pass on Y + self._parallel_on_X_prange_iter_finalize(thread_num, X_start, X_end) + + # end: for X_chunk_idx + + # Deallocating thread datastructures + self._parallel_on_X_parallel_finalize(thread_num) + + # end: with nogil, parallel + return + + @final + cdef void _parallel_on_Y(self) noexcept nogil: + """Perform computation and reduction in parallel on chunks of Y. + + This strategy is a sequence of embarrassingly parallel subtasks: + chunks of X are iterated over sequentially, and for each chunk of X, + tasks are dispatched statically on threads. Each task processes one + and only one chunk of Y, computing and reducing distances matrices + between vectors of the chunk of X and vectors of the Y. + + It comes with lock-free and parallelized intermediate data structures + that synchronize at each iteration of the sequential outer loop on X + chunks. + + Private datastructures are modified internally by threads. + + Private template methods can be implemented on subclasses to + interact with those datastructures at various stages. + """ + cdef: + intp_t Y_start, Y_end, X_start, X_end, X_chunk_idx, Y_chunk_idx + intp_t thread_num + + # Allocating datastructures shared by all threads + self._parallel_on_Y_init() + + for X_chunk_idx in range(self.X_n_chunks): + X_start = X_chunk_idx * self.X_n_samples_chunk + if X_chunk_idx == self.X_n_chunks - 1: + X_end = X_start + self.X_n_samples_last_chunk + else: + X_end = X_start + self.X_n_samples_chunk + + with nogil, parallel(num_threads=self.chunks_n_threads): + thread_num = omp_get_thread_num() + + # Initializing datastructures used in this thread + self._parallel_on_Y_parallel_init(thread_num, X_start, X_end) + + for Y_chunk_idx in prange(self.Y_n_chunks, schedule='static'): + Y_start = Y_chunk_idx * self.Y_n_samples_chunk + if Y_chunk_idx == self.Y_n_chunks - 1: + Y_end = Y_start + self.Y_n_samples_last_chunk + else: + Y_end = Y_start + self.Y_n_samples_chunk + + self._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + + self._compute_and_reduce_distances_on_chunks( + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + # end: prange + + # end: with nogil, parallel + + # Synchronizing the thread datastructures with the main ones + self._parallel_on_Y_synchronize(X_start, X_end) + + # end: for X_chunk_idx + # Deallocating temporary datastructures and adjusting main datastructures + self._parallel_on_Y_finalize() + return + + # Placeholder methods which have to be implemented + + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + """Compute the pairwise distances on two chunks of X and Y and reduce them. + + This is THE core computational method of BaseDistancesReduction{{name_suffix}}. + This must be implemented in subclasses agnostically from the parallelization + strategies. + """ + return + + def _finalize_results(self, bint return_distance): + """Callback adapting datastructures before returning results. + + This must be implemented in subclasses. + """ + return None + + # Placeholder methods which can be implemented + + cdef void compute_exact_distances(self) noexcept nogil: + """Convert rank-preserving distances to exact distances or recompute them.""" + return + + cdef void _parallel_on_X_parallel_init( + self, + intp_t thread_num, + ) noexcept nogil: + """Allocate datastructures used in a thread given its number.""" + return + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + """Initialize datastructures used in a thread given its number. + + In this method, EuclideanDistance specialisations of subclass of + BaseDistancesReduction _must_ call: + + self.middle_term_computer._parallel_on_X_init_chunk( + thread_num, X_start, X_end, + ) + + to ensure the proper upcast of X[X_start:X_end] to float64 prior + to the reduction with float64 accumulator buffers when X.dtype is + float32. + """ + return + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + """Initialize datastructures just before the _compute_and_reduce_distances_on_chunks. + + In this method, EuclideanDistance specialisations of subclass of + BaseDistancesReduction _must_ call: + + self.middle_term_computer._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num, + ) + + to ensure the proper upcast of Y[Y_start:Y_end] to float64 prior + to the reduction with float64 accumulator buffers when Y.dtype is + float32. + """ + return + + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + """Interact with datastructures after a reduction on chunks.""" + return + + cdef void _parallel_on_X_parallel_finalize( + self, + intp_t thread_num + ) noexcept nogil: + """Interact with datastructures after executing all the reductions.""" + return + + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil: + """Allocate datastructures used in all threads.""" + return + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + """Initialize datastructures used in a thread given its number. + + In this method, EuclideanDistance specialisations of subclass of + BaseDistancesReduction _must_ call: + + self.middle_term_computer._parallel_on_Y_parallel_init( + thread_num, X_start, X_end, + ) + + to ensure the proper upcast of X[X_start:X_end] to float64 prior + to the reduction with float64 accumulator buffers when X.dtype is + float32. + """ + return + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + """Initialize datastructures just before the _compute_and_reduce_distances_on_chunks. + + In this method, EuclideanDistance specialisations of subclass of + BaseDistancesReduction _must_ call: + + self.middle_term_computer._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num, + ) + + to ensure the proper upcast of Y[Y_start:Y_end] to float64 prior + to the reduction with float64 accumulator buffers when Y.dtype is + float32. + """ + return + + cdef void _parallel_on_Y_synchronize( + self, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + """Update thread datastructures before leaving a parallel region.""" + return + + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil: + """Update datastructures after executing all the reductions.""" + return + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_classmode.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_classmode.pxd new file mode 100644 index 0000000000000000000000000000000000000000..65db044d668e89cc0a681a871663220d065dca41 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_classmode.pxd @@ -0,0 +1,5 @@ +cpdef enum WeightingStrategy: + uniform = 0 + # TODO: Implement the following options in weighted_histogram_mode + distance = 1 + callable = 2 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..1e57b3291a8f4be47902a1c4c26c1a41d1f43297 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pxd.tp @@ -0,0 +1,67 @@ +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + ('64', 'DistanceMetric64', 'float64_t'), + ('32', 'DistanceMetric32', 'float32_t') +] + +}} +from ...utils._typedefs cimport float64_t, float32_t, int32_t, intp_t +from ...metrics._dist_metrics cimport DistanceMetric64, DistanceMetric32, DistanceMetric + +{{for name_suffix, DistanceMetric, INPUT_DTYPE_t in implementation_specific_values}} + + +cdef class DatasetsPair{{name_suffix}}: + cdef: + {{DistanceMetric}} distance_metric + intp_t n_features + + cdef intp_t n_samples_X(self) noexcept nogil + + cdef intp_t n_samples_Y(self) noexcept nogil + + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil + + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil + + +cdef class DenseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + cdef: + const {{INPUT_DTYPE_t}}[:, ::1] X + const {{INPUT_DTYPE_t}}[:, ::1] Y + + +cdef class SparseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + cdef: + const {{INPUT_DTYPE_t}}[:] X_data + const int32_t[::1] X_indices + const int32_t[::1] X_indptr + + const {{INPUT_DTYPE_t}}[:] Y_data + const int32_t[::1] Y_indices + const int32_t[::1] Y_indptr + + +cdef class SparseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + cdef: + const {{INPUT_DTYPE_t}}[:] X_data + const int32_t[::1] X_indices + const int32_t[::1] X_indptr + + const {{INPUT_DTYPE_t}}[:] Y_data + const int32_t[::1] Y_indices + intp_t n_Y + + +cdef class DenseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + cdef: + # As distance metrics are commutative, we can simply rely + # on the implementation of SparseDenseDatasetsPair and + # swap arguments. + DatasetsPair{{name_suffix}} datasets_pair + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..2c3ca44047145e98ca4b446a85db87b1c2ecd2c2 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_datasets_pair.pyx.tp @@ -0,0 +1,406 @@ +import copy + +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + ('64', 'DistanceMetric64', 'float64_t', 'np.float64'), + ('32', 'DistanceMetric32', 'float32_t', 'np.float32') +] + +}} +import numpy as np + +from cython cimport final + +from ...utils._typedefs cimport float64_t, float32_t, intp_t + +from scipy.sparse import issparse, csr_matrix + +{{for name_suffix, DistanceMetric, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +cdef class DatasetsPair{{name_suffix}}: + """Abstract class which wraps a pair of datasets (X, Y). + + This class allows computing distances between a single pair of rows of + of X and Y at a time given the pair of their indices (i, j). This class is + specialized for each metric thanks to the :func:`get_for` factory classmethod. + + The handling of parallelization over chunks to compute the distances + and aggregation for several rows at a time is done in dedicated + subclasses of :class:`BaseDistancesReductionDispatcher` that in-turn rely on + subclasses of :class:`DatasetsPair` for each pair of rows in the data. The + goal is to make it possible to decouple the generic parallelization and + aggregation logic from metric-specific computation as much as possible. + + X and Y can be stored as C-contiguous np.ndarrays or CSR matrices + in subclasses. + + This class avoids the overhead of dispatching distance computations + to :class:`sklearn.metrics.DistanceMetric` based on the physical + representation of the vectors (sparse vs. dense). It makes use of + cython.final to remove the overhead of dispatching method calls. + + Parameters + ---------- + distance_metric: {{DistanceMetric}} + The distance metric responsible for computing distances + between two vectors of (X, Y). + """ + + @classmethod + def get_for( + cls, + X, + Y, + metric="euclidean", + dict metric_kwargs=None, + ) -> DatasetsPair{{name_suffix}}: + """Return the DatasetsPair implementation for the given arguments. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples_X, n_features) + Input data. + If provided as a ndarray, it must be C-contiguous. + If provided as a sparse matrix, it must be in CSR format. + + Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features) + Input data. + If provided as a ndarray, it must be C-contiguous. + If provided as a sparse matrix, it must be in CSR format. + + metric : str or DistanceMetric object, default='euclidean' + The distance metric to compute between rows of X and Y. + The default metric is a fast implementation of the Euclidean + metric. For a list of available metrics, see the documentation + of :class:`~sklearn.metrics.DistanceMetric`. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + Returns + ------- + datasets_pair: DatasetsPair{{name_suffix}} + The suited DatasetsPair{{name_suffix}} implementation. + """ + # X_norm_squared and Y_norm_squared might be propagated + # down to DatasetsPairs via metrics_kwargs when the Euclidean + # specialisations can't be used. + # To prevent X_norm_squared and Y_norm_squared to be passed + # down to DistanceMetrics (whose constructors would raise + # a RuntimeError), we pop them here. + if metric_kwargs is not None: + # Copying metric_kwargs not to pop "X_norm_squared" + # and "Y_norm_squared" where they are used + metric_kwargs = copy.copy(metric_kwargs) + metric_kwargs.pop("X_norm_squared", None) + metric_kwargs.pop("Y_norm_squared", None) + cdef: + {{DistanceMetric}} distance_metric = DistanceMetric.get_metric( + metric, + {{INPUT_DTYPE}}, + **(metric_kwargs or {}) + ) + + # Metric-specific checks that do not replace nor duplicate `check_array`. + distance_metric._validate_data(X) + distance_metric._validate_data(Y) + + X_is_sparse = issparse(X) + Y_is_sparse = issparse(Y) + + if not X_is_sparse and not Y_is_sparse: + return DenseDenseDatasetsPair{{name_suffix}}(X, Y, distance_metric) + + if X_is_sparse and Y_is_sparse: + return SparseSparseDatasetsPair{{name_suffix}}(X, Y, distance_metric) + + if X_is_sparse and not Y_is_sparse: + return SparseDenseDatasetsPair{{name_suffix}}(X, Y, distance_metric) + + return DenseSparseDatasetsPair{{name_suffix}}(X, Y, distance_metric) + + @classmethod + def unpack_csr_matrix(cls, X: csr_matrix): + """Ensure that the CSR matrix is indexed with np.int32.""" + X_data = np.asarray(X.data, dtype={{INPUT_DTYPE}}) + X_indices = np.asarray(X.indices, dtype=np.int32) + X_indptr = np.asarray(X.indptr, dtype=np.int32) + return X_data, X_indices, X_indptr + + def __init__(self, {{DistanceMetric}} distance_metric, intp_t n_features): + self.distance_metric = distance_metric + self.n_features = n_features + + cdef intp_t n_samples_X(self) noexcept nogil: + """Number of samples in X.""" + # This is a abstract method. + # This _must_ always be overwritten in subclasses. + # TODO: add "with gil: raise" here when supporting Cython 3.0 + return -999 + + cdef intp_t n_samples_Y(self) noexcept nogil: + """Number of samples in Y.""" + # This is a abstract method. + # This _must_ always be overwritten in subclasses. + # TODO: add "with gil: raise" here when supporting Cython 3.0 + return -999 + + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil: + return self.dist(i, j) + + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil: + # This is a abstract method. + # This _must_ always be overwritten in subclasses. + # TODO: add "with gil: raise" here when supporting Cython 3.0 + return -1 + +@final +cdef class DenseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + """Compute distances between row vectors of two arrays. + + Parameters + ---------- + X: ndarray of shape (n_samples_X, n_features) + Rows represent vectors. Must be C-contiguous. + + Y: ndarray of shape (n_samples_Y, n_features) + Rows represent vectors. Must be C-contiguous. + + distance_metric: DistanceMetric + The distance metric responsible for computing distances + between two row vectors of (X, Y). + """ + + def __init__( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + const {{INPUT_DTYPE_t}}[:, ::1] Y, + {{DistanceMetric}} distance_metric, + ): + super().__init__(distance_metric, n_features=X.shape[1]) + # Arrays have already been checked + self.X = X + self.Y = Y + + @final + cdef intp_t n_samples_X(self) noexcept nogil: + return self.X.shape[0] + + @final + cdef intp_t n_samples_Y(self) noexcept nogil: + return self.Y.shape[0] + + @final + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil: + return self.distance_metric.rdist(&self.X[i, 0], &self.Y[j, 0], self.n_features) + + @final + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil: + return self.distance_metric.dist(&self.X[i, 0], &self.Y[j, 0], self.n_features) + + +@final +cdef class SparseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + """Compute distances between vectors of two CSR matrices. + + Parameters + ---------- + X: sparse matrix of shape (n_samples_X, n_features) + Rows represent vectors. Must be in CSR format. + + Y: sparse matrix of shape (n_samples_Y, n_features) + Rows represent vectors. Must be in CSR format. + + distance_metric: DistanceMetric + The distance metric responsible for computing distances + between two vectors of (X, Y). + """ + + def __init__(self, X, Y, {{DistanceMetric}} distance_metric): + super().__init__(distance_metric, n_features=X.shape[1]) + + self.X_data, self.X_indices, self.X_indptr = self.unpack_csr_matrix(X) + self.Y_data, self.Y_indices, self.Y_indptr = self.unpack_csr_matrix(Y) + + @final + cdef intp_t n_samples_X(self) noexcept nogil: + return self.X_indptr.shape[0] - 1 + + @final + cdef intp_t n_samples_Y(self) noexcept nogil: + return self.Y_indptr.shape[0] - 1 + + @final + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil: + return self.distance_metric.rdist_csr( + x1_data=&self.X_data[0], + x1_indices=&self.X_indices[0], + x2_data=&self.Y_data[0], + x2_indices=&self.Y_indices[0], + x1_start=self.X_indptr[i], + x1_end=self.X_indptr[i + 1], + x2_start=self.Y_indptr[j], + x2_end=self.Y_indptr[j + 1], + size=self.n_features, + ) + + @final + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil: + return self.distance_metric.dist_csr( + x1_data=&self.X_data[0], + x1_indices=&self.X_indices[0], + x2_data=&self.Y_data[0], + x2_indices=&self.Y_indices[0], + x1_start=self.X_indptr[i], + x1_end=self.X_indptr[i + 1], + x2_start=self.Y_indptr[j], + x2_end=self.Y_indptr[j + 1], + size=self.n_features, + ) + + +@final +cdef class SparseDenseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + """Compute distances between vectors of a CSR matrix and a dense array. + + Parameters + ---------- + X: sparse matrix of shape (n_samples_X, n_features) + Rows represent vectors. Must be in CSR format. + + Y: ndarray of shape (n_samples_Y, n_features) + Rows represent vectors. Must be C-contiguous. + + distance_metric: DistanceMetric + The distance metric responsible for computing distances + between two vectors of (X, Y). + """ + + def __init__(self, X, Y, {{DistanceMetric}} distance_metric): + super().__init__(distance_metric, n_features=X.shape[1]) + + self.X_data, self.X_indices, self.X_indptr = self.unpack_csr_matrix(X) + + # We support the sparse-dense case by using the sparse-sparse interfaces + # of `DistanceMetric` (namely `DistanceMetric.{dist_csr,rdist_csr}`) to + # avoid introducing a new complex set of interfaces. In this case, we + # need to convert `Y` (the dense array) into a CSR matrix. + # + # Here we motive using another simpler CSR representation to use for `Y`. + # + # If we were to use the usual CSR representation for `Y`, storing all + # the columns indices in `indices` would have required allocating an + # array of n_samples × n_features elements with repeated contiguous + # integers from 0 to n_features - 1. This would have been very wasteful + # from a memory point of view. This alternative representation just uses + # the necessary amount of information needed and only necessitates + # shifting the address of `data` before calling the CSR × CSR routines. + # + # In this representation: + # + # - the `data` array is the original dense array, `Y`, whose first + # element's address is shifted before calling the CSR × CSR routine + # + # - the `indices` array is a single row of `n_features` elements: + # + # [0, 1, ..., n_features-1] + # + # - the `indptr` array is not materialised as the indices pointers' + # offset is constant (the offset equals `n_features`). Moreover, as + # `data` is shifted, constant `start` and `end` indices pointers + # respectively equalling 0 and n_features are used. + + # Y array already has been checked here + self.n_Y = Y.shape[0] + self.Y_data = np.ravel(Y) + self.Y_indices = np.arange(self.n_features, dtype=np.int32) + + @final + cdef intp_t n_samples_X(self) noexcept nogil: + return self.X_indptr.shape[0] - 1 + + @final + cdef intp_t n_samples_Y(self) noexcept nogil: + return self.n_Y + + @final + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil: + return self.distance_metric.rdist_csr( + x1_data=&self.X_data[0], + x1_indices=&self.X_indices[0], + # Increment the data pointer such that x2_start=0 is aligned with the + # j-th row + x2_data=&self.Y_data[0] + j * self.n_features, + x2_indices=&self.Y_indices[0], + x1_start=self.X_indptr[i], + x1_end=self.X_indptr[i + 1], + x2_start=0, + x2_end=self.n_features, + size=self.n_features, + ) + + @final + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil: + + return self.distance_metric.dist_csr( + x1_data=&self.X_data[0], + x1_indices=&self.X_indices[0], + # Increment the data pointer such that x2_start=0 is aligned with the + # j-th row + x2_data=&self.Y_data[0] + j * self.n_features, + x2_indices=&self.Y_indices[0], + x1_start=self.X_indptr[i], + x1_end=self.X_indptr[i + 1], + x2_start=0, + x2_end=self.n_features, + size=self.n_features, + ) + + +@final +cdef class DenseSparseDatasetsPair{{name_suffix}}(DatasetsPair{{name_suffix}}): + """Compute distances between vectors of a dense array and a CSR matrix. + + Parameters + ---------- + X: ndarray of shape (n_samples_X, n_features) + Rows represent vectors. Must be C-contiguous. + + Y: sparse matrix of shape (n_samples_Y, n_features) + Rows represent vectors. Must be in CSR format. + + distance_metric: DistanceMetric + The distance metric responsible for computing distances + between two vectors of (X, Y). + """ + + def __init__(self, X, Y, {{DistanceMetric}} distance_metric): + super().__init__(distance_metric, n_features=X.shape[1]) + # Swapping arguments on the constructor + self.datasets_pair = SparseDenseDatasetsPair{{name_suffix}}(Y, X, distance_metric) + + @final + cdef intp_t n_samples_X(self) noexcept nogil: + # Swapping interface + return self.datasets_pair.n_samples_Y() + + @final + cdef intp_t n_samples_Y(self) noexcept nogil: + # Swapping interface + return self.datasets_pair.n_samples_X() + + @final + cdef float64_t surrogate_dist(self, intp_t i, intp_t j) noexcept nogil: + # Swapping arguments on the same interface + return self.datasets_pair.surrogate_dist(j, i) + + @final + cdef float64_t dist(self, intp_t i, intp_t j) noexcept nogil: + # Swapping arguments on the same interface + return self.datasets_pair.dist(j, i) + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..d8307cbe84eaa904b50bdf11b59546aef397dbc3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_dispatcher.py @@ -0,0 +1,767 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from abc import abstractmethod +from typing import List + +import numpy as np +from scipy.sparse import issparse + +from ... import get_config +from .._dist_metrics import ( + BOOL_METRICS, + METRIC_MAPPING64, + DistanceMetric, +) +from ._argkmin import ( + ArgKmin32, + ArgKmin64, +) +from ._argkmin_classmode import ( + ArgKminClassMode32, + ArgKminClassMode64, +) +from ._base import _sqeuclidean_row_norms32, _sqeuclidean_row_norms64 +from ._radius_neighbors import ( + RadiusNeighbors32, + RadiusNeighbors64, +) +from ._radius_neighbors_classmode import ( + RadiusNeighborsClassMode32, + RadiusNeighborsClassMode64, +) + + +def sqeuclidean_row_norms(X, num_threads): + """Compute the squared euclidean norm of the rows of X in parallel. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples, n_features) + Input data. Must be c-contiguous. + + num_threads : int + The number of OpenMP threads to use. + + Returns + ------- + sqeuclidean_row_norms : ndarray of shape (n_samples,) + Arrays containing the squared euclidean norm of each row of X. + """ + if X.dtype == np.float64: + return np.asarray(_sqeuclidean_row_norms64(X, num_threads)) + if X.dtype == np.float32: + return np.asarray(_sqeuclidean_row_norms32(X, num_threads)) + + raise ValueError( + "Only float64 or float32 datasets are supported at this time, " + f"got: X.dtype={X.dtype}." + ) + + +class BaseDistancesReductionDispatcher: + """Abstract base dispatcher for pairwise distance computation & reduction. + + Each dispatcher extending the base :class:`BaseDistancesReductionDispatcher` + dispatcher must implement the :meth:`compute` classmethod. + """ + + @classmethod + def valid_metrics(cls) -> List[str]: + excluded = { + # PyFunc cannot be supported because it necessitates interacting with + # the CPython interpreter to call user defined functions. + "pyfunc", + "mahalanobis", # is numerically unstable + # In order to support discrete distance metrics, we need to have a + # stable simultaneous sort which preserves the order of the indices + # because there generally is a lot of occurrences for a given values + # of distances in this case. + # TODO: implement a stable simultaneous_sort. + "hamming", + *BOOL_METRICS, + } + return sorted(({"sqeuclidean"} | set(METRIC_MAPPING64.keys())) - excluded) + + @classmethod + def is_usable_for(cls, X, Y, metric) -> bool: + """Return True if the dispatcher can be used for the + given parameters. + + Parameters + ---------- + X : {ndarray, sparse matrix} of shape (n_samples_X, n_features) + Input data. + + Y : {ndarray, sparse matrix} of shape (n_samples_Y, n_features) + Input data. + + metric : str, default='euclidean' + The distance metric to use. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + Returns + ------- + True if the dispatcher can be used, else False. + """ + + # FIXME: the current Cython implementation is too slow for a large number of + # features. We temporarily disable it to fallback on SciPy's implementation. + # See: https://github.com/scikit-learn/scikit-learn/issues/28191 + if ( + issparse(X) + and issparse(Y) + and isinstance(metric, str) + and "euclidean" in metric + ): + return False + + def is_numpy_c_ordered(X): + return hasattr(X, "flags") and getattr(X.flags, "c_contiguous", False) + + def is_valid_sparse_matrix(X): + return ( + issparse(X) + and X.format == "csr" + and + # TODO: support CSR matrices without non-zeros elements + X.nnz > 0 + and + # TODO: support CSR matrices with int64 indices and indptr + # See: https://github.com/scikit-learn/scikit-learn/issues/23653 + X.indices.dtype == X.indptr.dtype == np.int32 + ) + + is_usable = ( + get_config().get("enable_cython_pairwise_dist", True) + and (is_numpy_c_ordered(X) or is_valid_sparse_matrix(X)) + and (is_numpy_c_ordered(Y) or is_valid_sparse_matrix(Y)) + and X.dtype == Y.dtype + and X.dtype in (np.float32, np.float64) + and (metric in cls.valid_metrics() or isinstance(metric, DistanceMetric)) + ) + + return is_usable + + @classmethod + @abstractmethod + def compute( + cls, + X, + Y, + **kwargs, + ): + """Compute the reduction. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + **kwargs : additional parameters for the reduction + + Notes + ----- + This method is an abstract class method: it has to be implemented + for all subclasses. + """ + + +class ArgKmin(BaseDistancesReductionDispatcher): + """Compute the argkmin of row vectors of X on the ones of Y. + + For each row vector of X, computes the indices of k first the rows + vectors of Y with the smallest distances. + + ArgKmin is typically used to perform + bruteforce k-nearest neighbors queries. + + This class is not meant to be instantiated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def compute( + cls, + X, + Y, + k, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + return_distance=False, + ): + """Compute the argkmin reduction. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + k : int + The k for the argkmin reduction. + + metric : str, default='euclidean' + The distance metric to use for argkmin. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + + return_distance : boolean, default=False + Return distances between each X vector and its + argkmin if set to True. + + Returns + ------- + If return_distance=False: + - argkmin_indices : ndarray of shape (n_samples_X, k) + Indices of the argkmin for each vector in X. + + If return_distance=True: + - argkmin_distances : ndarray of shape (n_samples_X, k) + Distances to the argkmin for each vector in X. + - argkmin_indices : ndarray of shape (n_samples_X, k) + Indices of the argkmin for each vector in X. + + Notes + ----- + This classmethod inspects the arguments values to dispatch to the + dtype-specialized implementation of :class:`ArgKmin`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + """ + if X.dtype == Y.dtype == np.float64: + return ArgKmin64.compute( + X=X, + Y=Y, + k=k, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + return_distance=return_distance, + ) + + if X.dtype == Y.dtype == np.float32: + return ArgKmin32.compute( + X=X, + Y=Y, + k=k, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + return_distance=return_distance, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) + + +class RadiusNeighbors(BaseDistancesReductionDispatcher): + """Compute radius-based neighbors for two sets of vectors. + + For each row-vector X[i] of the queries X, find all the indices j of + row-vectors in Y such that: + + dist(X[i], Y[j]) <= radius + + The distance function `dist` depends on the values of the `metric` + and `metric_kwargs` parameters. + + This class is not meant to be instantiated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def compute( + cls, + X, + Y, + radius, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + return_distance=False, + sort_results=False, + ): + """Return the results of the reduction for the given arguments. + + Parameters + ---------- + X : ndarray or CSR matrix of shape (n_samples_X, n_features) + Input data. + + Y : ndarray or CSR matrix of shape (n_samples_Y, n_features) + Input data. + + radius : float + The radius defining the neighborhood. + + metric : str, default='euclidean' + The distance metric to use. + For a list of available metrics, see the documentation of + :class:`~sklearn.metrics.DistanceMetric`. + + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + despite the synchronization step at each iteration of the outer loop + on chunks of `X`. + + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + + return_distance : boolean, default=False + Return distances between each X vector and its neighbors if set to True. + + sort_results : boolean, default=False + Sort results with respect to distances between each X vector and its + neighbors if set to True. + + Returns + ------- + If return_distance=False: + - neighbors_indices : ndarray of n_samples_X ndarray + Indices of the neighbors for each vector in X. + + If return_distance=True: + - neighbors_indices : ndarray of n_samples_X ndarray + Indices of the neighbors for each vector in X. + - neighbors_distances : ndarray of n_samples_X ndarray + Distances to the neighbors for each vector in X. + + Notes + ----- + This classmethod inspects the arguments values to dispatch to the + dtype-specialized implementation of :class:`RadiusNeighbors`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + """ + if X.dtype == Y.dtype == np.float64: + return RadiusNeighbors64.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + sort_results=sort_results, + return_distance=return_distance, + ) + + if X.dtype == Y.dtype == np.float32: + return RadiusNeighbors32.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + sort_results=sort_results, + return_distance=return_distance, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) + + +class ArgKminClassMode(BaseDistancesReductionDispatcher): + """Compute the argkmin of row vectors of X on the ones of Y with labels. + + For each row vector of X, computes the indices of k first the rows + vectors of Y with the smallest distances. Computes weighted mode of labels. + + ArgKminClassMode is typically used to perform bruteforce k-nearest neighbors + queries when the weighted mode of the labels for the k-nearest neighbors + are required, such as in `predict` methods. + + This class is not meant to be instantiated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def valid_metrics(cls) -> List[str]: + excluded = { + # Euclidean is technically usable for ArgKminClassMode + # but its current implementation would not be competitive. + # TODO: implement Euclidean specialization using GEMM. + "euclidean", + "sqeuclidean", + } + return list(set(BaseDistancesReductionDispatcher.valid_metrics()) - excluded) + + @classmethod + def compute( + cls, + X, + Y, + k, + weights, + Y_labels, + unique_Y_labels, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + ): + """Compute the argkmin reduction. + + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + The input array to be labelled. + + Y : ndarray of shape (n_samples_Y, n_features) + The input array whose class membership are provided through the + `Y_labels` parameter. + + k : int + The number of nearest neighbors to consider. + + weights : ndarray + The weights applied over the `Y_labels` of `Y` when computing the + weighted mode of the labels. + + Y_labels : ndarray + An array containing the index of the class membership of the + associated samples in `Y`. This is used in labeling `X`. + + unique_Y_labels : ndarray + An array containing all unique indices contained in the + corresponding `Y_labels` array. + + metric : str, default='euclidean' + The distance metric to use. For a list of available metrics, see + the documentation of :class:`~sklearn.metrics.DistanceMetric`. + Currently does not support `'precomputed'`. + + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + despite the synchronization step at each iteration of the outer loop + on chunks of `X`. + + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + + Returns + ------- + probabilities : ndarray of shape (n_samples_X, n_classes) + An array containing the class probabilities for each sample. + + Notes + ----- + This classmethod is responsible for introspecting the arguments + values to dispatch to the most appropriate implementation of + :class:`PairwiseDistancesArgKmin`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + """ + if weights not in {"uniform", "distance"}: + raise ValueError( + "Only the 'uniform' or 'distance' weights options are supported" + f" at this time. Got: {weights=}." + ) + if X.dtype == Y.dtype == np.float64: + return ArgKminClassMode64.compute( + X=X, + Y=Y, + k=k, + weights=weights, + Y_labels=np.array(Y_labels, dtype=np.intp), + unique_Y_labels=np.array(unique_Y_labels, dtype=np.intp), + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + ) + + if X.dtype == Y.dtype == np.float32: + return ArgKminClassMode32.compute( + X=X, + Y=Y, + k=k, + weights=weights, + Y_labels=np.array(Y_labels, dtype=np.intp), + unique_Y_labels=np.array(unique_Y_labels, dtype=np.intp), + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) + + +class RadiusNeighborsClassMode(BaseDistancesReductionDispatcher): + """Compute radius-based class modes of row vectors of X using the + those of Y. + + For each row-vector X[i] of the queries X, find all the indices j of + row-vectors in Y such that: + + dist(X[i], Y[j]) <= radius + + RadiusNeighborsClassMode is typically used to perform bruteforce + radius neighbors queries when the weighted mode of the labels for + the nearest neighbors within the specified radius are required, + such as in `predict` methods. + + This class is not meant to be instantiated, one should only use + its :meth:`compute` classmethod which handles allocation and + deallocation consistently. + """ + + @classmethod + def valid_metrics(cls) -> List[str]: + excluded = { + # Euclidean is technically usable for RadiusNeighborsClassMode + # but it would not be competitive. + # TODO: implement Euclidean specialization using GEMM. + "euclidean", + "sqeuclidean", + } + return sorted(set(BaseDistancesReductionDispatcher.valid_metrics()) - excluded) + + @classmethod + def compute( + cls, + X, + Y, + radius, + weights, + Y_labels, + unique_Y_labels, + outlier_label, + metric="euclidean", + chunk_size=None, + metric_kwargs=None, + strategy=None, + ): + """Return the results of the reduction for the given arguments. + Parameters + ---------- + X : ndarray of shape (n_samples_X, n_features) + The input array to be labelled. + Y : ndarray of shape (n_samples_Y, n_features) + The input array whose class membership is provided through + the `Y_labels` parameter. + radius : float + The radius defining the neighborhood. + weights : ndarray + The weights applied to the `Y_labels` when computing the + weighted mode of the labels. + Y_labels : ndarray + An array containing the index of the class membership of the + associated samples in `Y`. This is used in labeling `X`. + unique_Y_labels : ndarray + An array containing all unique class labels. + outlier_label : int, default=None + Label for outlier samples (samples with no neighbors in given + radius). In the default case when the value is None if any + outlier is detected, a ValueError will be raised. The outlier + label should be selected from among the unique 'Y' labels. If + it is specified with a different value a warning will be raised + and all class probabilities of outliers will be assigned to be 0. + metric : str, default='euclidean' + The distance metric to use. For a list of available metrics, see + the documentation of :class:`~sklearn.metrics.DistanceMetric`. + Currently does not support `'precomputed'`. + chunk_size : int, default=None, + The number of vectors per chunk. If None (default) looks-up in + scikit-learn configuration for `pairwise_dist_chunk_size`, + and use 256 if it is not set. + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + strategy : str, {'auto', 'parallel_on_X', 'parallel_on_Y'}, default=None + The chunking strategy defining which dataset parallelization are made on. + For both strategies the computations happens with two nested loops, + respectively on chunks of X and chunks of Y. + Strategies differs on which loop (outer or inner) is made to run + in parallel with the Cython `prange` construct: + - 'parallel_on_X' dispatches chunks of X uniformly on threads. + Each thread then iterates on all the chunks of Y. This strategy is + embarrassingly parallel and comes with no datastructures + synchronisation. + - 'parallel_on_Y' dispatches chunks of Y uniformly on threads. + Each thread processes all the chunks of X in turn. This strategy is + a sequence of embarrassingly parallel subtasks (the inner loop on Y + chunks) with intermediate datastructures synchronisation at each + iteration of the sequential outer loop on X chunks. + - 'auto' relies on a simple heuristic to choose between + 'parallel_on_X' and 'parallel_on_Y': when `X.shape[0]` is large enough, + 'parallel_on_X' is usually the most efficient strategy. + When `X.shape[0]` is small but `Y.shape[0]` is large, 'parallel_on_Y' + brings more opportunity for parallelism and is therefore more efficient + despite the synchronization step at each iteration of the outer loop + on chunks of `X`. + - None (default) looks-up in scikit-learn configuration for + `pairwise_dist_parallel_strategy`, and use 'auto' if it is not set. + Returns + ------- + probabilities : ndarray of shape (n_samples_X, n_classes) + An array containing the class probabilities for each sample. + """ + if weights not in {"uniform", "distance"}: + raise ValueError( + "Only the 'uniform' or 'distance' weights options are supported" + f" at this time. Got: {weights=}." + ) + if X.dtype == Y.dtype == np.float64: + return RadiusNeighborsClassMode64.compute( + X=X, + Y=Y, + radius=radius, + weights=weights, + Y_labels=np.array(Y_labels, dtype=np.intp), + unique_Y_labels=np.array(unique_Y_labels, dtype=np.intp), + outlier_label=outlier_label, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + ) + + if X.dtype == Y.dtype == np.float32: + return RadiusNeighborsClassMode32.compute( + X=X, + Y=Y, + radius=radius, + weights=weights, + Y_labels=np.array(Y_labels, dtype=np.intp), + unique_Y_labels=np.array(unique_Y_labels, dtype=np.intp), + outlier_label=outlier_label, + metric=metric, + chunk_size=chunk_size, + metric_kwargs=metric_kwargs, + strategy=strategy, + ) + + raise ValueError( + "Only float64 or float32 datasets pairs are supported at this time, " + f"got: X.dtype={X.dtype} and Y.dtype={Y.dtype}." + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..bdf007bd0514ab4b49ccdd55a3bd5dbe1b2c75ec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pxd.tp @@ -0,0 +1,228 @@ +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, upcast_to_float64, INPUT_DTYPE_t, INPUT_DTYPE + # + # We also use the float64 dtype and C-type names as defined in + # `sklearn.utils._typedefs` to maintain consistency. + # + ('64', False, 'float64_t', 'np.float64'), + ('32', True, 'float32_t', 'np.float32') +] + +}} +from libcpp.vector cimport vector + +from ...utils._typedefs cimport float64_t, float32_t, int32_t, intp_t + + +cdef void _middle_term_sparse_sparse_64( + const float64_t[:] X_data, + const int32_t[:] X_indices, + const int32_t[:] X_indptr, + intp_t X_start, + intp_t X_end, + const float64_t[:] Y_data, + const int32_t[:] Y_indices, + const int32_t[:] Y_indptr, + intp_t Y_start, + intp_t Y_end, + float64_t * D, +) noexcept nogil + + +{{for name_suffix, upcast_to_float64, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + + +cdef class MiddleTermComputer{{name_suffix}}: + cdef: + intp_t effective_n_threads + intp_t chunks_n_threads + intp_t dist_middle_terms_chunks_size + intp_t n_features + intp_t chunk_size + + # Buffers for the `-2 * X_c @ Y_c.T` term computed via GEMM + vector[vector[float64_t]] dist_middle_terms_chunks + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + cdef void _parallel_on_X_parallel_init(self, intp_t thread_num) noexcept nogil + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_init(self) noexcept nogil + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + +cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + cdef: + const {{INPUT_DTYPE_t}}[:, ::1] X + const {{INPUT_DTYPE_t}}[:, ::1] Y + + {{if upcast_to_float64}} + # Buffers for upcasting chunks of X and Y from 32bit to 64bit + vector[vector[float64_t]] X_c_upcast + vector[vector[float64_t]] Y_c_upcast + {{endif}} + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + +cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + cdef: + const float64_t[:] X_data + const int32_t[:] X_indices + const int32_t[:] X_indptr + + const float64_t[:] Y_data + const int32_t[:] Y_indices + const int32_t[:] Y_indptr + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + + +cdef class SparseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + cdef: + const float64_t[:] X_data + const int32_t[:] X_indices + const int32_t[:] X_indptr + + const {{INPUT_DTYPE_t}}[:, ::1] Y + + # We treat the dense-sparse case with the sparse-dense case by simply + # treating the dist_middle_terms as F-ordered and by swapping arguments. + # This attribute is meant to encode the case and adapt the logic + # accordingly. + bint c_ordered_middle_term + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..1fca2d674720c40fa2df8f56fea4f3a7a6980ba8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.pyx.tp @@ -0,0 +1,633 @@ +{{py: + +implementation_specific_values = [ + # Values are the following ones: + # + # name_suffix, upcast_to_float64, INPUT_DTYPE_t, INPUT_DTYPE + # + # We also use the float64 dtype and C-type names as defined in + # `sklearn.utils._typedefs` to maintain consistency. + # + ('64', False, 'float64_t', 'np.float64'), + ('32', True, 'float32_t', 'np.float32') +] + +}} +from libcpp.vector cimport vector +from libcpp.algorithm cimport fill + +from ...utils._cython_blas cimport ( + BLAS_Order, + BLAS_Trans, + NoTrans, + RowMajor, + Trans, + _gemm, +) +from ...utils._typedefs cimport float64_t, float32_t, int32_t, intp_t + +import numpy as np +from scipy.sparse import issparse, csr_matrix + + +cdef void _middle_term_sparse_sparse_64( + const float64_t[:] X_data, + const int32_t[:] X_indices, + const int32_t[:] X_indptr, + intp_t X_start, + intp_t X_end, + const float64_t[:] Y_data, + const int32_t[:] Y_indices, + const int32_t[:] Y_indptr, + intp_t Y_start, + intp_t Y_end, + float64_t * D, +) noexcept nogil: + # This routine assumes that D points to the first element of a + # zeroed buffer of length at least equal to n_X × n_Y, conceptually + # representing a 2-d C-ordered array. + cdef: + intp_t i, j, k + intp_t n_X = X_end - X_start + intp_t n_Y = Y_end - Y_start + intp_t x_col, x_ptr, y_col, y_ptr + + for i in range(n_X): + for x_ptr in range(X_indptr[X_start+i], X_indptr[X_start+i+1]): + x_col = X_indices[x_ptr] + for j in range(n_Y): + k = i * n_Y + j + for y_ptr in range(Y_indptr[Y_start+j], Y_indptr[Y_start+j+1]): + y_col = Y_indices[y_ptr] + if x_col == y_col: + D[k] += -2 * X_data[x_ptr] * Y_data[y_ptr] + + +{{for name_suffix, upcast_to_float64, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +cdef void _middle_term_sparse_dense_{{name_suffix}}( + const float64_t[:] X_data, + const int32_t[:] X_indices, + const int32_t[:] X_indptr, + intp_t X_start, + intp_t X_end, + const {{INPUT_DTYPE_t}}[:, ::1] Y, + intp_t Y_start, + intp_t Y_end, + bint c_ordered_middle_term, + float64_t * dist_middle_terms, +) noexcept nogil: + # This routine assumes that dist_middle_terms is a pointer to the first element + # of a buffer filled with zeros of length at least equal to n_X × n_Y, conceptually + # representing a 2-d C-ordered of F-ordered array. + cdef: + intp_t i, j, k + intp_t n_X = X_end - X_start + intp_t n_Y = Y_end - Y_start + intp_t X_i_col_idx, X_i_ptr, Y_j_col_idx, Y_j_ptr + + for i in range(n_X): + for j in range(n_Y): + k = i * n_Y + j if c_ordered_middle_term else j * n_X + i + for X_i_ptr in range(X_indptr[X_start+i], X_indptr[X_start+i+1]): + X_i_col_idx = X_indices[X_i_ptr] + dist_middle_terms[k] += -2 * X_data[X_i_ptr] * Y[Y_start + j, X_i_col_idx] + + +cdef class MiddleTermComputer{{name_suffix}}: + """Helper class to compute a Euclidean distance matrix in chunks. + + This is an abstract base class that is further specialized depending + on the type of data (dense or sparse). + + `EuclideanDistance` subclasses relies on the squared Euclidean + distances between chunks of vectors X_c and Y_c using the + following decomposition for the (i,j) pair : + + + ||X_c_i - Y_c_j||² = ||X_c_i||² - 2 X_c_i.Y_c_j^T + ||Y_c_j||² + + + This helper class is in charge of wrapping the common logic to compute + the middle term, i.e. `- 2 X_c_i.Y_c_j^T`. + """ + + @classmethod + def get_for( + cls, + X, + Y, + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) -> MiddleTermComputer{{name_suffix}}: + """Return the MiddleTermComputer implementation for the given arguments. + + Parameters + ---------- + X : ndarray or CSR sparse matrix of shape (n_samples_X, n_features) + Input data. + If provided as a ndarray, it must be C-contiguous. + + Y : ndarray or CSR sparse matrix of shape (n_samples_Y, n_features) + Input data. + If provided as a ndarray, it must be C-contiguous. + + Returns + ------- + middle_term_computer: MiddleTermComputer{{name_suffix}} + The suited MiddleTermComputer{{name_suffix}} implementation. + """ + X_is_sparse = issparse(X) + Y_is_sparse = issparse(Y) + + if not X_is_sparse and not Y_is_sparse: + return DenseDenseMiddleTermComputer{{name_suffix}}( + X, + Y, + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) + if X_is_sparse and Y_is_sparse: + return SparseSparseMiddleTermComputer{{name_suffix}}( + X, + Y, + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) + if X_is_sparse and not Y_is_sparse: + return SparseDenseMiddleTermComputer{{name_suffix}}( + X, + Y, + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + c_ordered_middle_term=True + ) + if not X_is_sparse and Y_is_sparse: + # NOTE: The Dense-Sparse case is implement via the Sparse-Dense case. + # + # To do so: + # - X (dense) and Y (sparse) are swapped + # - the distance middle term is seen as F-ordered for consistency + # (c_ordered_middle_term = False) + return SparseDenseMiddleTermComputer{{name_suffix}}( + # Mind that X and Y are swapped here. + Y, + X, + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + c_ordered_middle_term=False, + ) + raise NotImplementedError( + "X and Y must be CSR sparse matrices or numpy arrays." + ) + + @classmethod + def unpack_csr_matrix(cls, X: csr_matrix): + """Ensure that the CSR matrix is indexed with np.int32.""" + X_data = np.asarray(X.data, dtype=np.float64) + X_indices = np.asarray(X.indices, dtype=np.int32) + X_indptr = np.asarray(X.indptr, dtype=np.int32) + return X_data, X_indices, X_indptr + + def __init__( + self, + intp_t effective_n_threads, + intp_t chunks_n_threads, + intp_t dist_middle_terms_chunks_size, + intp_t n_features, + intp_t chunk_size, + ): + self.effective_n_threads = effective_n_threads + self.chunks_n_threads = chunks_n_threads + self.dist_middle_terms_chunks_size = dist_middle_terms_chunks_size + self.n_features = n_features + self.chunk_size = chunk_size + + self.dist_middle_terms_chunks = vector[vector[float64_t]](self.effective_n_threads) + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + return + + cdef void _parallel_on_X_parallel_init(self, intp_t thread_num) noexcept nogil: + self.dist_middle_terms_chunks[thread_num].resize(self.dist_middle_terms_chunks_size) + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + return + + cdef void _parallel_on_Y_init(self) noexcept nogil: + for thread_num in range(self.chunks_n_threads): + self.dist_middle_terms_chunks[thread_num].resize( + self.dist_middle_terms_chunks_size + ) + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + return + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil: + return + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + return NULL + + +cdef class DenseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + """Computes the middle term of the Euclidean distance between two chunked dense matrices + X_c and Y_c. + + dist_middle_terms = - 2 X_c_i.Y_c_j^T + + This class use the BLAS gemm routine to perform the dot product of each chunks + of the distance matrix with improved arithmetic intensity and vector instruction (SIMD). + """ + + def __init__( + self, + const {{INPUT_DTYPE_t}}[:, ::1] X, + const {{INPUT_DTYPE_t}}[:, ::1] Y, + intp_t effective_n_threads, + intp_t chunks_n_threads, + intp_t dist_middle_terms_chunks_size, + intp_t n_features, + intp_t chunk_size, + ): + super().__init__( + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) + self.X = X + self.Y = Y + +{{if upcast_to_float64}} + # We populate the buffer for upcasting chunks of X and Y from float32 to float64. + self.X_c_upcast = vector[vector[float64_t]](self.effective_n_threads) + self.Y_c_upcast = vector[vector[float64_t]](self.effective_n_threads) + + upcast_buffer_n_elements = self.chunk_size * n_features + + for thread_num in range(self.effective_n_threads): + self.X_c_upcast[thread_num].resize(upcast_buffer_n_elements) + self.Y_c_upcast[thread_num].resize(upcast_buffer_n_elements) +{{endif}} + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: +{{if upcast_to_float64}} + cdef: + intp_t i, j + intp_t n_chunk_samples = Y_end - Y_start + + # Upcasting Y_c=Y[Y_start:Y_end, :] from float32 to float64 + for i in range(n_chunk_samples): + for j in range(self.n_features): + self.Y_c_upcast[thread_num][i * self.n_features + j] = self.Y[Y_start + i, j] +{{else}} + return +{{endif}} + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: +{{if upcast_to_float64}} + cdef: + intp_t i, j + intp_t n_chunk_samples = X_end - X_start + + # Upcasting X_c=X[X_start:X_end, :] from float32 to float64 + for i in range(n_chunk_samples): + for j in range(self.n_features): + self.X_c_upcast[thread_num][i * self.n_features + j] = self.X[X_start + i, j] +{{else}} + return +{{endif}} + + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: +{{if upcast_to_float64}} + cdef: + intp_t i, j + intp_t n_chunk_samples = X_end - X_start + + # Upcasting X_c=X[X_start:X_end, :] from float32 to float64 + for i in range(n_chunk_samples): + for j in range(self.n_features): + self.X_c_upcast[thread_num][i * self.n_features + j] = self.X[X_start + i, j] +{{else}} + return +{{endif}} + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num + ) noexcept nogil: +{{if upcast_to_float64}} + cdef: + intp_t i, j + intp_t n_chunk_samples = Y_end - Y_start + + # Upcasting Y_c=Y[Y_start:Y_end, :] from float32 to float64 + for i in range(n_chunk_samples): + for j in range(self.n_features): + self.Y_c_upcast[thread_num][i * self.n_features + j] = self.Y[Y_start + i, j] +{{else}} + return +{{endif}} + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + float64_t *dist_middle_terms = self.dist_middle_terms_chunks[thread_num].data() + + # Careful: LDA, LDB and LDC are given for F-ordered arrays + # in BLAS documentations, for instance: + # https://www.netlib.org/lapack/explore-html/db/dc9/group__single__blas__level3_gafe51bacb54592ff5de056acabd83c260.html #noqa + # + # Here, we use their counterpart values to work with C-ordered arrays. + BLAS_Order order = RowMajor + BLAS_Trans ta = NoTrans + BLAS_Trans tb = Trans + intp_t m = X_end - X_start + intp_t n = Y_end - Y_start + intp_t K = self.n_features + float64_t alpha = - 2. +{{if upcast_to_float64}} + float64_t * A = self.X_c_upcast[thread_num].data() + float64_t * B = self.Y_c_upcast[thread_num].data() +{{else}} + # Casting for A and B to remove the const is needed because APIs exposed via + # scipy.linalg.cython_blas aren't reflecting the arguments' const qualifier. + # See: https://github.com/scipy/scipy/issues/14262 + float64_t * A = &self.X[X_start, 0] + float64_t * B = &self.Y[Y_start, 0] +{{endif}} + intp_t lda = self.n_features + intp_t ldb = self.n_features + float64_t beta = 0. + intp_t ldc = Y_end - Y_start + + # dist_middle_terms = `-2 * X[X_start:X_end] @ Y[Y_start:Y_end].T` + _gemm(order, ta, tb, m, n, K, alpha, A, lda, B, ldb, beta, dist_middle_terms, ldc) + + return dist_middle_terms + + +cdef class SparseSparseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + """Middle term of the Euclidean distance between two chunked CSR matrices. + + The result is return as a contiguous array. + + dist_middle_terms = - 2 X_c_i.Y_c_j^T + + The logic of the computation is wrapped in the routine _middle_term_sparse_sparse_64. + This routine iterates over the data, indices and indptr arrays of the sparse matrices without + densifying them. + """ + + def __init__( + self, + X, + Y, + intp_t effective_n_threads, + intp_t chunks_n_threads, + intp_t dist_middle_terms_chunks_size, + intp_t n_features, + intp_t chunk_size, + ): + super().__init__( + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) + self.X_data, self.X_indices, self.X_indptr = self.unpack_csr_matrix(X) + self.Y_data, self.Y_indices, self.Y_indptr = self.unpack_csr_matrix(Y) + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + # Flush the thread dist_middle_terms_chunks to 0.0 + fill( + self.dist_middle_terms_chunks[thread_num].begin(), + self.dist_middle_terms_chunks[thread_num].end(), + 0.0, + ) + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + # Flush the thread dist_middle_terms_chunks to 0.0 + fill( + self.dist_middle_terms_chunks[thread_num].begin(), + self.dist_middle_terms_chunks[thread_num].end(), + 0.0, + ) + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + float64_t *dist_middle_terms = ( + self.dist_middle_terms_chunks[thread_num].data() + ) + + _middle_term_sparse_sparse_64( + self.X_data, + self.X_indices, + self.X_indptr, + X_start, + X_end, + self.Y_data, + self.Y_indices, + self.Y_indptr, + Y_start, + Y_end, + dist_middle_terms, + ) + + return dist_middle_terms + +cdef class SparseDenseMiddleTermComputer{{name_suffix}}(MiddleTermComputer{{name_suffix}}): + """Middle term of the Euclidean distance between chunks of a CSR matrix and a np.ndarray. + + The logic of the computation is wrapped in the routine _middle_term_sparse_dense_{{name_suffix}}. + This routine iterates over the data, indices and indptr arrays of the sparse matrices + without densifying them. + """ + + def __init__( + self, + X, + Y, + intp_t effective_n_threads, + intp_t chunks_n_threads, + intp_t dist_middle_terms_chunks_size, + intp_t n_features, + intp_t chunk_size, + bint c_ordered_middle_term, + ): + super().__init__( + effective_n_threads, + chunks_n_threads, + dist_middle_terms_chunks_size, + n_features, + chunk_size, + ) + self.X_data, self.X_indices, self.X_indptr = self.unpack_csr_matrix(X) + self.Y = Y + self.c_ordered_middle_term = c_ordered_middle_term + + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + # Fill the thread's dist_middle_terms_chunks with 0.0 before + # computing its elements in _compute_dist_middle_terms. + fill( + self.dist_middle_terms_chunks[thread_num].begin(), + self.dist_middle_terms_chunks[thread_num].end(), + 0.0, + ) + + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + # Fill the thread's dist_middle_terms_chunks with 0.0 before + # computing its elements in _compute_dist_middle_terms. + fill( + self.dist_middle_terms_chunks[thread_num].begin(), + self.dist_middle_terms_chunks[thread_num].end(), + 0.0, + ) + + cdef float64_t * _compute_dist_middle_terms( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + float64_t *dist_middle_terms = ( + self.dist_middle_terms_chunks[thread_num].data() + ) + + # For the dense-sparse case, we use the sparse-dense case + # with dist_middle_terms seen as F-ordered. + # Hence we swap indices pointers here. + if not self.c_ordered_middle_term: + X_start, Y_start = Y_start, X_start + X_end, Y_end = Y_end, X_end + + _middle_term_sparse_dense_{{name_suffix}}( + self.X_data, + self.X_indices, + self.X_indptr, + X_start, + X_end, + self.Y, + Y_start, + Y_end, + self.c_ordered_middle_term, + dist_middle_terms, + ) + + return dist_middle_terms + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp new file mode 100644 index 0000000000000000000000000000000000000000..809a80a68c5b0c6a513b8b9267fe211f109cdaee --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pxd.tp @@ -0,0 +1,90 @@ +cimport numpy as cnp + +from libcpp.memory cimport shared_ptr +from libcpp.vector cimport vector +from cython cimport final + +from ...utils._typedefs cimport intp_t, float64_t + +cnp.import_array() + +###################### +## std::vector to np.ndarray coercion +# As type covariance is not supported for C++ containers via Cython, +# we need to redefine fused types. +ctypedef fused vector_double_intp_t: + vector[intp_t] + vector[float64_t] + + +ctypedef fused vector_vector_double_intp_t: + vector[vector[intp_t]] + vector[vector[float64_t]] + +cdef cnp.ndarray[object, ndim=1] coerce_vectors_to_nd_arrays( + shared_ptr[vector_vector_double_intp_t] vecs +) + +##################### +{{for name_suffix in ['64', '32']}} + +from ._base cimport BaseDistancesReduction{{name_suffix}} +from ._middle_term_computer cimport MiddleTermComputer{{name_suffix}} + +cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): + """float{{name_suffix}} implementation of the RadiusNeighbors.""" + + cdef: + float64_t radius + + # DistanceMetric{{name_suffix}} compute rank-preserving surrogate distance via rdist + # which are proxies necessitating less computations. + # We get the equivalent for the radius to be able to compare it against + # vectors' rank-preserving surrogate distances. + float64_t r_radius + + # Neighbors indices and distances are returned as np.ndarrays of np.ndarrays. + # + # For this implementation, we want resizable buffers which we will wrap + # into numpy arrays at the end. std::vector comes as a handy container + # for interacting efficiently with resizable buffers. + # + # Though it is possible to access their buffer address with + # std::vector::data, they can't be stolen: buffers lifetime + # is tied to their std::vector and are deallocated when + # std::vectors are. + # + # To solve this, we dynamically allocate std::vectors and then + # encapsulate them in a StdVectorSentinel responsible for + # freeing them when the associated np.ndarray is freed. + # + # Shared pointers (defined via shared_ptr) are use for safer memory management. + # Unique pointers (defined via unique_ptr) can't be used as datastructures + # are shared across threads for parallel_on_X; see _parallel_on_X_init_chunk. + shared_ptr[vector[vector[intp_t]]] neigh_indices + shared_ptr[vector[vector[float64_t]]] neigh_distances + + # Used as array of pointers to private datastructures used in threads. + vector[shared_ptr[vector[vector[intp_t]]]] neigh_indices_chunks + vector[shared_ptr[vector[vector[float64_t]]]] neigh_distances_chunks + + bint sort_results + + @final + cdef void _merge_vectors( + self, + intp_t idx, + intp_t num_threads, + ) noexcept nogil + + +cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix}}): + """EuclideanDistance-specialisation of RadiusNeighbors{{name_suffix}}.""" + cdef: + MiddleTermComputer{{name_suffix}} middle_term_computer + const float64_t[::1] X_norm_squared + const float64_t[::1] Y_norm_squared + + bint use_squared_distances + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..d0567f2ead804d122fc24424a5d502084b6565e0 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.pyx.tp @@ -0,0 +1,514 @@ +cimport numpy as cnp +import numpy as np +import warnings + +from libcpp.memory cimport shared_ptr, make_shared +from libcpp.vector cimport vector +from libcpp.algorithm cimport move +from cython cimport final +from cython.operator cimport dereference as deref +from cython.parallel cimport parallel, prange + +from ...utils._sorting cimport simultaneous_sort +from ...utils._typedefs cimport intp_t, float64_t +from ...utils._vector_sentinel cimport vector_to_nd_array + +from numbers import Real +from scipy.sparse import issparse +from ...utils import check_array, check_scalar +from ...utils.fixes import _in_unstable_openblas_configuration +from ...utils.parallel import _get_threadpool_controller + +cnp.import_array() + +###################### + +cdef cnp.ndarray[object, ndim=1] coerce_vectors_to_nd_arrays( + shared_ptr[vector_vector_double_intp_t] vecs +): + """Coerce a std::vector of std::vector to a ndarray of ndarray.""" + cdef: + intp_t n = deref(vecs).size() + cnp.ndarray[object, ndim=1] nd_arrays_of_nd_arrays = np.empty(n, dtype=np.ndarray) + + for i in range(n): + nd_arrays_of_nd_arrays[i] = vector_to_nd_array(&(deref(vecs)[i])) + + return nd_arrays_of_nd_arrays + +##################### +{{for name_suffix in ['64', '32']}} + +from ._base cimport ( + BaseDistancesReduction{{name_suffix}}, + _sqeuclidean_row_norms{{name_suffix}} +) + +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + +from ._middle_term_computer cimport MiddleTermComputer{{name_suffix}} + + +cdef class RadiusNeighbors{{name_suffix}}(BaseDistancesReduction{{name_suffix}}): + """float{{name_suffix}} implementation of the RadiusNeighbors.""" + + @classmethod + def compute( + cls, + X, + Y, + float64_t radius, + str metric="euclidean", + chunk_size=None, + dict metric_kwargs=None, + str strategy=None, + bint return_distance=False, + bint sort_results=False, + ): + """Compute the radius-neighbors reduction. + + This classmethod is responsible for introspecting the arguments + values to dispatch to the most appropriate implementation of + :class:`RadiusNeighbors{{name_suffix}}`. + + This allows decoupling the API entirely from the implementation details + whilst maintaining RAII: all temporarily allocated datastructures necessary + for the concrete implementation are therefore freed when this classmethod + returns. + + No instance should directly be created outside of this class method. + """ + if metric in ("euclidean", "sqeuclidean"): + # Specialized implementation of RadiusNeighbors for the Euclidean + # distance for the dense-dense and sparse-sparse cases. + # This implementation computes the distances by chunk using + # a decomposition of the Squared Euclidean distance. + # This specialisation has an improved arithmetic intensity for both + # the dense and sparse settings, allowing in most case speed-ups of + # several orders of magnitude compared to the generic RadiusNeighbors + # implementation. + # For more information see MiddleTermComputer. + use_squared_distances = metric == "sqeuclidean" + pda = EuclideanRadiusNeighbors{{name_suffix}}( + X=X, Y=Y, radius=radius, + use_squared_distances=use_squared_distances, + chunk_size=chunk_size, + strategy=strategy, + sort_results=sort_results, + metric_kwargs=metric_kwargs, + ) + else: + # Fall back on a generic implementation that handles most scipy + # metrics by computing the distances between 2 vectors at a time. + pda = RadiusNeighbors{{name_suffix}}( + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric, metric_kwargs), + radius=radius, + chunk_size=chunk_size, + strategy=strategy, + sort_results=sort_results, + ) + + # Limit the number of threads in second level of nested parallelism for BLAS + # to avoid threads over-subscription (in GEMM for instance). + with _get_threadpool_controller().limit(limits=1, user_api="blas"): + if pda.execute_in_parallel_on_Y: + pda._parallel_on_Y() + else: + pda._parallel_on_X() + + return pda._finalize_results(return_distance) + + + def __init__( + self, + DatasetsPair{{name_suffix}} datasets_pair, + float64_t radius, + chunk_size=None, + strategy=None, + sort_results=False, + ): + super().__init__( + datasets_pair=datasets_pair, + chunk_size=chunk_size, + strategy=strategy, + ) + + self.radius = check_scalar(radius, "radius", Real, min_val=0) + self.r_radius = self.datasets_pair.distance_metric._dist_to_rdist(radius) + self.sort_results = sort_results + + # Allocating pointers to datastructures but not the datastructures themselves. + # There are as many pointers as effective threads. + # + # For the sake of explicitness: + # - when parallelizing on X, the pointers of those heaps are referencing + # self.neigh_distances and self.neigh_indices + # - when parallelizing on Y, the pointers of those heaps are referencing + # std::vectors of std::vectors which are thread-wise-allocated and whose + # content will be merged into self.neigh_distances and self.neigh_indices. + self.neigh_distances_chunks = vector[shared_ptr[vector[vector[float64_t]]]]( + self.chunks_n_threads + ) + self.neigh_indices_chunks = vector[shared_ptr[vector[vector[intp_t]]]]( + self.chunks_n_threads + ) + + # Temporary datastructures which will be coerced to numpy arrays on before + # RadiusNeighbors.compute "return" and will be then freed. + self.neigh_distances = make_shared[vector[vector[float64_t]]](self.n_samples_X) + self.neigh_indices = make_shared[vector[vector[intp_t]]](self.n_samples_X) + + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + intp_t i, j + float64_t r_dist_i_j + + for i in range(X_start, X_end): + for j in range(Y_start, Y_end): + r_dist_i_j = self.datasets_pair.surrogate_dist(i, j) + if r_dist_i_j <= self.r_radius: + deref(self.neigh_distances_chunks[thread_num])[i].push_back(r_dist_i_j) + deref(self.neigh_indices_chunks[thread_num])[i].push_back(j) + + def _finalize_results(self, bint return_distance=False): + if return_distance: + # We need to recompute distances because we relied on + # surrogate distances for the reduction. + self.compute_exact_distances() + return ( + coerce_vectors_to_nd_arrays(self.neigh_distances), + coerce_vectors_to_nd_arrays(self.neigh_indices), + ) + + return coerce_vectors_to_nd_arrays(self.neigh_indices) + + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + + # As this strategy is embarrassingly parallel, we can set the + # thread vectors' pointers to the main vectors'. + self.neigh_distances_chunks[thread_num] = self.neigh_distances + self.neigh_indices_chunks[thread_num] = self.neigh_indices + + @final + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + cdef: + intp_t idx + + # Sorting neighbors for each query vector of X + if self.sort_results: + for idx in range(X_start, X_end): + simultaneous_sort( + deref(self.neigh_distances)[idx].data(), + deref(self.neigh_indices)[idx].data(), + deref(self.neigh_indices)[idx].size() + ) + + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil: + cdef: + intp_t thread_num + # As chunks of X are shared across threads, so must datastructures to avoid race + # conditions: each thread has its own vectors of n_samples_X vectors which are + # then merged back in the main n_samples_X vectors. + for thread_num in range(self.chunks_n_threads): + self.neigh_distances_chunks[thread_num] = make_shared[vector[vector[float64_t]]](self.n_samples_X) + self.neigh_indices_chunks[thread_num] = make_shared[vector[vector[intp_t]]](self.n_samples_X) + + @final + cdef void _merge_vectors( + self, + intp_t idx, + intp_t num_threads, + ) noexcept nogil: + cdef: + intp_t thread_num + intp_t idx_n_elements = 0 + intp_t last_element_idx = deref(self.neigh_indices)[idx].size() + + # Resizing buffers only once for the given number of elements. + for thread_num in range(num_threads): + idx_n_elements += deref(self.neigh_distances_chunks[thread_num])[idx].size() + + deref(self.neigh_distances)[idx].resize(last_element_idx + idx_n_elements) + deref(self.neigh_indices)[idx].resize(last_element_idx + idx_n_elements) + + # Moving the elements by range using the range first element + # as the reference for the insertion. + for thread_num in range(num_threads): + move( + deref(self.neigh_distances_chunks[thread_num])[idx].begin(), + deref(self.neigh_distances_chunks[thread_num])[idx].end(), + deref(self.neigh_distances)[idx].begin() + last_element_idx + ) + move( + deref(self.neigh_indices_chunks[thread_num])[idx].begin(), + deref(self.neigh_indices_chunks[thread_num])[idx].end(), + deref(self.neigh_indices)[idx].begin() + last_element_idx + ) + last_element_idx += deref(self.neigh_distances_chunks[thread_num])[idx].size() + + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil: + cdef: + intp_t idx + + with nogil, parallel(num_threads=self.effective_n_threads): + # Merge vectors used in threads into the main ones. + # This is done in parallel sample-wise (no need for locks). + for idx in prange(self.n_samples_X, schedule='static'): + self._merge_vectors(idx, self.chunks_n_threads) + + # The content of the vector have been std::moved. + # Hence they can't be used anymore and can be deleted. + # Their deletion is carried out automatically as the + # implementation relies on shared pointers. + + # Sort in parallel in ascending order w.r.t the distances if requested. + if self.sort_results: + for idx in prange(self.n_samples_X, schedule='static'): + simultaneous_sort( + deref(self.neigh_distances)[idx].data(), + deref(self.neigh_indices)[idx].data(), + deref(self.neigh_indices)[idx].size() + ) + + return + + cdef void compute_exact_distances(self) noexcept nogil: + """Convert rank-preserving distances to pairwise distances in parallel.""" + cdef: + intp_t i + vector[intp_t].size_type j + + for i in prange(self.n_samples_X, nogil=True, schedule='static', + num_threads=self.effective_n_threads): + for j in range(deref(self.neigh_indices)[i].size()): + deref(self.neigh_distances)[i][j] = ( + self.datasets_pair.distance_metric._rdist_to_dist( + # Guard against potential -0., causing nan production. + max(deref(self.neigh_distances)[i][j], 0.) + ) + ) + + +cdef class EuclideanRadiusNeighbors{{name_suffix}}(RadiusNeighbors{{name_suffix}}): + """EuclideanDistance-specialisation of RadiusNeighbors{{name_suffix}}.""" + + @classmethod + def is_usable_for(cls, X, Y, metric) -> bool: + return (RadiusNeighbors{{name_suffix}}.is_usable_for(X, Y, metric) + and not _in_unstable_openblas_configuration()) + + def __init__( + self, + X, + Y, + float64_t radius, + bint use_squared_distances=False, + chunk_size=None, + strategy=None, + sort_results=False, + metric_kwargs=None, + ): + if ( + isinstance(metric_kwargs, dict) and + (metric_kwargs.keys() - {"X_norm_squared", "Y_norm_squared"}) + ): + warnings.warn( + f"Some metric_kwargs have been passed ({metric_kwargs}) but aren't " + f"usable for this case (EuclideanRadiusNeighbors64) and will be ignored.", + UserWarning, + stacklevel=3, + ) + + super().__init__( + # The datasets pair here is used for exact distances computations + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric="euclidean"), + radius=radius, + chunk_size=chunk_size, + strategy=strategy, + sort_results=sort_results, + ) + cdef: + intp_t dist_middle_terms_chunks_size = self.Y_n_samples_chunk * self.X_n_samples_chunk + + self.middle_term_computer = MiddleTermComputer{{name_suffix}}.get_for( + X, + Y, + self.effective_n_threads, + self.chunks_n_threads, + dist_middle_terms_chunks_size, + n_features=X.shape[1], + chunk_size=self.chunk_size, + ) + + if metric_kwargs is not None and "Y_norm_squared" in metric_kwargs: + self.Y_norm_squared = check_array( + metric_kwargs.pop("Y_norm_squared"), + ensure_2d=False, + input_name="Y_norm_squared", + dtype=np.float64, + ) + else: + self.Y_norm_squared = _sqeuclidean_row_norms{{name_suffix}}( + Y, + self.effective_n_threads, + ) + + if metric_kwargs is not None and "X_norm_squared" in metric_kwargs: + self.X_norm_squared = check_array( + metric_kwargs.pop("X_norm_squared"), + ensure_2d=False, + input_name="X_norm_squared", + dtype=np.float64, + ) + else: + # Do not recompute norms if datasets are identical. + self.X_norm_squared = ( + self.Y_norm_squared if X is Y else + _sqeuclidean_row_norms{{name_suffix}}( + X, + self.effective_n_threads, + ) + ) + + self.use_squared_distances = use_squared_distances + + if use_squared_distances: + # In this specialisation and this setup, the value passed to the radius is + # already considered to be the adapted radius, so we overwrite it. + self.r_radius = radius + + @final + cdef void _parallel_on_X_parallel_init( + self, + intp_t thread_num, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_X_parallel_init(self, thread_num) + self.middle_term_computer._parallel_on_X_parallel_init(thread_num) + + @final + cdef void _parallel_on_X_init_chunk( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_X_init_chunk(self, thread_num, X_start, X_end) + self.middle_term_computer._parallel_on_X_init_chunk(thread_num, X_start, X_end) + + @final + cdef void _parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + self, + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + self.middle_term_computer._parallel_on_X_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num, + ) + + @final + cdef void _parallel_on_Y_init( + self, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_Y_init(self) + self.middle_term_computer._parallel_on_Y_init() + + @final + cdef void _parallel_on_Y_parallel_init( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_Y_parallel_init(self, thread_num, X_start, X_end) + self.middle_term_computer._parallel_on_Y_parallel_init(thread_num, X_start, X_end) + + @final + cdef void _parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + RadiusNeighbors{{name_suffix}}._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + self, + X_start, X_end, + Y_start, Y_end, + thread_num, + ) + self.middle_term_computer._parallel_on_Y_pre_compute_and_reduce_distances_on_chunks( + X_start, X_end, Y_start, Y_end, thread_num + ) + + @final + cdef void compute_exact_distances(self) noexcept nogil: + if not self.use_squared_distances: + RadiusNeighbors{{name_suffix}}.compute_exact_distances(self) + + @final + cdef void _compute_and_reduce_distances_on_chunks( + self, + intp_t X_start, + intp_t X_end, + intp_t Y_start, + intp_t Y_end, + intp_t thread_num, + ) noexcept nogil: + cdef: + intp_t i, j + float64_t sqeuclidean_dist_i_j + intp_t n_X = X_end - X_start + intp_t n_Y = Y_end - Y_start + float64_t *dist_middle_terms = self.middle_term_computer._compute_dist_middle_terms( + X_start, X_end, Y_start, Y_end, thread_num + ) + + # Pushing the distance and their associated indices in vectors. + for i in range(n_X): + for j in range(n_Y): + sqeuclidean_dist_i_j = ( + self.X_norm_squared[i + X_start] + + dist_middle_terms[i * n_Y + j] + + self.Y_norm_squared[j + Y_start] + ) + + # Catastrophic cancellation might cause -0. to be present, + # e.g. when computing d(x_i, y_i) when X is Y. + sqeuclidean_dist_i_j = max(0., sqeuclidean_dist_i_j) + + if sqeuclidean_dist_i_j <= self.r_radius: + deref(self.neigh_distances_chunks[thread_num])[i + X_start].push_back(sqeuclidean_dist_i_j) + deref(self.neigh_indices_chunks[thread_num])[i + X_start].push_back(j + Y_start) + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..0a9b22251843e60e52fa6d29248f3a745b37e414 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors_classmode.pyx.tp @@ -0,0 +1,217 @@ +import warnings + +from cython cimport floating, final, integral +from cython.operator cimport dereference as deref +from cython.parallel cimport parallel, prange +from ._classmode cimport WeightingStrategy +from ...utils._typedefs cimport intp_t, float64_t, uint8_t + +import numpy as np +from scipy.sparse import issparse +from ...utils.parallel import _get_threadpool_controller + + +{{for name_suffix in ["32", "64"]}} +from ._radius_neighbors cimport RadiusNeighbors{{name_suffix}} +from ._datasets_pair cimport DatasetsPair{{name_suffix}} + +cdef class RadiusNeighborsClassMode{{name_suffix}}(RadiusNeighbors{{name_suffix}}): + """ + {{name_suffix}}bit implementation of RadiusNeighborsClassMode. + """ + cdef: + const intp_t[::1] Y_labels + const intp_t[::1] unique_Y_labels + intp_t outlier_label_index + bint outlier_label_exists + bint outliers_exist + uint8_t[::1] outliers + object outlier_label + float64_t[:, ::1] class_scores + WeightingStrategy weight_type + + @classmethod + def compute( + cls, + X, + Y, + float64_t radius, + weights, + Y_labels, + unique_Y_labels, + outlier_label=None, + str metric="euclidean", + chunk_size=None, + dict metric_kwargs=None, + str strategy=None, + ): + # Use a generic implementation that handles most scipy + # metrics by computing the distances between 2 vectors at a time. + pda = RadiusNeighborsClassMode{{name_suffix}}( + datasets_pair=DatasetsPair{{name_suffix}}.get_for(X, Y, metric, metric_kwargs), + radius=radius, + chunk_size=chunk_size, + strategy=strategy, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=outlier_label, + ) + + # Limit the number of threads in second level of nested parallelism for BLAS + # to avoid threads over-subscription (in GEMM for instance). + with _get_threadpool_controller().limit(limits=1, user_api="blas"): + if pda.execute_in_parallel_on_Y: + pda._parallel_on_Y() + else: + pda._parallel_on_X() + + return pda._finalize_results() + + def __init__( + self, + DatasetsPair{{name_suffix}} datasets_pair, + const intp_t[::1] Y_labels, + const intp_t[::1] unique_Y_labels, + float64_t radius, + chunk_size=None, + strategy=None, + weights=None, + outlier_label=None, + ): + super().__init__( + datasets_pair=datasets_pair, + chunk_size=chunk_size, + strategy=strategy, + radius=radius, + ) + + if weights == "uniform": + self.weight_type = WeightingStrategy.uniform + elif weights == "distance": + self.weight_type = WeightingStrategy.distance + else: + self.weight_type = WeightingStrategy.callable + + self.Y_labels = Y_labels + self.unique_Y_labels = unique_Y_labels + self.outlier_label_index = -1 + self.outliers_exist = False + self.outlier_label = outlier_label + self.outliers = np.zeros(self.n_samples_X, dtype=np.bool_) + + cdef intp_t idx + if self.outlier_label is not None: + for idx in range(self.unique_Y_labels.shape[0]): + if self.unique_Y_labels[idx] == outlier_label: + self.outlier_label_index = idx + + # Map from set of unique labels to their indices in `class_scores` + # Buffer used in building a histogram for one-pass weighted mode + self.class_scores = np.zeros( + (self.n_samples_X, unique_Y_labels.shape[0]), dtype=np.float64, + ) + + + cdef inline void weighted_histogram_mode( + self, + intp_t sample_index, + intp_t sample_n_neighbors, + intp_t* indices, + float64_t* distances, + ) noexcept nogil: + cdef: + intp_t neighbor_idx, neighbor_class_idx, label_index + float64_t score_incr = 1 + bint use_distance_weighting = ( + self.weight_type == WeightingStrategy.distance + ) + + if sample_n_neighbors == 0: + self.outliers_exist = True + self.outliers[sample_index] = True + if self.outlier_label_index >= 0: + self.class_scores[sample_index][self.outlier_label_index] = score_incr + + return + + # Iterate over the neighbors. This can be different for + # each of the samples as they are based on the radius. + for neighbor_rank in range(sample_n_neighbors): + if use_distance_weighting: + score_incr = 1 / distances[neighbor_rank] + + neighbor_idx = indices[neighbor_rank] + neighbor_class_idx = self.Y_labels[neighbor_idx] + self.class_scores[sample_index][neighbor_class_idx] += score_incr + + return + + @final + cdef void _parallel_on_X_prange_iter_finalize( + self, + intp_t thread_num, + intp_t X_start, + intp_t X_end, + ) noexcept nogil: + cdef: + intp_t idx + + for idx in range(X_start, X_end): + self.weighted_histogram_mode( + sample_index=idx, + sample_n_neighbors=deref(self.neigh_indices)[idx].size(), + indices=deref(self.neigh_indices)[idx].data(), + distances=deref(self.neigh_distances)[idx].data(), + ) + + return + + @final + cdef void _parallel_on_Y_finalize( + self, + ) noexcept nogil: + cdef: + intp_t idx + + with nogil, parallel(num_threads=self.effective_n_threads): + # Merge vectors used in threads into the main ones. + # This is done in parallel sample-wise (no need for locks). + for idx in prange(self.n_samples_X, schedule='static'): + self._merge_vectors(idx, self.chunks_n_threads) + + for idx in prange(self.n_samples_X, schedule='static'): + self.weighted_histogram_mode( + sample_index=idx, + sample_n_neighbors=deref(self.neigh_indices)[idx].size(), + indices=deref(self.neigh_indices)[idx].data(), + distances=deref(self.neigh_distances)[idx].data(), + ) + + return + + def _finalize_results(self): + if self.outliers_exist and self.outlier_label is None: + raise ValueError( + "No neighbors found for test samples %r, " + "you can try using larger radius, " + "giving a label for outliers, " + "or considering removing them from your dataset." + % np.where(self.outliers)[0] + ) + + if self.outliers_exist and self.outlier_label_index < 0: + warnings.warn( + "Outlier label %s is not in training " + "classes. All class probabilities of " + "outliers will be assigned with 0." + % self.outlier_label + ) + + probabilities = np.asarray(self.class_scores) + normalizer = probabilities.sum(axis=1, keepdims=True) + normalizer[normalizer == 0.0] = 1.0 + probabilities /= normalizer + return probabilities + +{{endfor}} diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..0f7eaa286399c5319d16d2c413d7be1957a10d74 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/meson.build @@ -0,0 +1,193 @@ +# Note: the dependencies between different Cython files in +# _pairwise_distances_reduction is probably one of the most involved in +# scikit-learn. If you change this file make sure you build from scratch: +# rm -rf build; make dev-meson +# run a command like this: +# ninja -C build/cp312 -t missingdeps +# and make sure that the output is something like: +# No missing dependencies on generated files found. + +# _pairwise_distances_reduction is cimported from other subpackages so this is +# needed for the cimport to work +_pairwise_distances_reduction_cython_tree = [ + fs.copyfile('__init__.py'), + # We are in a sub-module of metrics, so we always need to have + # sklearn/metrics/__init__.py copied to the build directory to avoid the + # error: + # relative cimport beyond main package is not allowed + metrics_cython_tree +] + +_classmode_pxd = fs.copyfile('_classmode.pxd') + +_datasets_pair_pxd = custom_target( + '_datasets_pair_pxd', + output: '_datasets_pair.pxd', + input: '_datasets_pair.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'] +) +_datasets_pair_pyx = custom_target( + '_datasets_pair_pyx', + output: '_datasets_pair.pyx', + input: '_datasets_pair.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_datasets_pair_pxd, _pairwise_distances_reduction_cython_tree, utils_cython_tree], +) +_datasets_pair = py.extension_module( + '_datasets_pair', + cython_gen_cpp.process(_datasets_pair_pyx), + dependencies: [np_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_base_pxd = custom_target( + '_base_pxd', + output: '_base.pxd', + input: '_base.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'] +) +_base_pyx = custom_target( + '_base_pyx', + output: '_base.pyx', + input: '_base.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_base_pxd, _pairwise_distances_reduction_cython_tree, + _datasets_pair_pxd, utils_cython_tree], +) +_base = py.extension_module( + '_base', + cython_gen_cpp.process(_base_pyx), + dependencies: [np_dep, openmp_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_middle_term_computer_pxd = custom_target( + '_middle_term_computer_pxd', + output: '_middle_term_computer.pxd', + input: '_middle_term_computer.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'] +) +_middle_term_computer_pyx = custom_target( + '_middle_term_computer_pyx', + output: '_middle_term_computer.pyx', + input: '_middle_term_computer.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_middle_term_computer_pxd, + _pairwise_distances_reduction_cython_tree, + utils_cython_tree], +) +_middle_term_computer = py.extension_module( + '_middle_term_computer', + cython_gen_cpp.process(_middle_term_computer_pyx), + dependencies: [np_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_argkmin_pxd = custom_target( + '_argkmin_pxd', + output: '_argkmin.pxd', + input: '_argkmin.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'] + ) +_argkmin_pyx = custom_target( + '_argkmin_pyx', + output: '_argkmin.pyx', + input: '_argkmin.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_argkmin_pxd, + _pairwise_distances_reduction_cython_tree, + _datasets_pair_pxd, _base_pxd, _middle_term_computer_pxd], + ) +_argkmin = py.extension_module( + '_argkmin', + cython_gen_cpp.process(_argkmin_pyx), + dependencies: [np_dep, openmp_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_radius_neighbors_pxd = custom_target( + '_radius_neighbors_pxd', + output: '_radius_neighbors.pxd', + input: '_radius_neighbors.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'] + ) +_radius_neighbors_pyx = custom_target( + '_radius_neighbors_pyx', + output: '_radius_neighbors.pyx', + input: '_radius_neighbors.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_radius_neighbors_pxd, + _datasets_pair_pxd, _base_pxd, _middle_term_computer_pxd, + _pairwise_distances_reduction_cython_tree, utils_cython_tree], +) +_radius_neighbors = py.extension_module( + '_radius_neighbors', + cython_gen_cpp.process(_radius_neighbors_pyx), + dependencies: [np_dep, openmp_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_argkmin_classmode_pyx = custom_target( + '_argkmin_classmode_pyx', + output: '_argkmin_classmode.pyx', + input: '_argkmin_classmode.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_classmode_pxd, + _argkmin_pxd, _pairwise_distances_reduction_cython_tree, + _datasets_pair_pxd, _base_pxd, _middle_term_computer_pxd, utils_cython_tree], +) +_argkmin_classmode = py.extension_module( + '_argkmin_classmode', + cython_gen_cpp.process(_argkmin_classmode_pyx), + dependencies: [np_dep, openmp_dep], + # XXX: for some reason -fno-sized-deallocation is needed otherwise there is + # an error with undefined symbol _ZdlPv at import time in manylinux wheels. + # See https://github.com/scikit-learn/scikit-learn/issues/28596 for more details. + cpp_args: ['-fno-sized-deallocation'], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) + +_radius_neighbors_classmode_pyx = custom_target( + '_radius_neighbors_classmode_pyx', + output: '_radius_neighbors_classmode.pyx', + input: '_radius_neighbors_classmode.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: [_classmode_pxd, + _middle_term_computer_pxd, _radius_neighbors_pxd, + _pairwise_distances_reduction_cython_tree, + _datasets_pair_pxd, _base_pxd, utils_cython_tree], +) +_radius_neighbors_classmode = py.extension_module( + '_radius_neighbors_classmode', + cython_gen_cpp.process(_radius_neighbors_classmode_pyx), + dependencies: [np_dep, openmp_dep], + subdir: 'sklearn/metrics/_pairwise_distances_reduction', + install: true +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.pyx new file mode 100644 index 0000000000000000000000000000000000000000..bf4ded09b2610eef7949cd56e5270b77cb2ce4db --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.pyx @@ -0,0 +1,107 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from cython cimport floating +from cython.parallel cimport prange +from libc.math cimport fabs + +from ..utils._typedefs cimport intp_t + +from ..utils._openmp_helpers import _openmp_effective_n_threads + + +def _chi2_kernel_fast(floating[:, :] X, + floating[:, :] Y, + floating[:, :] result): + cdef intp_t i, j, k + cdef intp_t n_samples_X = X.shape[0] + cdef intp_t n_samples_Y = Y.shape[0] + cdef intp_t n_features = X.shape[1] + cdef double res, nom, denom + + with nogil: + for i in range(n_samples_X): + for j in range(n_samples_Y): + res = 0 + for k in range(n_features): + denom = (X[i, k] - Y[j, k]) + nom = (X[i, k] + Y[j, k]) + if nom != 0: + res += denom * denom / nom + result[i, j] = -res + + +def _sparse_manhattan( + const floating[::1] X_data, + const int[:] X_indices, + const int[:] X_indptr, + const floating[::1] Y_data, + const int[:] Y_indices, + const int[:] Y_indptr, + double[:, ::1] D, +): + """Pairwise L1 distances for CSR matrices. + + Usage: + >>> D = np.zeros(X.shape[0], Y.shape[0]) + >>> _sparse_manhattan(X.data, X.indices, X.indptr, + ... Y.data, Y.indices, Y.indptr, + ... D) + """ + cdef intp_t px, py, i, j, ix, iy + cdef double d = 0.0 + + cdef int m = D.shape[0] + cdef int n = D.shape[1] + + cdef int X_indptr_end = 0 + cdef int Y_indptr_end = 0 + + cdef int num_threads = _openmp_effective_n_threads() + + # We scan the matrices row by row. + # Given row px in X and row py in Y, we find the positions (i and j + # respectively), in .indices where the indices for the two rows start. + # If the indices (ix and iy) are the same, the corresponding data values + # are processed and the cursors i and j are advanced. + # If not, the lowest index is considered. Its associated data value is + # processed and its cursor is advanced. + # We proceed like this until one of the cursors hits the end for its row. + # Then we process all remaining data values in the other row. + + # Below the avoidance of inplace operators is intentional. + # When prange is used, the inplace operator has a special meaning, i.e. it + # signals a "reduction" + + for px in prange(m, nogil=True, num_threads=num_threads): + X_indptr_end = X_indptr[px + 1] + for py in range(n): + Y_indptr_end = Y_indptr[py + 1] + i = X_indptr[px] + j = Y_indptr[py] + d = 0.0 + while i < X_indptr_end and j < Y_indptr_end: + ix = X_indices[i] + iy = Y_indices[j] + + if ix == iy: + d = d + fabs(X_data[i] - Y_data[j]) + i = i + 1 + j = j + 1 + elif ix < iy: + d = d + fabs(X_data[i]) + i = i + 1 + else: + d = d + fabs(Y_data[j]) + j = j + 1 + + if i == X_indptr_end: + while j < Y_indptr_end: + d = d + fabs(Y_data[j]) + j = j + 1 + else: + while i < X_indptr_end: + d = d + fabs(X_data[i]) + i = i + 1 + + D[px, py] = d diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67dd18fb94b593f0a3125c1f5833f3b9597614ba --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/__init__.py @@ -0,0 +1,2 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py new file mode 100644 index 0000000000000000000000000000000000000000..cee515bebe08e859268c27c5441ce3450434d817 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/confusion_matrix.py @@ -0,0 +1,499 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from itertools import product + +import numpy as np + +from ...base import is_classifier +from ...utils._optional_dependencies import check_matplotlib_support +from ...utils._plotting import _validate_style_kwargs +from ...utils.multiclass import unique_labels +from .. import confusion_matrix + + +class ConfusionMatrixDisplay: + """Confusion Matrix visualization. + + It is recommended to use + :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_estimator` or + :func:`~sklearn.metrics.ConfusionMatrixDisplay.from_predictions` to + create a :class:`ConfusionMatrixDisplay`. All parameters are stored as + attributes. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + Parameters + ---------- + confusion_matrix : ndarray of shape (n_classes, n_classes) + Confusion matrix. + + display_labels : ndarray of shape (n_classes,), default=None + Display labels for plot. If None, display labels are set from 0 to + `n_classes - 1`. + + Attributes + ---------- + im_ : matplotlib AxesImage + Image representing the confusion matrix. + + text_ : ndarray of shape (n_classes, n_classes), dtype=matplotlib Text, \ + or None + Array of matplotlib axes. `None` if `include_values` is false. + + ax_ : matplotlib Axes + Axes with confusion matrix. + + figure_ : matplotlib Figure + Figure containing the confusion matrix. + + See Also + -------- + confusion_matrix : Compute Confusion Matrix to evaluate the accuracy of a + classification. + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> predictions = clf.predict(X_test) + >>> cm = confusion_matrix(y_test, predictions, labels=clf.classes_) + >>> disp = ConfusionMatrixDisplay(confusion_matrix=cm, + ... display_labels=clf.classes_) + >>> disp.plot() + <...> + >>> plt.show() + """ + + def __init__(self, confusion_matrix, *, display_labels=None): + self.confusion_matrix = confusion_matrix + self.display_labels = display_labels + + def plot( + self, + *, + include_values=True, + cmap="viridis", + xticks_rotation="horizontal", + values_format=None, + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot visualization. + + Parameters + ---------- + include_values : bool, default=True + Includes values in confusion matrix. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, + the format specification is 'd' or '.2g' whichever is shorter. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + Returns a :class:`~sklearn.metrics.ConfusionMatrixDisplay` instance + that contains all the information to plot the confusion matrix. + """ + check_matplotlib_support("ConfusionMatrixDisplay.plot") + import matplotlib.pyplot as plt + + if ax is None: + fig, ax = plt.subplots() + else: + fig = ax.figure + + cm = self.confusion_matrix + n_classes = cm.shape[0] + + default_im_kw = dict(interpolation="nearest", cmap=cmap) + im_kw = im_kw or {} + im_kw = _validate_style_kwargs(default_im_kw, im_kw) + text_kw = text_kw or {} + + self.im_ = ax.imshow(cm, **im_kw) + self.text_ = None + cmap_min, cmap_max = self.im_.cmap(0), self.im_.cmap(1.0) + + if include_values: + self.text_ = np.empty_like(cm, dtype=object) + + # print text with appropriate color depending on background + thresh = (cm.max() + cm.min()) / 2.0 + + for i, j in product(range(n_classes), range(n_classes)): + color = cmap_max if cm[i, j] < thresh else cmap_min + + if values_format is None: + text_cm = format(cm[i, j], ".2g") + if cm.dtype.kind != "f": + text_d = format(cm[i, j], "d") + if len(text_d) < len(text_cm): + text_cm = text_d + else: + text_cm = format(cm[i, j], values_format) + + default_text_kwargs = dict(ha="center", va="center", color=color) + text_kwargs = _validate_style_kwargs(default_text_kwargs, text_kw) + + self.text_[i, j] = ax.text(j, i, text_cm, **text_kwargs) + + if self.display_labels is None: + display_labels = np.arange(n_classes) + else: + display_labels = self.display_labels + if colorbar: + fig.colorbar(self.im_, ax=ax) + ax.set( + xticks=np.arange(n_classes), + yticks=np.arange(n_classes), + xticklabels=display_labels, + yticklabels=display_labels, + ylabel="True label", + xlabel="Predicted label", + ) + + ax.set_ylim((n_classes - 0.5, -0.5)) + plt.setp(ax.get_xticklabels(), rotation=xticks_rotation) + + self.figure_ = fig + self.ax_ = ax + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + labels=None, + sample_weight=None, + normalize=None, + display_labels=None, + include_values=True, + xticks_rotation="horizontal", + values_format=None, + cmap="viridis", + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot Confusion Matrix given an estimator and some data. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the confusion matrix. This may be used to + reorder or select a subset of labels. If `None` is given, those + that appear at least once in `y_true` or `y_pred` are used in + sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + normalize : {'true', 'pred', 'all'}, default=None + Either to normalize the counts display in the matrix: + + - if `'true'`, the confusion matrix is normalized over the true + conditions (e.g. rows); + - if `'pred'`, the confusion matrix is normalized over the + predicted conditions (e.g. columns); + - if `'all'`, the confusion matrix is normalized by the total + number of samples; + - if `None` (default), the confusion matrix will not be normalized. + + display_labels : array-like of shape (n_classes,), default=None + Target names used for plotting. By default, `labels` will be used + if it is defined, otherwise the unique labels of `y_true` and + `y_pred` will be used. + + include_values : bool, default=True + Includes values in confusion matrix. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, the + format specification is 'd' or '.2g' whichever is shorter. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + + See Also + -------- + ConfusionMatrixDisplay.from_predictions : Plot the confusion matrix + given the true and predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> ConfusionMatrixDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + + For a detailed example of using a confusion matrix to evaluate a + Support Vector Classifier, please see + :ref:`sphx_glr_auto_examples_model_selection_plot_confusion_matrix.py` + """ + method_name = f"{cls.__name__}.from_estimator" + check_matplotlib_support(method_name) + if not is_classifier(estimator): + raise ValueError(f"{method_name} only supports classifiers") + y_pred = estimator.predict(X) + + return cls.from_predictions( + y, + y_pred, + sample_weight=sample_weight, + labels=labels, + normalize=normalize, + display_labels=display_labels, + include_values=include_values, + cmap=cmap, + ax=ax, + xticks_rotation=xticks_rotation, + values_format=values_format, + colorbar=colorbar, + im_kw=im_kw, + text_kw=text_kw, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + labels=None, + sample_weight=None, + normalize=None, + display_labels=None, + include_values=True, + xticks_rotation="horizontal", + values_format=None, + cmap="viridis", + ax=None, + colorbar=True, + im_kw=None, + text_kw=None, + ): + """Plot Confusion Matrix given true and predicted labels. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_pred : array-like of shape (n_samples,) + The predicted labels given by the method `predict` of an + classifier. + + labels : array-like of shape (n_classes,), default=None + List of labels to index the confusion matrix. This may be used to + reorder or select a subset of labels. If `None` is given, those + that appear at least once in `y_true` or `y_pred` are used in + sorted order. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + normalize : {'true', 'pred', 'all'}, default=None + Either to normalize the counts display in the matrix: + + - if `'true'`, the confusion matrix is normalized over the true + conditions (e.g. rows); + - if `'pred'`, the confusion matrix is normalized over the + predicted conditions (e.g. columns); + - if `'all'`, the confusion matrix is normalized by the total + number of samples; + - if `None` (default), the confusion matrix will not be normalized. + + display_labels : array-like of shape (n_classes,), default=None + Target names used for plotting. By default, `labels` will be used + if it is defined, otherwise the unique labels of `y_true` and + `y_pred` will be used. + + include_values : bool, default=True + Includes values in confusion matrix. + + xticks_rotation : {'vertical', 'horizontal'} or float, \ + default='horizontal' + Rotation of xtick labels. + + values_format : str, default=None + Format specification for values in confusion matrix. If `None`, the + format specification is 'd' or '.2g' whichever is shorter. + + cmap : str or matplotlib Colormap, default='viridis' + Colormap recognized by matplotlib. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + colorbar : bool, default=True + Whether or not to add a colorbar to the plot. + + im_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.imshow` call. + + text_kw : dict, default=None + Dict with keywords passed to `matplotlib.pyplot.text` call. + + .. versionadded:: 1.2 + + Returns + ------- + display : :class:`~sklearn.metrics.ConfusionMatrixDisplay` + + See Also + -------- + ConfusionMatrixDisplay.from_estimator : Plot the confusion matrix + given an estimator, the data, and the label. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import ConfusionMatrixDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> y_pred = clf.predict(X_test) + >>> ConfusionMatrixDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + if display_labels is None: + if labels is None: + display_labels = unique_labels(y_true, y_pred) + else: + display_labels = labels + + cm = confusion_matrix( + y_true, + y_pred, + sample_weight=sample_weight, + labels=labels, + normalize=normalize, + ) + + disp = cls(confusion_matrix=cm, display_labels=display_labels) + + return disp.plot( + include_values=include_values, + cmap=cmap, + ax=ax, + xticks_rotation=xticks_rotation, + values_format=values_format, + colorbar=colorbar, + im_kw=im_kw, + text_kw=text_kw, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..590b908d917232d9e43b0f8492710ee978ce989c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/det_curve.py @@ -0,0 +1,371 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +import scipy as sp + +from ...utils._plotting import _BinaryClassifierCurveDisplayMixin +from .._ranking import det_curve + + +class DetCurveDisplay(_BinaryClassifierCurveDisplayMixin): + """Detection Error Tradeoff (DET) curve visualization. + + It is recommended to use :func:`~sklearn.metrics.DetCurveDisplay.from_estimator` + or :func:`~sklearn.metrics.DetCurveDisplay.from_predictions` to create a + visualizer. All parameters are stored as attributes. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + fpr : ndarray + False positive rate. + + fnr : ndarray + False negative rate. + + estimator_name : str, default=None + Name of estimator. If None, the estimator name is not shown. + + pos_label : int, float, bool or str, default=None + The label of the positive class. + + Attributes + ---------- + line_ : matplotlib Artist + DET Curve. + + ax_ : matplotlib Axes + Axes with DET Curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import det_curve, DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_pred = clf.decision_function(X_test) + >>> fpr, fnr, _ = det_curve(y_test, y_pred) + >>> display = DetCurveDisplay( + ... fpr=fpr, fnr=fnr, estimator_name="SVC" + ... ) + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, fpr, fnr, estimator_name=None, pos_label=None): + self.fpr = fpr + self.fnr = fnr + self.estimator_name = estimator_name + self.pos_label = pos_label + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + drop_intermediate=True, + response_method="auto", + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot DET curve given an estimator and data. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop thresholds where true positives (tp) do not change + from the previous or subsequent threshold. All points with the same + tp value have the same `fnr` and thus same y coordinate. + + .. versionadded:: 1.7 + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the predicted target response. If set + to 'auto', :term:`predict_proba` is tried first and if it does not + exist :term:`decision_function` is tried next. + + pos_label : int, float, bool or str, default=None + The label of the positive class. When `pos_label=None`, if `y_true` + is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an + error will be raised. + + name : str, default=None + Name of DET curve for labeling. If `None`, use the name of the + estimator. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> DetCurveDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + y_pred, pos_label, name = cls._validate_and_get_response_values( + estimator, + X, + y, + response_method=response_method, + pos_label=pos_label, + name=name, + ) + + return cls.from_predictions( + y_true=y, + y_pred=y_pred, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + name=name, + ax=ax, + pos_label=pos_label, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + sample_weight=None, + drop_intermediate=True, + pos_label=None, + name=None, + ax=None, + **kwargs, + ): + """Plot the DET curve given the true and predicted labels. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_pred : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by `decision_function` on some classifiers). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop thresholds where true positives (tp) do not change + from the previous or subsequent threshold. All points with the same + tp value have the same `fnr` and thus same y coordinate. + + .. versionadded:: 1.7 + + pos_label : int, float, bool or str, default=None + The label of the positive class. When `pos_label=None`, if `y_true` + is in {-1, 1} or {0, 1}, `pos_label` is set to 1, otherwise an + error will be raised. + + name : str, default=None + Name of DET curve for labeling. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + + See Also + -------- + det_curve : Compute error rates for different probability thresholds. + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import DetCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(n_samples=1000, random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.4, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_pred = clf.decision_function(X_test) + >>> DetCurveDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + pos_label_validated, name = cls._validate_from_predictions_params( + y_true, y_pred, sample_weight=sample_weight, pos_label=pos_label, name=name + ) + + fpr, fnr, _ = det_curve( + y_true, + y_pred, + pos_label=pos_label, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + ) + + viz = cls( + fpr=fpr, + fnr=fnr, + estimator_name=name, + pos_label=pos_label_validated, + ) + + return viz.plot(ax=ax, name=name, **kwargs) + + def plot(self, ax=None, *, name=None, **kwargs): + """Plot visualization. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of DET curve for labeling. If `None`, use `estimator_name` if + it is not `None`, otherwise no labeling is shown. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + Returns + ------- + display : :class:`~sklearn.metrics.DetCurveDisplay` + Object that stores computed values. + """ + self.ax_, self.figure_, name = self._validate_plot_params(ax=ax, name=name) + + line_kwargs = {} if name is None else {"label": name} + line_kwargs.update(**kwargs) + + # We have the following bounds: + # sp.stats.norm.ppf(0.0) = -np.inf + # sp.stats.norm.ppf(1.0) = np.inf + # We therefore clip to eps and 1 - eps to not provide infinity to matplotlib. + eps = np.finfo(self.fpr.dtype).eps + self.fpr = self.fpr.clip(eps, 1 - eps) + self.fnr = self.fnr.clip(eps, 1 - eps) + + (self.line_,) = self.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 + self.ax_.set(xlabel=xlabel, ylabel=ylabel) + + if "label" in line_kwargs: + self.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 + ] + self.ax_.set_xticks(tick_locations) + self.ax_.set_xticklabels(tick_labels) + self.ax_.set_xlim(-3, 3) + self.ax_.set_yticks(tick_locations) + self.ax_.set_yticklabels(tick_labels) + self.ax_.set_ylim(-3, 3) + + return self diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..30dd1fba08761f12d74d75743b4985aca3442d59 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/precision_recall_curve.py @@ -0,0 +1,555 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from collections import Counter + +from ...utils._plotting import ( + _BinaryClassifierCurveDisplayMixin, + _despine, + _validate_style_kwargs, +) +from .._ranking import average_precision_score, precision_recall_curve + + +class PrecisionRecallDisplay(_BinaryClassifierCurveDisplayMixin): + """Precision Recall visualization. + + It is recommended to use + :func:`~sklearn.metrics.PrecisionRecallDisplay.from_estimator` or + :func:`~sklearn.metrics.PrecisionRecallDisplay.from_predictions` to create + a :class:`~sklearn.metrics.PrecisionRecallDisplay`. All parameters are + stored as attributes. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + Parameters + ---------- + precision : ndarray + Precision values. + + recall : ndarray + Recall values. + + average_precision : float, default=None + Average precision. If None, the average precision is not shown. + + estimator_name : str, default=None + Name of estimator. If None, then the estimator name is not shown. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class. If None, the class will not + be shown in the legend. + + .. versionadded:: 0.24 + + prevalence_pos_label : float, default=None + The prevalence of the positive label. It is used for plotting the + chance level line. If None, the chance level line will not be plotted + even if `plot_chance_level` is set to True when plotting. + + .. versionadded:: 1.3 + + Attributes + ---------- + line_ : matplotlib Artist + Precision recall curve. + + chance_level_ : matplotlib Artist or None + The chance level line. It is `None` if the chance level is not plotted. + + .. versionadded:: 1.3 + + ax_ : matplotlib Axes + Axes with precision recall curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given + a binary classifier. + PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve + using predictions from a binary classifier. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) in + scikit-learn is computed without any interpolation. To be consistent with + this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"` in :meth:`plot`, :meth:`from_estimator`, or + :meth:`from_predictions`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import (precision_recall_curve, + ... PrecisionRecallDisplay) + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=0) + >>> clf = SVC(random_state=0) + >>> clf.fit(X_train, y_train) + SVC(random_state=0) + >>> predictions = clf.predict(X_test) + >>> precision, recall, _ = precision_recall_curve(y_test, predictions) + >>> disp = PrecisionRecallDisplay(precision=precision, recall=recall) + >>> disp.plot() + <...> + >>> plt.show() + """ + + def __init__( + self, + precision, + recall, + *, + average_precision=None, + estimator_name=None, + pos_label=None, + prevalence_pos_label=None, + ): + self.estimator_name = estimator_name + self.precision = precision + self.recall = recall + self.average_precision = average_precision + self.pos_label = pos_label + self.prevalence_pos_label = prevalence_pos_label + + def plot( + self, + ax=None, + *, + name=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + **kwargs, + ): + """Plot visualization. + + Extra keyword arguments will be passed to matplotlib's `plot`. + + Parameters + ---------- + ax : Matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str, default=None + Name of precision recall curve for labeling. If `None`, use + `estimator_name` if not `None`, otherwise no labeling is shown. + + plot_chance_level : bool, default=False + Whether to plot the chance level. The chance level is the prevalence + of the positive label computed from the data passed during + :meth:`from_estimator` or :meth:`from_predictions` call. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + Object that stores computed values. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + """ + self.ax_, self.figure_, name = self._validate_plot_params(ax=ax, name=name) + + default_line_kwargs = {"drawstyle": "steps-post"} + if self.average_precision is not None and name is not None: + default_line_kwargs["label"] = ( + f"{name} (AP = {self.average_precision:0.2f})" + ) + elif self.average_precision is not None: + default_line_kwargs["label"] = f"AP = {self.average_precision:0.2f}" + elif name is not None: + default_line_kwargs["label"] = name + + line_kwargs = _validate_style_kwargs(default_line_kwargs, kwargs) + + (self.line_,) = self.ax_.plot(self.recall, self.precision, **line_kwargs) + + info_pos_label = ( + f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" + ) + + xlabel = "Recall" + info_pos_label + ylabel = "Precision" + info_pos_label + self.ax_.set( + xlabel=xlabel, + xlim=(-0.01, 1.01), + ylabel=ylabel, + ylim=(-0.01, 1.01), + aspect="equal", + ) + + if plot_chance_level: + if self.prevalence_pos_label is None: + raise ValueError( + "You must provide prevalence_pos_label when constructing the " + "PrecisionRecallDisplay object in order to plot the chance " + "level line. Alternatively, you may use " + "PrecisionRecallDisplay.from_estimator or " + "PrecisionRecallDisplay.from_predictions " + "to automatically set prevalence_pos_label" + ) + + default_chance_level_line_kw = { + "label": f"Chance level (AP = {self.prevalence_pos_label:0.2f})", + "color": "k", + "linestyle": "--", + } + + if chance_level_kw is None: + chance_level_kw = {} + + chance_level_line_kw = _validate_style_kwargs( + default_chance_level_line_kw, chance_level_kw + ) + + (self.chance_level_,) = self.ax_.plot( + (0, 1), + (self.prevalence_pos_label, self.prevalence_pos_label), + **chance_level_line_kw, + ) + else: + self.chance_level_ = None + + if despine: + _despine(self.ax_) + + if "label" in line_kwargs or plot_chance_level: + self.ax_.legend(loc="lower left") + + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + drop_intermediate=False, + response_method="auto", + pos_label=None, + name=None, + ax=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + **kwargs, + ): + """Plot precision-recall curve given an estimator and some data. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=False + Whether to drop some suboptimal thresholds which would not appear + on a plotted precision-recall curve. This is useful in order to + create lighter precision-recall curves. + + .. versionadded:: 1.3 + + response_method : {'predict_proba', 'decision_function', 'auto'}, \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing the + precision and recall metrics. By default, `estimators.classes_[1]` + is considered as the positive class. + + name : str, default=None + Name for labeling curve. If `None`, no name is used. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + plot_chance_level : bool, default=False + Whether to plot the chance level. The chance level is the prevalence + of the positive label computed from the data passed during + :meth:`from_estimator` or :meth:`from_predictions` call. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + + See Also + -------- + PrecisionRecallDisplay.from_predictions : Plot precision-recall curve + using estimated probabilities or output of decision function. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import PrecisionRecallDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression() + >>> clf.fit(X_train, y_train) + LogisticRegression() + >>> PrecisionRecallDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + y_pred, pos_label, name = cls._validate_and_get_response_values( + estimator, + X, + y, + response_method=response_method, + pos_label=pos_label, + name=name, + ) + + return cls.from_predictions( + y, + y_pred, + sample_weight=sample_weight, + name=name, + pos_label=pos_label, + drop_intermediate=drop_intermediate, + ax=ax, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + despine=despine, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + sample_weight=None, + drop_intermediate=False, + pos_label=None, + name=None, + ax=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + **kwargs, + ): + """Plot precision-recall curve given binary class predictions. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True binary labels. + + y_pred : array-like of shape (n_samples,) + Estimated probabilities or output of decision function. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=False + Whether to drop some suboptimal thresholds which would not appear + on a plotted precision-recall curve. This is useful in order to + create lighter precision-recall curves. + + .. versionadded:: 1.3 + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing the + precision and recall metrics. + + name : str, default=None + Name for labeling curve. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + plot_chance_level : bool, default=False + Whether to plot the chance level. The chance level is the prevalence + of the positive label computed from the data passed during + :meth:`from_estimator` or :meth:`from_predictions` call. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + Returns + ------- + display : :class:`~sklearn.metrics.PrecisionRecallDisplay` + + See Also + -------- + PrecisionRecallDisplay.from_estimator : Plot precision-recall curve + using an estimator. + + Notes + ----- + The average precision (cf. :func:`~sklearn.metrics.average_precision_score`) + in scikit-learn is computed without any interpolation. To be consistent + with this metric, the precision-recall curve is plotted without any + interpolation as well (step-wise style). + + You can change this style by passing the keyword argument + `drawstyle="default"`. However, the curve will not be strictly + consistent with the reported average precision. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import PrecisionRecallDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = LogisticRegression() + >>> clf.fit(X_train, y_train) + LogisticRegression() + >>> y_pred = clf.predict_proba(X_test)[:, 1] + >>> PrecisionRecallDisplay.from_predictions( + ... y_test, y_pred) + <...> + >>> plt.show() + """ + pos_label, name = cls._validate_from_predictions_params( + y_true, y_pred, sample_weight=sample_weight, pos_label=pos_label, name=name + ) + + precision, recall, _ = precision_recall_curve( + y_true, + y_pred, + pos_label=pos_label, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + ) + average_precision = average_precision_score( + y_true, y_pred, pos_label=pos_label, sample_weight=sample_weight + ) + + class_count = Counter(y_true) + prevalence_pos_label = class_count[pos_label] / sum(class_count.values()) + + viz = cls( + precision=precision, + recall=recall, + average_precision=average_precision, + estimator_name=name, + pos_label=pos_label, + prevalence_pos_label=prevalence_pos_label, + ) + + return viz.plot( + ax=ax, + name=name, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + despine=despine, + **kwargs, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py new file mode 100644 index 0000000000000000000000000000000000000000..1b56859cabefd181eafec383a1aa48c2a28807a4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/regression.py @@ -0,0 +1,413 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers + +import numpy as np + +from ...utils import _safe_indexing, check_random_state +from ...utils._optional_dependencies import check_matplotlib_support +from ...utils._plotting import _validate_style_kwargs + + +class PredictionErrorDisplay: + """Visualization of the prediction error of a regression model. + + This tool can display "residuals vs predicted" or "actual vs predicted" + using scatter plots to qualitatively assess the behavior of a regressor, + preferably on held-out data points. + + See the details in the docstrings of + :func:`~sklearn.metrics.PredictionErrorDisplay.from_estimator` or + :func:`~sklearn.metrics.PredictionErrorDisplay.from_predictions` to + create a visualizer. All parameters are stored as attributes. + + For general information regarding `scikit-learn` visualization tools, read + more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True values. + + y_pred : ndarray of shape (n_samples,) + Prediction values. + + Attributes + ---------- + line_ : matplotlib Artist + Optimal line representing `y_true == y_pred`. Therefore, it is a + diagonal line for `kind="predictions"` and a horizontal line for + `kind="residuals"`. + + errors_lines_ : matplotlib Artist or None + Residual lines. If `with_errors=False`, then it is set to `None`. + + scatter_ : matplotlib Artist + Scatter data points. + + ax_ : matplotlib Axes + Axes with the different matplotlib axis. + + figure_ : matplotlib Figure + Figure containing the scatter and lines. + + See Also + -------- + PredictionErrorDisplay.from_estimator : Prediction error visualization + given an estimator and some data. + PredictionErrorDisplay.from_predictions : Prediction error visualization + given the true and predicted targets. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> y_pred = ridge.predict(X) + >>> display = PredictionErrorDisplay(y_true=y, y_pred=y_pred) + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, y_true, y_pred): + self.y_true = y_true + self.y_pred = y_pred + + def plot( + self, + ax=None, + *, + kind="residual_vs_predicted", + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot visualization. + + Extra keyword arguments will be passed to matplotlib's ``plot``. + + Parameters + ---------- + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e. difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.PredictionErrorDisplay` + + Object that stores computed values. + """ + check_matplotlib_support(f"{self.__class__.__name__}.plot") + + expected_kind = ("actual_vs_predicted", "residual_vs_predicted") + if kind not in expected_kind: + raise ValueError( + f"`kind` must be one of {', '.join(expected_kind)}. " + f"Got {kind!r} instead." + ) + + import matplotlib.pyplot as plt + + if scatter_kwargs is None: + scatter_kwargs = {} + if line_kwargs is None: + line_kwargs = {} + + default_scatter_kwargs = {"color": "tab:blue", "alpha": 0.8} + default_line_kwargs = {"color": "black", "alpha": 0.7, "linestyle": "--"} + + scatter_kwargs = _validate_style_kwargs(default_scatter_kwargs, scatter_kwargs) + line_kwargs = _validate_style_kwargs(default_line_kwargs, line_kwargs) + + scatter_kwargs = {**default_scatter_kwargs, **scatter_kwargs} + line_kwargs = {**default_line_kwargs, **line_kwargs} + + if ax is None: + _, ax = plt.subplots() + + if kind == "actual_vs_predicted": + max_value = max(np.max(self.y_true), np.max(self.y_pred)) + min_value = min(np.min(self.y_true), np.min(self.y_pred)) + self.line_ = ax.plot( + [min_value, max_value], [min_value, max_value], **line_kwargs + )[0] + + x_data, y_data = self.y_pred, self.y_true + xlabel, ylabel = "Predicted values", "Actual values" + + self.scatter_ = ax.scatter(x_data, y_data, **scatter_kwargs) + + # force to have a squared axis + ax.set_aspect("equal", adjustable="datalim") + ax.set_xticks(np.linspace(min_value, max_value, num=5)) + ax.set_yticks(np.linspace(min_value, max_value, num=5)) + else: # kind == "residual_vs_predicted" + self.line_ = ax.plot( + [np.min(self.y_pred), np.max(self.y_pred)], + [0, 0], + **line_kwargs, + )[0] + self.scatter_ = ax.scatter( + self.y_pred, self.y_true - self.y_pred, **scatter_kwargs + ) + xlabel, ylabel = "Predicted values", "Residuals (actual - predicted)" + + ax.set(xlabel=xlabel, ylabel=ylabel) + + self.ax_ = ax + self.figure_ = ax.figure + + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + kind="residual_vs_predicted", + subsample=1_000, + random_state=None, + ax=None, + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot the prediction error given a regressor and some data. + + For general information regarding `scikit-learn` visualization tools, + read more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + estimator : estimator instance + Fitted regressor or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a regressor. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e. difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + subsample : float, int or None, default=1_000 + Sampling the samples to be shown on the scatter plot. If `float`, + it should be between 0 and 1 and represents the proportion of the + original dataset. If `int`, it represents the number of samples + display on the scatter plot. If `None`, no subsampling will be + applied. by default, 1000 samples or less will be displayed. + + random_state : int or RandomState, default=None + Controls the randomness when `subsample` is not `None`. + See :term:`Glossary ` for details. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.PredictionErrorDisplay` + Object that stores the computed values. + + See Also + -------- + PredictionErrorDisplay : Prediction error visualization for regression. + PredictionErrorDisplay.from_predictions : Prediction error visualization + given the true and predicted targets. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> disp = PredictionErrorDisplay.from_estimator(ridge, X, y) + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + y_pred = estimator.predict(X) + + return cls.from_predictions( + y_true=y, + y_pred=y_pred, + kind=kind, + subsample=subsample, + random_state=random_state, + ax=ax, + scatter_kwargs=scatter_kwargs, + line_kwargs=line_kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_pred, + *, + kind="residual_vs_predicted", + subsample=1_000, + random_state=None, + ax=None, + scatter_kwargs=None, + line_kwargs=None, + ): + """Plot the prediction error given the true and predicted targets. + + For general information regarding `scikit-learn` visualization tools, + read more in the :ref:`Visualization Guide `. + For details regarding interpreting these plots, refer to the + :ref:`Model Evaluation Guide `. + + .. versionadded:: 1.2 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True target values. + + y_pred : array-like of shape (n_samples,) + Predicted target values. + + kind : {"actual_vs_predicted", "residual_vs_predicted"}, \ + default="residual_vs_predicted" + The type of plot to draw: + + - "actual_vs_predicted" draws the observed values (y-axis) vs. + the predicted values (x-axis). + - "residual_vs_predicted" draws the residuals, i.e. difference + between observed and predicted values, (y-axis) vs. the predicted + values (x-axis). + + subsample : float, int or None, default=1_000 + Sampling the samples to be shown on the scatter plot. If `float`, + it should be between 0 and 1 and represents the proportion of the + original dataset. If `int`, it represents the number of samples + display on the scatter plot. If `None`, no subsampling will be + applied. by default, 1000 samples or less will be displayed. + + random_state : int or RandomState, default=None + Controls the randomness when `subsample` is not `None`. + See :term:`Glossary ` for details. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + scatter_kwargs : dict, default=None + Dictionary with keywords passed to the `matplotlib.pyplot.scatter` + call. + + line_kwargs : dict, default=None + Dictionary with keyword passed to the `matplotlib.pyplot.plot` + call to draw the optimal line. + + Returns + ------- + display : :class:`~sklearn.metrics.PredictionErrorDisplay` + Object that stores the computed values. + + See Also + -------- + PredictionErrorDisplay : Prediction error visualization for regression. + PredictionErrorDisplay.from_estimator : Prediction error visualization + given an estimator and some data. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_diabetes + >>> from sklearn.linear_model import Ridge + >>> from sklearn.metrics import PredictionErrorDisplay + >>> X, y = load_diabetes(return_X_y=True) + >>> ridge = Ridge().fit(X, y) + >>> y_pred = ridge.predict(X) + >>> disp = PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred) + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_predictions") + + random_state = check_random_state(random_state) + + n_samples = len(y_true) + if isinstance(subsample, numbers.Integral): + if subsample <= 0: + raise ValueError( + f"When an integer, subsample={subsample} should be positive." + ) + elif isinstance(subsample, numbers.Real): + if subsample <= 0 or subsample >= 1: + raise ValueError( + f"When a floating-point, subsample={subsample} should" + " be in the (0, 1) range." + ) + subsample = int(n_samples * subsample) + + if subsample is not None and subsample < n_samples: + indices = random_state.choice(np.arange(n_samples), size=subsample) + y_true = _safe_indexing(y_true, indices, axis=0) + y_pred = _safe_indexing(y_pred, indices, axis=0) + + viz = cls( + y_true=y_true, + y_pred=y_pred, + ) + + return viz.plot( + ax=ax, + kind=kind, + scatter_kwargs=scatter_kwargs, + line_kwargs=line_kwargs, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..383f14e688859afe537ccf89da68fe2751bcb5a4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/roc_curve.py @@ -0,0 +1,795 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + + +import warnings + +import numpy as np + +from ...utils import _safe_indexing +from ...utils._plotting import ( + _BinaryClassifierCurveDisplayMixin, + _check_param_lengths, + _convert_to_list_leaving_none, + _deprecate_estimator_name, + _despine, + _validate_style_kwargs, +) +from ...utils._response import _get_response_values_binary +from .._ranking import auc, roc_curve + + +class RocCurveDisplay(_BinaryClassifierCurveDisplayMixin): + """ROC Curve visualization. + + It is recommended to use + :func:`~sklearn.metrics.RocCurveDisplay.from_estimator` or + :func:`~sklearn.metrics.RocCurveDisplay.from_predictions` or + :func:`~sklearn.metrics.RocCurveDisplay.from_cv_results` to create + a :class:`~sklearn.metrics.RocCurveDisplay`. All parameters are + stored as attributes. + + For general information regarding `scikit-learn` visualization tools, see + the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + Parameters + ---------- + fpr : ndarray or list of ndarrays + False positive rates. Each ndarray should contain values for a single curve. + If plotting multiple curves, list should be of same length as `tpr`. + + .. versionchanged:: 1.7 + Now accepts a list for plotting multiple curves. + + tpr : ndarray or list of ndarrays + True positive rates. Each ndarray should contain values for a single curve. + If plotting multiple curves, list should be of same length as `fpr`. + + .. versionchanged:: 1.7 + Now accepts a list for plotting multiple curves. + + roc_auc : float or list of floats, default=None + Area under ROC curve, used for labeling each curve in the legend. + If plotting multiple curves, should be a list of the same length as `fpr` + and `tpr`. If `None`, ROC AUC scores are not shown in the legend. + + .. versionchanged:: 1.7 + Now accepts a list for plotting multiple curves. + + name : str or list of str, default=None + Name for labeling legend entries. The number of legend entries is determined + by the `curve_kwargs` passed to `plot`, and is not affected by `name`. + To label each curve, provide a list of strings. To avoid labeling + individual curves that have the same appearance, this cannot be used in + conjunction with `curve_kwargs` being a dictionary or None. If a + string is provided, it will be used to either label the single legend entry + or if there are multiple legend entries, label each individual curve with + the same name. If still `None`, no name is shown in the legend. + + .. versionadded:: 1.7 + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing the roc auc + metrics. By default, `estimators.classes_[1]` is considered + as the positive class. + + .. versionadded:: 0.24 + + estimator_name : str, default=None + Name of estimator. If None, the estimator name is not shown. + + .. deprecated:: 1.7 + `estimator_name` is deprecated and will be removed in 1.9. Use `name` + instead. + + Attributes + ---------- + line_ : matplotlib Artist or list of matplotlib Artists + ROC Curves. + + .. versionchanged:: 1.7 + This attribute can now be a list of Artists, for when multiple curves + are plotted. + + chance_level_ : matplotlib Artist or None + The chance level line. It is `None` if the chance level is not plotted. + + .. versionadded:: 1.3 + + ax_ : matplotlib Axes + Axes with ROC Curve. + + figure_ : matplotlib Figure + Figure containing the curve. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic + (ROC) curve given an estimator and some data. + RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic + (ROC) curve given the true and predicted values. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from sklearn import metrics + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_score = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score) + >>> roc_auc = metrics.auc(fpr, tpr) + >>> display = metrics.RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, + ... name='example estimator') + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__( + self, + *, + fpr, + tpr, + roc_auc=None, + name=None, + pos_label=None, + estimator_name="deprecated", + ): + self.fpr = fpr + self.tpr = tpr + self.roc_auc = roc_auc + self.name = _deprecate_estimator_name(estimator_name, name, "1.7") + self.pos_label = pos_label + + def _validate_plot_params(self, *, ax, name): + self.ax_, self.figure_, name = super()._validate_plot_params(ax=ax, name=name) + + fpr = _convert_to_list_leaving_none(self.fpr) + tpr = _convert_to_list_leaving_none(self.tpr) + roc_auc = _convert_to_list_leaving_none(self.roc_auc) + name = _convert_to_list_leaving_none(name) + + optional = {"self.roc_auc": roc_auc} + if isinstance(name, list) and len(name) != 1: + optional.update({"'name' (or self.name)": name}) + _check_param_lengths( + required={"self.fpr": fpr, "self.tpr": tpr}, + optional=optional, + class_name="RocCurveDisplay", + ) + return fpr, tpr, roc_auc, name + + def plot( + self, + ax=None, + *, + name=None, + curve_kwargs=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + **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 or list of str, default=None + Name for labeling legend entries. The number of legend entries + is determined by `curve_kwargs`, and is not affected by `name`. + To label each curve, provide a list of strings. To avoid labeling + individual curves that have the same appearance, this cannot be used in + conjunction with `curve_kwargs` being a dictionary or None. If a + string is provided, it will be used to either label the single legend entry + or if there are multiple legend entries, label each individual curve with + the same name. If `None`, set to `name` provided at `RocCurveDisplay` + initialization. If still `None`, no name is shown in the legend. + + .. versionadded:: 1.7 + + curve_kwargs : dict or list of dict, default=None + Keywords arguments to be passed to matplotlib's `plot` function + to draw individual ROC curves. For single curve plotting, should be + a dictionary. For multi-curve plotting, if a list is provided the + parameters are applied to the ROC curves of each CV fold + sequentially and a legend entry is added for each curve. + If a single dictionary is provided, the same parameters are applied + to all ROC curves and a single legend entry for all curves is added, + labeled with the mean ROC AUC score. + + .. versionadded:: 1.7 + + plot_chance_level : bool, default=False + Whether to plot the chance level. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + .. deprecated:: 1.7 + kwargs is deprecated and will be removed in 1.9. Pass matplotlib + arguments to `curve_kwargs` as a dictionary instead. + + Returns + ------- + display : :class:`~sklearn.metrics.RocCurveDisplay` + Object that stores computed values. + """ + fpr, tpr, roc_auc, name = self._validate_plot_params(ax=ax, name=name) + n_curves = len(fpr) + if not isinstance(curve_kwargs, list) and n_curves > 1: + if roc_auc: + legend_metric = {"mean": np.mean(roc_auc), "std": np.std(roc_auc)} + else: + legend_metric = {"mean": None, "std": None} + else: + roc_auc = roc_auc if roc_auc is not None else [None] * n_curves + legend_metric = {"metric": roc_auc} + + curve_kwargs = self._validate_curve_kwargs( + n_curves, + name, + legend_metric, + "AUC", + curve_kwargs=curve_kwargs, + **kwargs, + ) + + default_chance_level_line_kw = { + "label": "Chance level (AUC = 0.5)", + "color": "k", + "linestyle": "--", + } + + if chance_level_kw is None: + chance_level_kw = {} + + chance_level_kw = _validate_style_kwargs( + default_chance_level_line_kw, chance_level_kw + ) + + self.line_ = [] + for fpr, tpr, line_kw in zip(fpr, tpr, curve_kwargs): + self.line_.extend(self.ax_.plot(fpr, tpr, **line_kw)) + # Return single artist if only one curve is plotted + if len(self.line_) == 1: + self.line_ = self.line_[0] + + info_pos_label = ( + f" (Positive label: {self.pos_label})" if self.pos_label is not None else "" + ) + + xlabel = "False Positive Rate" + info_pos_label + ylabel = "True Positive Rate" + info_pos_label + self.ax_.set( + xlabel=xlabel, + xlim=(-0.01, 1.01), + ylabel=ylabel, + ylim=(-0.01, 1.01), + aspect="equal", + ) + + if plot_chance_level: + (self.chance_level_,) = self.ax_.plot((0, 1), (0, 1), **chance_level_kw) + else: + self.chance_level_ = None + + if despine: + _despine(self.ax_) + + if curve_kwargs[0].get("label") is not None or ( + plot_chance_level and chance_level_kw.get("label") is not None + ): + self.ax_.legend(loc="lower right") + + return self + + @classmethod + def from_estimator( + cls, + estimator, + X, + y, + *, + sample_weight=None, + drop_intermediate=True, + response_method="auto", + pos_label=None, + name=None, + ax=None, + curve_kwargs=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + **kwargs, + ): + """Create a ROC Curve display from an estimator. + + For general information regarding `scikit-learn` visualization tools, + see the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + Parameters + ---------- + estimator : estimator instance + Fitted classifier or a fitted :class:`~sklearn.pipeline.Pipeline` + in which the last estimator is a classifier. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop thresholds where the resulting point is collinear + with its neighbors in ROC space. This has no effect on the ROC AUC + or visual shape of the curve, but reduces the number of plotted + points. + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing the ROC AUC. + By default, `estimators.classes_[1]` is considered + as the positive class. + + name : str, default=None + Name of ROC Curve for labeling. If `None`, use the name of the + estimator. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is created. + + curve_kwargs : dict, default=None + Keywords arguments to be passed to matplotlib's `plot` function. + + .. versionadded:: 1.7 + + plot_chance_level : bool, default=False + Whether to plot the chance level. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + **kwargs : dict + Keyword arguments to be passed to matplotlib's `plot`. + + .. deprecated:: 1.7 + kwargs is deprecated and will be removed in 1.9. Pass matplotlib + arguments to `curve_kwargs` as a dictionary instead. + + Returns + ------- + display : :class:`~sklearn.metrics.RocCurveDisplay` + The ROC Curve display. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_predictions : ROC Curve visualization given the + probabilities of scores of a classifier. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import RocCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> RocCurveDisplay.from_estimator( + ... clf, X_test, y_test) + <...> + >>> plt.show() + """ + y_score, pos_label, name = cls._validate_and_get_response_values( + estimator, + X, + y, + response_method=response_method, + pos_label=pos_label, + name=name, + ) + + return cls.from_predictions( + y_true=y, + y_score=y_score, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + name=name, + ax=ax, + curve_kwargs=curve_kwargs, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + despine=despine, + **kwargs, + ) + + @classmethod + def from_predictions( + cls, + y_true, + y_score=None, + *, + sample_weight=None, + drop_intermediate=True, + pos_label=None, + name=None, + ax=None, + curve_kwargs=None, + plot_chance_level=False, + chance_level_kw=None, + despine=False, + y_pred="deprecated", + **kwargs, + ): + """Plot ROC curve given the true and predicted values. + + For general information regarding `scikit-learn` visualization tools, + see the :ref:`Visualization Guide `. + For guidance on interpreting these plots, refer to the :ref:`Model + Evaluation Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_score : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by “decision_function” on some classifiers). + + .. versionadded:: 1.7 + `y_pred` has been renamed to `y_score`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop thresholds where the resulting point is collinear + with its neighbors in ROC space. This has no effect on the ROC AUC + or visual shape of the curve, but reduces the number of plotted + points. + + pos_label : int, float, bool or str, default=None + The label of the positive class when computing the ROC AUC. + When `pos_label=None`, if `y_true` is in {-1, 1} or {0, 1}, `pos_label` + is set to 1, otherwise an error will be raised. + + name : str, default=None + Name of ROC curve for legend labeling. If `None`, name will be set to + `"Classifier"`. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + curve_kwargs : dict, default=None + Keywords arguments to be passed to matplotlib's `plot` function. + + .. versionadded:: 1.7 + + plot_chance_level : bool, default=False + Whether to plot the chance level. + + .. versionadded:: 1.3 + + chance_level_kw : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + .. versionadded:: 1.3 + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + .. versionadded:: 1.6 + + y_pred : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by “decision_function” on some classifiers). + + .. deprecated:: 1.7 + `y_pred` is deprecated and will be removed in 1.9. Use + `y_score` instead. + + **kwargs : dict + Additional keywords arguments passed to matplotlib `plot` function. + + .. deprecated:: 1.7 + kwargs is deprecated and will be removed in 1.9. Pass matplotlib + arguments to `curve_kwargs` as a dictionary instead. + + Returns + ------- + display : :class:`~sklearn.metrics.RocCurveDisplay` + Object that stores computed values. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : ROC Curve visualization given an + estimator and some data. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import RocCurveDisplay + >>> from sklearn.model_selection import train_test_split + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, random_state=0) + >>> clf = SVC(random_state=0).fit(X_train, y_train) + >>> y_score = clf.decision_function(X_test) + >>> RocCurveDisplay.from_predictions(y_test, y_score) + <...> + >>> plt.show() + """ + # TODO(1.9): remove after the end of the deprecation period of `y_pred` + if y_score is not None and not ( + isinstance(y_pred, str) and y_pred == "deprecated" + ): + raise ValueError( + "`y_pred` and `y_score` cannot be both specified. Please use `y_score`" + " only as `y_pred` is deprecated in 1.7 and will be removed in 1.9." + ) + if not (isinstance(y_pred, str) and y_pred == "deprecated"): + warnings.warn( + ( + "y_pred is deprecated in 1.7 and will be removed in 1.9. " + "Please use `y_score` instead." + ), + FutureWarning, + ) + y_score = y_pred + + pos_label_validated, name = cls._validate_from_predictions_params( + y_true, y_score, sample_weight=sample_weight, pos_label=pos_label, name=name + ) + + fpr, tpr, _ = roc_curve( + y_true, + y_score, + pos_label=pos_label, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + ) + roc_auc = auc(fpr, tpr) + + viz = cls( + fpr=fpr, + tpr=tpr, + roc_auc=roc_auc, + name=name, + pos_label=pos_label_validated, + ) + + return viz.plot( + ax=ax, + curve_kwargs=curve_kwargs, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + despine=despine, + **kwargs, + ) + + @classmethod + def from_cv_results( + cls, + cv_results, + X, + y, + *, + sample_weight=None, + drop_intermediate=True, + response_method="auto", + pos_label=None, + ax=None, + name=None, + curve_kwargs=None, + plot_chance_level=False, + chance_level_kwargs=None, + despine=False, + ): + """Create a multi-fold ROC curve display given cross-validation results. + + .. versionadded:: 1.7 + + Parameters + ---------- + cv_results : dict + Dictionary as returned by :func:`~sklearn.model_selection.cross_validate` + using `return_estimator=True` and `return_indices=True` (i.e., dictionary + should contain the keys "estimator" and "indices"). + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input values. + + y : array-like of shape (n_samples,) + Target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop some suboptimal thresholds which would not appear + on a plotted ROC curve. This is useful in order to create lighter + ROC curves. + + response_method : {'predict_proba', 'decision_function', 'auto'} \ + default='auto' + Specifies whether to use :term:`predict_proba` or + :term:`decision_function` as the target response. If set to 'auto', + :term:`predict_proba` is tried first and if it does not exist + :term:`decision_function` is tried next. + + pos_label : int, float, bool or str, default=None + The class considered as the positive class when computing the ROC AUC + metrics. By default, `estimators.classes_[1]` is considered + as the positive class. + + ax : matplotlib axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + name : str or list of str, default=None + Name for labeling legend entries. The number of legend entries + is determined by `curve_kwargs`, and is not affected by `name`. + To label each curve, provide a list of strings. To avoid labeling + individual curves that have the same appearance, this cannot be used in + conjunction with `curve_kwargs` being a dictionary or None. If a + string is provided, it will be used to either label the single legend entry + or if there are multiple legend entries, label each individual curve with + the same name. If `None`, no name is shown in the legend. + + curve_kwargs : dict or list of dict, default=None + Keywords arguments to be passed to matplotlib's `plot` function + to draw individual ROC curves. If a list is provided the + parameters are applied to the ROC curves of each CV fold + sequentially and a legend entry is added for each curve. + If a single dictionary is provided, the same parameters are applied + to all ROC curves and a single legend entry for all curves is added, + labeled with the mean ROC AUC score. + + plot_chance_level : bool, default=False + Whether to plot the chance level. + + chance_level_kwargs : dict, default=None + Keyword arguments to be passed to matplotlib's `plot` for rendering + the chance level line. + + despine : bool, default=False + Whether to remove the top and right spines from the plot. + + Returns + ------- + display : :class:`~sklearn.metrics.RocCurveDisplay` + The multi-fold ROC curve display. + + See Also + -------- + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : ROC Curve visualization given an + estimator and some data. + RocCurveDisplay.from_predictions : ROC Curve visualization given the + probabilities of scores of a classifier. + roc_auc_score : Compute the area under the ROC curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.metrics import RocCurveDisplay + >>> from sklearn.model_selection import cross_validate + >>> from sklearn.svm import SVC + >>> X, y = make_classification(random_state=0) + >>> clf = SVC(random_state=0) + >>> cv_results = cross_validate( + ... clf, X, y, cv=3, return_estimator=True, return_indices=True) + >>> RocCurveDisplay.from_cv_results(cv_results, X, y) + <...> + >>> plt.show() + """ + pos_label_ = cls._validate_from_cv_results_params( + cv_results, + X, + y, + sample_weight=sample_weight, + pos_label=pos_label, + ) + + fpr_folds, tpr_folds, auc_folds = [], [], [] + for estimator, test_indices in zip( + cv_results["estimator"], cv_results["indices"]["test"] + ): + y_true = _safe_indexing(y, test_indices) + y_pred, _ = _get_response_values_binary( + estimator, + _safe_indexing(X, test_indices), + response_method=response_method, + pos_label=pos_label_, + ) + sample_weight_fold = ( + None + if sample_weight is None + else _safe_indexing(sample_weight, test_indices) + ) + fpr, tpr, _ = roc_curve( + y_true, + y_pred, + pos_label=pos_label_, + sample_weight=sample_weight_fold, + drop_intermediate=drop_intermediate, + ) + roc_auc = auc(fpr, tpr) + + fpr_folds.append(fpr) + tpr_folds.append(tpr) + auc_folds.append(roc_auc) + + viz = cls( + fpr=fpr_folds, + tpr=tpr_folds, + roc_auc=auc_folds, + name=name, + pos_label=pos_label_, + ) + return viz.plot( + ax=ax, + curve_kwargs=curve_kwargs, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kwargs, + despine=despine, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py new file mode 100644 index 0000000000000000000000000000000000000000..753f2a1e7319d51b2ff7c299a25a7146801e5fd3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_common_curve_display.py @@ -0,0 +1,292 @@ +import numpy as np +import pytest + +from sklearn.base import BaseEstimator, ClassifierMixin, clone +from sklearn.calibration import CalibrationDisplay +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.metrics import ( + ConfusionMatrixDisplay, + DetCurveDisplay, + PrecisionRecallDisplay, + PredictionErrorDisplay, + RocCurveDisplay, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor + + +@pytest.fixture(scope="module") +def data(): + return load_iris(return_X_y=True) + + +@pytest.fixture(scope="module") +def data_binary(data): + X, y = data + return X[y < 2], y[y < 2] + + +@pytest.mark.parametrize( + "Display", + [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay], +) +def test_display_curve_error_classifier(pyplot, data, data_binary, Display): + """Check that a proper error is raised when only binary classification is + supported.""" + X, y = data + X_binary, y_binary = data_binary + clf = DecisionTreeClassifier().fit(X, y) + + # Case 1: multiclass classifier with multiclass target + msg = "Expected 'estimator' to be a binary classifier. Got 3 classes instead." + with pytest.raises(ValueError, match=msg): + Display.from_estimator(clf, X, y) + + # Case 2: multiclass classifier with binary target + with pytest.raises(ValueError, match=msg): + Display.from_estimator(clf, X_binary, y_binary) + + # Case 3: binary classifier with multiclass target + clf = DecisionTreeClassifier().fit(X_binary, y_binary) + msg = "The target y is not binary. Got multiclass type of target." + with pytest.raises(ValueError, match=msg): + Display.from_estimator(clf, X, y) + + +@pytest.mark.parametrize( + "Display", + [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay], +) +def test_display_curve_error_regression(pyplot, data_binary, Display): + """Check that we raise an error with regressor.""" + + # Case 1: regressor + X, y = data_binary + regressor = DecisionTreeRegressor().fit(X, y) + + msg = "Expected 'estimator' to be a binary classifier. Got DecisionTreeRegressor" + with pytest.raises(ValueError, match=msg): + Display.from_estimator(regressor, X, y) + + # Case 2: regression target + classifier = DecisionTreeClassifier().fit(X, y) + # Force `y_true` to be seen as a regression problem + y = y + 0.5 + msg = "The target y is not binary. Got continuous type of target." + with pytest.raises(ValueError, match=msg): + Display.from_estimator(classifier, X, y) + with pytest.raises(ValueError, match=msg): + Display.from_predictions(y, regressor.fit(X, y).predict(X)) + + +@pytest.mark.parametrize( + "response_method, msg", + [ + ( + "predict_proba", + "MyClassifier has none of the following attributes: predict_proba.", + ), + ( + "decision_function", + "MyClassifier has none of the following attributes: decision_function.", + ), + ( + "auto", + ( + "MyClassifier has none of the following attributes: predict_proba," + " decision_function." + ), + ), + ( + "bad_method", + "MyClassifier has none of the following attributes: bad_method.", + ), + ], +) +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_error_no_response( + pyplot, + data_binary, + response_method, + msg, + Display, +): + """Check that a proper error is raised when the response method requested + is not defined for the given trained classifier.""" + X, y = data_binary + + class MyClassifier(ClassifierMixin, BaseEstimator): + def fit(self, X, y): + self.classes_ = [0, 1] + return self + + clf = MyClassifier().fit(X, y) + + with pytest.raises(AttributeError, match=msg): + Display.from_estimator(clf, X, y, response_method=response_method) + + +@pytest.mark.parametrize("Display", [DetCurveDisplay, PrecisionRecallDisplay]) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_display_curve_estimator_name_multiple_calls( + pyplot, + data_binary, + Display, + constructor_name, +): + """Check that passing `name` when calling `plot` will overwrite the original name + in the legend.""" + X, y = data_binary + clf_name = "my hand-crafted name" + clf = LogisticRegression().fit(X, y) + y_pred = clf.predict_proba(X)[:, 1] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + disp = Display.from_estimator(clf, X, y, name=clf_name) + else: + disp = Display.from_predictions(y, y_pred, name=clf_name) + assert disp.estimator_name == clf_name + pyplot.close("all") + disp.plot() + assert clf_name in disp.line_.get_label() + pyplot.close("all") + clf_name = "another_name" + disp.plot(name=clf_name) + assert clf_name in disp.line_.get_label() + + +# TODO: remove this test once classes moved to using `name` instead of +# `estimator_name` +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +@pytest.mark.parametrize("Display", [DetCurveDisplay, PrecisionRecallDisplay]) +def test_display_curve_not_fitted_errors_old_name(pyplot, data_binary, clf, Display): + """Check that a proper error is raised when the classifier is not + fitted.""" + X, y = data_binary + # clone since we parametrize the test and the classifier will be fitted + # when testing the second and subsequent plotting function + model = clone(clf) + with pytest.raises(NotFittedError): + Display.from_estimator(model, X, y) + model.fit(X, y) + disp = Display.from_estimator(model, X, y) + assert model.__class__.__name__ in disp.line_.get_label() + assert disp.estimator_name == model.__class__.__name__ + + +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +@pytest.mark.parametrize("Display", [RocCurveDisplay]) +def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display): + """Check that a proper error is raised when the classifier is not fitted.""" + X, y = data_binary + # clone since we parametrize the test and the classifier will be fitted + # when testing the second and subsequent plotting function + model = clone(clf) + with pytest.raises(NotFittedError): + Display.from_estimator(model, X, y) + model.fit(X, y) + disp = Display.from_estimator(model, X, y) + assert model.__class__.__name__ in disp.line_.get_label() + assert disp.name == model.__class__.__name__ + + +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_n_samples_consistency(pyplot, data_binary, Display): + """Check the error raised when `y_pred` or `sample_weight` have inconsistent + length.""" + X, y = data_binary + classifier = DecisionTreeClassifier().fit(X, y) + + msg = "Found input variables with inconsistent numbers of samples" + with pytest.raises(ValueError, match=msg): + Display.from_estimator(classifier, X[:-2], y) + with pytest.raises(ValueError, match=msg): + Display.from_estimator(classifier, X, y[:-2]) + with pytest.raises(ValueError, match=msg): + Display.from_estimator(classifier, X, y, sample_weight=np.ones(X.shape[0] - 2)) + + +@pytest.mark.parametrize( + "Display", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay] +) +def test_display_curve_error_pos_label(pyplot, data_binary, Display): + """Check consistence of error message when `pos_label` should be specified.""" + X, y = data_binary + y = y + 10 + + classifier = DecisionTreeClassifier().fit(X, y) + y_pred = classifier.predict_proba(X)[:, -1] + msg = r"y_true takes value in {10, 11} and pos_label is not specified" + with pytest.raises(ValueError, match=msg): + Display.from_predictions(y, y_pred) + + +@pytest.mark.parametrize( + "Display", + [ + CalibrationDisplay, + DetCurveDisplay, + PrecisionRecallDisplay, + RocCurveDisplay, + PredictionErrorDisplay, + ConfusionMatrixDisplay, + ], +) +@pytest.mark.parametrize( + "constructor", + ["from_predictions", "from_estimator"], +) +def test_classifier_display_curve_named_constructor_return_type( + pyplot, data_binary, Display, constructor +): + """Check that named constructors return the correct type when subclassed. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/27675 + """ + X, y = data_binary + + # This can be anything - we just need to check the named constructor return + # type so the only requirement here is instantiating the class without error + y_pred = y + + classifier = LogisticRegression().fit(X, y) + + class SubclassOfDisplay(Display): + pass + + if constructor == "from_predictions": + curve = SubclassOfDisplay.from_predictions(y, y_pred) + else: # constructor == "from_estimator" + curve = SubclassOfDisplay.from_estimator(classifier, X, y) + + assert isinstance(curve, SubclassOfDisplay) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py new file mode 100644 index 0000000000000000000000000000000000000000..6e93bf4993a93f0f5c12d295aa9c0c3b6136218d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_confusion_matrix_display.py @@ -0,0 +1,374 @@ +import numpy as np +import pytest +from numpy.testing import ( + assert_allclose, + assert_array_equal, +) + +from sklearn.compose import make_column_transformer +from sklearn.datasets import make_classification +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC, SVR + + +def test_confusion_matrix_display_validation(pyplot): + """Check that we raise the proper error when validating parameters.""" + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=5, random_state=0 + ) + + with pytest.raises(NotFittedError): + ConfusionMatrixDisplay.from_estimator(SVC(), X, y) + + regressor = SVR().fit(X, y) + y_pred_regressor = regressor.predict(X) + y_pred_classifier = SVC().fit(X, y).predict(X) + + err_msg = "ConfusionMatrixDisplay.from_estimator only supports classifiers" + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_estimator(regressor, X, y) + + err_msg = "Mix type of y not allowed, got types" + with pytest.raises(ValueError, match=err_msg): + # Force `y_true` to be seen as a regression problem + ConfusionMatrixDisplay.from_predictions(y + 0.5, y_pred_classifier) + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_predictions(y, y_pred_regressor) + + err_msg = "Found input variables with inconsistent numbers of samples" + with pytest.raises(ValueError, match=err_msg): + ConfusionMatrixDisplay.from_predictions(y, y_pred_classifier[::2]) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("with_labels", [True, False]) +@pytest.mark.parametrize("with_display_labels", [True, False]) +def test_confusion_matrix_display_custom_labels( + pyplot, constructor_name, with_labels, with_display_labels +): + """Check the resulting plot when labels are given.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + ax = pyplot.gca() + labels = [2, 1, 0, 3, 4] if with_labels else None + display_labels = ["b", "d", "a", "e", "f"] if with_display_labels else None + + cm = confusion_matrix(y, y_pred, labels=labels) + common_kwargs = { + "ax": ax, + "display_labels": display_labels, + "labels": labels, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + assert_allclose(disp.confusion_matrix, cm) + + if with_display_labels: + expected_display_labels = display_labels + elif with_labels: + expected_display_labels = labels + else: + expected_display_labels = list(range(n_classes)) + + expected_display_labels_str = [str(name) for name in expected_display_labels] + + x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()] + + assert_array_equal(disp.display_labels, expected_display_labels) + assert_array_equal(x_ticks, expected_display_labels_str) + assert_array_equal(y_ticks, expected_display_labels_str) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("normalize", ["true", "pred", "all", None]) +@pytest.mark.parametrize("include_values", [True, False]) +def test_confusion_matrix_display_plotting( + pyplot, + constructor_name, + normalize, + include_values, +): + """Check the overall plotting rendering.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + ax = pyplot.gca() + cmap = "plasma" + + cm = confusion_matrix(y, y_pred) + common_kwargs = { + "normalize": normalize, + "cmap": cmap, + "ax": ax, + "include_values": include_values, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + assert disp.ax_ == ax + + if normalize == "true": + cm = cm / cm.sum(axis=1, keepdims=True) + elif normalize == "pred": + cm = cm / cm.sum(axis=0, keepdims=True) + elif normalize == "all": + cm = cm / cm.sum() + + assert_allclose(disp.confusion_matrix, cm) + import matplotlib as mpl + + assert isinstance(disp.im_, mpl.image.AxesImage) + assert disp.im_.get_cmap().name == cmap + assert isinstance(disp.ax_, pyplot.Axes) + assert isinstance(disp.figure_, pyplot.Figure) + + assert disp.ax_.get_ylabel() == "True label" + assert disp.ax_.get_xlabel() == "Predicted label" + + x_ticks = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + y_ticks = [tick.get_text() for tick in disp.ax_.get_yticklabels()] + + expected_display_labels = list(range(n_classes)) + + expected_display_labels_str = [str(name) for name in expected_display_labels] + + assert_array_equal(disp.display_labels, expected_display_labels) + assert_array_equal(x_ticks, expected_display_labels_str) + assert_array_equal(y_ticks, expected_display_labels_str) + + image_data = disp.im_.get_array().data + assert_allclose(image_data, cm) + + if include_values: + assert disp.text_.shape == (n_classes, n_classes) + fmt = ".2g" + expected_text = np.array([format(v, fmt) for v in cm.ravel(order="C")]) + text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")]) + assert_array_equal(expected_text, text_text) + else: + assert disp.text_ is None + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_confusion_matrix_display(pyplot, constructor_name): + """Check the behaviour of the default constructor without using the class + methods.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + cm = confusion_matrix(y, y_pred) + common_kwargs = { + "normalize": None, + "include_values": True, + "cmap": "viridis", + "xticks_rotation": 45.0, + } + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + assert_allclose(disp.confusion_matrix, cm) + assert disp.text_.shape == (n_classes, n_classes) + + rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()] + assert_allclose(rotations, 45.0) + + image_data = disp.im_.get_array().data + assert_allclose(image_data, cm) + + disp.plot(cmap="plasma") + assert disp.im_.get_cmap().name == "plasma" + + disp.plot(include_values=False) + assert disp.text_ is None + + disp.plot(xticks_rotation=90.0) + rotations = [tick.get_rotation() for tick in disp.ax_.get_xticklabels()] + assert_allclose(rotations, 90.0) + + disp.plot(values_format="e") + expected_text = np.array([format(v, "e") for v in cm.ravel(order="C")]) + text_text = np.array([t.get_text() for t in disp.text_.ravel(order="C")]) + assert_array_equal(expected_text, text_text) + + +def test_confusion_matrix_contrast(pyplot): + """Check that the text color is appropriate depending on background.""" + + cm = np.eye(2) / 2 + disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1]) + + disp.plot(cmap=pyplot.cm.gray) + # diagonal text is black + assert_allclose(disp.text_[0, 0].get_color(), [0.0, 0.0, 0.0, 1.0]) + assert_allclose(disp.text_[1, 1].get_color(), [0.0, 0.0, 0.0, 1.0]) + + # off-diagonal text is white + assert_allclose(disp.text_[0, 1].get_color(), [1.0, 1.0, 1.0, 1.0]) + assert_allclose(disp.text_[1, 0].get_color(), [1.0, 1.0, 1.0, 1.0]) + + disp.plot(cmap=pyplot.cm.gray_r) + # diagonal text is white + assert_allclose(disp.text_[0, 1].get_color(), [0.0, 0.0, 0.0, 1.0]) + assert_allclose(disp.text_[1, 0].get_color(), [0.0, 0.0, 0.0, 1.0]) + + # off-diagonal text is black + assert_allclose(disp.text_[0, 0].get_color(), [1.0, 1.0, 1.0, 1.0]) + assert_allclose(disp.text_[1, 1].get_color(), [1.0, 1.0, 1.0, 1.0]) + + # Regression test for #15920 + cm = np.array([[19, 34], [32, 58]]) + disp = ConfusionMatrixDisplay(cm, display_labels=[0, 1]) + + disp.plot(cmap=pyplot.cm.Blues) + min_color = pyplot.cm.Blues(0) + max_color = pyplot.cm.Blues(255) + assert_allclose(disp.text_[0, 0].get_color(), max_color) + assert_allclose(disp.text_[0, 1].get_color(), max_color) + assert_allclose(disp.text_[1, 0].get_color(), max_color) + assert_allclose(disp.text_[1, 1].get_color(), min_color) + + +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), + LogisticRegression(), + ), + ], + ids=["clf", "pipeline-clf", "pipeline-column_transformer-clf"], +) +def test_confusion_matrix_pipeline(pyplot, clf): + """Check the behaviour of the plotting with more complex pipeline.""" + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + with pytest.raises(NotFittedError): + ConfusionMatrixDisplay.from_estimator(clf, X, y) + clf.fit(X, y) + y_pred = clf.predict(X) + + disp = ConfusionMatrixDisplay.from_estimator(clf, X, y) + cm = confusion_matrix(y, y_pred) + + assert_allclose(disp.confusion_matrix, cm) + assert disp.text_.shape == (n_classes, n_classes) + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_confusion_matrix_with_unknown_labels(pyplot, constructor_name): + """Check that when labels=None, the unique values in `y_pred` and `y_true` + will be used. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/18405 + """ + n_classes = 5 + X, y = make_classification( + n_samples=100, n_informative=5, n_classes=n_classes, random_state=0 + ) + classifier = SVC().fit(X, y) + y_pred = classifier.predict(X) + # create unseen labels in `y_true` not seen during fitting and not present + # in 'classifier.classes_' + y = y + 1 + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + common_kwargs = {"labels": None} + if constructor_name == "from_estimator": + disp = ConfusionMatrixDisplay.from_estimator(classifier, X, y, **common_kwargs) + else: + disp = ConfusionMatrixDisplay.from_predictions(y, y_pred, **common_kwargs) + + display_labels = [tick.get_text() for tick in disp.ax_.get_xticklabels()] + expected_labels = [str(i) for i in range(n_classes + 1)] + assert_array_equal(expected_labels, display_labels) + + +def test_colormap_max(pyplot): + """Check that the max color is used for the color of the text.""" + gray = pyplot.get_cmap("gray", 1024) + confusion_matrix = np.array([[1.0, 0.0], [0.0, 1.0]]) + + disp = ConfusionMatrixDisplay(confusion_matrix) + disp.plot(cmap=gray) + + color = disp.text_[1, 0].get_color() + assert_allclose(color, [1.0, 1.0, 1.0, 1.0]) + + +def test_im_kw_adjust_vmin_vmax(pyplot): + """Check that im_kw passes kwargs to imshow""" + + confusion_matrix = np.array([[0.48, 0.04], [0.08, 0.4]]) + disp = ConfusionMatrixDisplay(confusion_matrix) + disp.plot(im_kw=dict(vmin=0.0, vmax=0.8)) + + clim = disp.im_.get_clim() + assert clim[0] == pytest.approx(0.0) + assert clim[1] == pytest.approx(0.8) + + +def test_confusion_matrix_text_kw(pyplot): + """Check that text_kw is passed to the text call.""" + font_size = 15.0 + X, y = make_classification(random_state=0) + classifier = SVC().fit(X, y) + + # from_estimator passes the font size + disp = ConfusionMatrixDisplay.from_estimator( + classifier, X, y, text_kw={"fontsize": font_size} + ) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == font_size + + # plot adjusts plot to new font size + new_font_size = 20.0 + disp.plot(text_kw={"fontsize": new_font_size}) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == new_font_size + + # from_predictions passes the font size + y_pred = classifier.predict(X) + disp = ConfusionMatrixDisplay.from_predictions( + y, y_pred, text_kw={"fontsize": font_size} + ) + for text in disp.text_.reshape(-1): + assert text.get_fontsize() == font_size diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_det_curve_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_det_curve_display.py new file mode 100644 index 0000000000000000000000000000000000000000..105778c63103040255278dfd4410dab5a2abd792 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_det_curve_display.py @@ -0,0 +1,114 @@ +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from sklearn.datasets import load_iris +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import DetCurveDisplay, det_curve + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("drop_intermediate", [True, False]) +@pytest.mark.parametrize("with_strings", [True, False]) +def test_det_curve_display( + pyplot, + constructor_name, + response_method, + with_sample_weight, + drop_intermediate, + with_strings, +): + X, y = load_iris(return_X_y=True) + # Binarize the data with only the two first classes + X, y = X[y < 2], y[y < 2] + + 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) + y_pred = getattr(lr, response_method)(X) + if y_pred.ndim == 2: + y_pred = y_pred[:, 1] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + common_kwargs = { + "name": lr.__class__.__name__, + "alpha": 0.8, + "sample_weight": sample_weight, + "drop_intermediate": drop_intermediate, + "pos_label": pos_label, + } + if constructor_name == "from_estimator": + disp = DetCurveDisplay.from_estimator(lr, X, y, **common_kwargs) + else: + disp = DetCurveDisplay.from_predictions(y, y_pred, **common_kwargs) + + fpr, fnr, _ = det_curve( + y, + y_pred, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + ) + + assert_allclose(disp.fpr, fpr, atol=1e-7) + assert_allclose(disp.fnr, fnr, atol=1e-7) + + assert disp.estimator_name == "LogisticRegression" + + # cannot fail thanks to pyplot fixture + import matplotlib as mpl + + assert isinstance(disp.line_, mpl.lines.Line2D) + assert disp.line_.get_alpha() == 0.8 + assert isinstance(disp.ax_, mpl.axes.Axes) + assert isinstance(disp.figure_, mpl.figure.Figure) + assert disp.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 disp.ax_.get_ylabel() == expected_ylabel + assert disp.ax_.get_xlabel() == expected_xlabel + + +@pytest.mark.parametrize( + "constructor_name, expected_clf_name", + [ + ("from_estimator", "LogisticRegression"), + ("from_predictions", "Classifier"), + ], +) +def test_det_curve_display_default_name( + pyplot, + constructor_name, + expected_clf_name, +): + # Check the default name display in the figure when `name` is not provided + X, y = load_iris(return_X_y=True) + # Binarize the data with only the two first classes + X, y = X[y < 2], y[y < 2] + + lr = LogisticRegression().fit(X, y) + y_pred = lr.predict_proba(X)[:, 1] + + if constructor_name == "from_estimator": + disp = DetCurveDisplay.from_estimator(lr, X, y) + else: + disp = DetCurveDisplay.from_predictions(y, y_pred) + + assert disp.estimator_name == expected_clf_name + assert disp.line_.get_label() == expected_clf_name diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py new file mode 100644 index 0000000000000000000000000000000000000000..022a5fbf28a914e4e27b6679b0d572d5a356ca82 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_precision_recall_display.py @@ -0,0 +1,382 @@ +from collections import Counter + +import numpy as np +import pytest +from scipy.integrate import trapezoid + +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_breast_cancer, make_classification +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ( + PrecisionRecallDisplay, + average_precision_score, + precision_recall_curve, +) +from sklearn.model_selection import train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils import shuffle + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize("drop_intermediate", [True, False]) +def test_precision_recall_display_plotting( + pyplot, constructor_name, response_method, drop_intermediate +): + """Check the overall plotting rendering.""" + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = getattr(classifier, response_method)(X) + y_pred = y_pred if y_pred.ndim == 1 else y_pred[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X, + y, + response_method=response_method, + drop_intermediate=drop_intermediate, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label, drop_intermediate=drop_intermediate + ) + + precision, recall, _ = precision_recall_curve( + y, y_pred, pos_label=pos_label, drop_intermediate=drop_intermediate + ) + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + np.testing.assert_allclose(display.precision, precision) + np.testing.assert_allclose(display.recall, recall) + assert display.average_precision == pytest.approx(average_precision) + + import matplotlib as mpl + + assert isinstance(display.line_, mpl.lines.Line2D) + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + + assert display.ax_.get_xlabel() == "Recall (Positive label: 1)" + assert display.ax_.get_ylabel() == "Precision (Positive label: 1)" + assert display.ax_.get_adjustable() == "box" + assert display.ax_.get_aspect() in ("equal", 1.0) + assert display.ax_.get_xlim() == display.ax_.get_ylim() == (-0.01, 1.01) + + # plotting passing some new parameters + display.plot(alpha=0.8, name="MySpecialEstimator") + expected_label = f"MySpecialEstimator (AP = {average_precision:0.2f})" + assert display.line_.get_label() == expected_label + assert display.line_.get_alpha() == pytest.approx(0.8) + + # Check that the chance level line is not plotted by default + assert display.chance_level_ is None + + +@pytest.mark.parametrize("chance_level_kw", [None, {"color": "r"}, {"c": "r"}]) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_precision_recall_chance_level_line( + pyplot, + chance_level_kw, + constructor_name, +): + """Check the chance level line plotting behavior.""" + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + pos_prevalence = Counter(y)[1] / len(y) + + lr = LogisticRegression() + y_pred = lr.fit(X, y).predict_proba(X)[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + lr, + X, + y, + plot_chance_level=True, + chance_level_kw=chance_level_kw, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, + y_pred, + plot_chance_level=True, + chance_level_kw=chance_level_kw, + ) + + import matplotlib as mpl + + assert isinstance(display.chance_level_, mpl.lines.Line2D) + assert tuple(display.chance_level_.get_xdata()) == (0, 1) + assert tuple(display.chance_level_.get_ydata()) == (pos_prevalence, pos_prevalence) + + # Checking for chance level line styles + if chance_level_kw is None: + assert display.chance_level_.get_color() == "k" + else: + assert display.chance_level_.get_color() == "r" + + +@pytest.mark.parametrize( + "constructor_name, default_label", + [ + ("from_estimator", "LogisticRegression (AP = {:.2f})"), + ("from_predictions", "Classifier (AP = {:.2f})"), + ], +) +def test_precision_recall_display_name(pyplot, constructor_name, default_label): + """Check the behaviour of the name parameters""" + X, y = make_classification(n_classes=2, n_samples=100, random_state=0) + pos_label = 1 + + classifier = LogisticRegression().fit(X, y) + classifier.fit(X, y) + + y_pred = classifier.predict_proba(X)[:, pos_label] + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator(classifier, X, y) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=pos_label + ) + + average_precision = average_precision_score(y, y_pred, pos_label=pos_label) + + # check that the default name is used + assert display.line_.get_label() == default_label.format(average_precision) + + # check that the name can be set + display.plot(name="MySpecialEstimator") + assert ( + display.line_.get_label() + == f"MySpecialEstimator (AP = {average_precision:.2f})" + ) + + +@pytest.mark.parametrize( + "clf", + [ + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +def test_precision_recall_display_pipeline(pyplot, clf): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + with pytest.raises(NotFittedError): + PrecisionRecallDisplay.from_estimator(clf, X, y) + clf.fit(X, y) + display = PrecisionRecallDisplay.from_estimator(clf, X, y) + assert display.estimator_name == clf.__class__.__name__ + + +def test_precision_recall_display_string_labels(pyplot): + # regression test #15738 + cancer = load_breast_cancer() + X, y = cancer.data, cancer.target_names[cancer.target] + + lr = make_pipeline(StandardScaler(), LogisticRegression()) + lr.fit(X, y) + for klass in cancer.target_names: + assert klass in lr.classes_ + display = PrecisionRecallDisplay.from_estimator(lr, X, y) + + y_pred = lr.predict_proba(X)[:, 1] + avg_prec = average_precision_score(y, y_pred, pos_label=lr.classes_[1]) + + assert display.average_precision == pytest.approx(avg_prec) + assert display.estimator_name == lr.__class__.__name__ + + err_msg = r"y_true takes value in {'benign', 'malignant'}" + with pytest.raises(ValueError, match=err_msg): + PrecisionRecallDisplay.from_predictions(y, y_pred) + + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, pos_label=lr.classes_[1] + ) + assert display.average_precision == pytest.approx(avg_prec) + + +@pytest.mark.parametrize( + "average_precision, estimator_name, expected_label", + [ + (0.9, None, "AP = 0.90"), + (None, "my_est", "my_est"), + (0.8, "my_est2", "my_est2 (AP = 0.80)"), + ], +) +def test_default_labels(pyplot, average_precision, estimator_name, expected_label): + """Check the default labels used in the display.""" + precision = np.array([1, 0.5, 0]) + recall = np.array([0, 0.5, 1]) + display = PrecisionRecallDisplay( + precision, + recall, + average_precision=average_precision, + estimator_name=estimator_name, + ) + display.plot() + assert display.line_.get_label() == expected_label + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +def test_plot_precision_recall_pos_label(pyplot, constructor_name, response_method): + # check that we can provide the positive label and display the proper + # statistics + X, y = load_breast_cancer(return_X_y=True) + # create an highly imbalanced version of the breast cancer dataset + idx_positive = np.flatnonzero(y == 1) + idx_negative = np.flatnonzero(y == 0) + idx_selected = np.hstack([idx_negative, idx_positive[:25]]) + X, y = X[idx_selected], y[idx_selected] + X, y = shuffle(X, y, random_state=42) + # only use 2 features to make the problem even harder + X = X[:, :2] + y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + stratify=y, + random_state=0, + ) + + classifier = LogisticRegression() + classifier.fit(X_train, y_train) + + # sanity check to be sure the positive class is classes_[0] and that we + # are betrayed by the class imbalance + assert classifier.classes_.tolist() == ["cancer", "not cancer"] + + y_pred = getattr(classifier, response_method)(X_test) + # we select the corresponding probability columns or reverse the decision + # function otherwise + y_pred_cancer = -1 * y_pred if y_pred.ndim == 1 else y_pred[:, 0] + y_pred_not_cancer = y_pred if y_pred.ndim == 1 else y_pred[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + pos_label="cancer", + response_method=response_method, + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_cancer, + pos_label="cancer", + ) + # we should obtain the statistics of the "cancer" class + avg_prec_limit = 0.65 + assert display.average_precision < avg_prec_limit + assert -trapezoid(display.precision, display.recall) < avg_prec_limit + + # otherwise we should obtain the statistics of the "not cancer" class + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + classifier, + X_test, + y_test, + response_method=response_method, + pos_label="not cancer", + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y_test, + y_pred_not_cancer, + pos_label="not cancer", + ) + avg_prec_limit = 0.95 + assert display.average_precision > avg_prec_limit + assert -trapezoid(display.precision, display.recall) > avg_prec_limit + + +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_precision_recall_prevalence_pos_label_reusable(pyplot, constructor_name): + # Check that even if one passes plot_chance_level=False the first time + # one can still call disp.plot with plot_chance_level=True and get the + # chance level line + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + lr = LogisticRegression() + y_pred = lr.fit(X, y).predict_proba(X)[:, 1] + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator( + lr, X, y, plot_chance_level=False + ) + else: + display = PrecisionRecallDisplay.from_predictions( + y, y_pred, plot_chance_level=False + ) + assert display.chance_level_ is None + + import matplotlib as mpl + + # When calling from_estimator or from_predictions, + # prevalence_pos_label should have been set, so that directly + # calling plot_chance_level=True should plot the chance level line + display.plot(plot_chance_level=True) + assert isinstance(display.chance_level_, mpl.lines.Line2D) + + +def test_precision_recall_raise_no_prevalence(pyplot): + # Check that raises correctly when plotting chance level with + # no prvelance_pos_label is provided + precision = np.array([1, 0.5, 0]) + recall = np.array([0, 0.5, 1]) + display = PrecisionRecallDisplay(precision, recall) + + msg = ( + "You must provide prevalence_pos_label when constructing the " + "PrecisionRecallDisplay object in order to plot the chance " + "level line. Alternatively, you may use " + "PrecisionRecallDisplay.from_estimator or " + "PrecisionRecallDisplay.from_predictions " + "to automatically set prevalence_pos_label" + ) + + with pytest.raises(ValueError, match=msg): + display.plot(plot_chance_level=True) + + +@pytest.mark.parametrize("despine", [True, False]) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_plot_precision_recall_despine(pyplot, despine, constructor_name): + # Check that the despine keyword is working correctly + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + clf = LogisticRegression().fit(X, y) + clf.fit(X, y) + + y_pred = clf.decision_function(X) + + # safe guard for the binary if/else construction + assert constructor_name in ("from_estimator", "from_predictions") + + if constructor_name == "from_estimator": + display = PrecisionRecallDisplay.from_estimator(clf, X, y, despine=despine) + else: + display = PrecisionRecallDisplay.from_predictions(y, y_pred, despine=despine) + + for s in ["top", "right"]: + assert display.ax_.spines[s].get_visible() is not despine + + if despine: + for s in ["bottom", "left"]: + assert display.ax_.spines[s].get_bounds() == (0, 1) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py new file mode 100644 index 0000000000000000000000000000000000000000..b2cb888e8884958f55d665879429f224fc9b787d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_predict_error_display.py @@ -0,0 +1,169 @@ +import pytest +from numpy.testing import assert_allclose + +from sklearn.datasets import load_diabetes +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import Ridge +from sklearn.metrics import PredictionErrorDisplay + +X, y = load_diabetes(return_X_y=True) + + +@pytest.fixture +def regressor_fitted(): + return Ridge().fit(X, y) + + +@pytest.mark.parametrize( + "regressor, params, err_type, err_msg", + [ + ( + Ridge().fit(X, y), + {"subsample": -1}, + ValueError, + "When an integer, subsample=-1 should be", + ), + ( + Ridge().fit(X, y), + {"subsample": 20.0}, + ValueError, + "When a floating-point, subsample=20.0 should be", + ), + ( + Ridge().fit(X, y), + {"subsample": -20.0}, + ValueError, + "When a floating-point, subsample=-20.0 should be", + ), + ( + Ridge().fit(X, y), + {"kind": "xxx"}, + ValueError, + "`kind` must be one of", + ), + ], +) +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +def test_prediction_error_display_raise_error( + pyplot, class_method, regressor, params, err_type, err_msg +): + """Check that we raise the proper error when making the parameters + # validation.""" + with pytest.raises(err_type, match=err_msg): + if class_method == "from_estimator": + PredictionErrorDisplay.from_estimator(regressor, X, y, **params) + else: + y_pred = regressor.predict(X) + PredictionErrorDisplay.from_predictions(y_true=y, y_pred=y_pred, **params) + + +def test_from_estimator_not_fitted(pyplot): + """Check that we raise a `NotFittedError` when the passed regressor is not + fit.""" + regressor = Ridge() + with pytest.raises(NotFittedError, match="is not fitted yet."): + PredictionErrorDisplay.from_estimator(regressor, X, y) + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize("kind", ["actual_vs_predicted", "residual_vs_predicted"]) +def test_prediction_error_display(pyplot, regressor_fitted, class_method, kind): + """Check the default behaviour of the display.""" + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, kind=kind + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, kind=kind + ) + + if kind == "actual_vs_predicted": + assert_allclose(display.line_.get_xdata(), display.line_.get_ydata()) + assert display.ax_.get_xlabel() == "Predicted values" + assert display.ax_.get_ylabel() == "Actual values" + assert display.line_ is not None + else: + assert display.ax_.get_xlabel() == "Predicted values" + assert display.ax_.get_ylabel() == "Residuals (actual - predicted)" + assert display.line_ is not None + + assert display.ax_.get_legend() is None + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize( + "subsample, expected_size", + [(5, 5), (0.1, int(X.shape[0] * 0.1)), (None, X.shape[0])], +) +def test_plot_prediction_error_subsample( + pyplot, regressor_fitted, class_method, subsample, expected_size +): + """Check the behaviour of `subsample`.""" + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, subsample=subsample + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, subsample=subsample + ) + assert len(display.scatter_.get_offsets()) == expected_size + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +def test_plot_prediction_error_ax(pyplot, regressor_fitted, class_method): + """Check that we can pass an axis to the display.""" + _, ax = pyplot.subplots() + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator(regressor_fitted, X, y, ax=ax) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, ax=ax + ) + assert display.ax_ is ax + + +@pytest.mark.parametrize("class_method", ["from_estimator", "from_predictions"]) +@pytest.mark.parametrize( + "scatter_kwargs", + [None, {"color": "blue", "alpha": 0.9}, {"c": "blue", "alpha": 0.9}], +) +@pytest.mark.parametrize( + "line_kwargs", [None, {"color": "red", "linestyle": "-"}, {"c": "red", "ls": "-"}] +) +def test_prediction_error_custom_artist( + pyplot, regressor_fitted, class_method, scatter_kwargs, line_kwargs +): + """Check that we can tune the style of the line and the scatter.""" + extra_params = { + "kind": "actual_vs_predicted", + "scatter_kwargs": scatter_kwargs, + "line_kwargs": line_kwargs, + } + if class_method == "from_estimator": + display = PredictionErrorDisplay.from_estimator( + regressor_fitted, X, y, **extra_params + ) + else: + y_pred = regressor_fitted.predict(X) + display = PredictionErrorDisplay.from_predictions( + y_true=y, y_pred=y_pred, **extra_params + ) + + if line_kwargs is not None: + assert display.line_.get_linestyle() == "-" + assert display.line_.get_color() == "red" + else: + assert display.line_.get_linestyle() == "--" + assert display.line_.get_color() == "black" + assert display.line_.get_alpha() == 0.7 + + if scatter_kwargs is not None: + assert_allclose(display.scatter_.get_facecolor(), [[0.0, 0.0, 1.0, 0.9]]) + assert_allclose(display.scatter_.get_edgecolor(), [[0.0, 0.0, 1.0, 0.9]]) + else: + assert display.scatter_.get_alpha() == 0.8 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_roc_curve_display.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_roc_curve_display.py new file mode 100644 index 0000000000000000000000000000000000000000..23fa2f2e3a5e6a7f0e8b918ec4b75e404887af8b --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/test_roc_curve_display.py @@ -0,0 +1,987 @@ +from collections.abc import Mapping + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.integrate import trapezoid + +from sklearn import clone +from sklearn.compose import make_column_transformer +from sklearn.datasets import load_breast_cancer, make_classification +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import RocCurveDisplay, auc, roc_curve +from sklearn.model_selection import cross_validate, train_test_split +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.utils import _safe_indexing, shuffle +from sklearn.utils._response import _get_response_values_binary + + +@pytest.fixture(scope="module") +def data_binary(): + X, y = make_classification( + n_samples=200, + n_features=20, + n_informative=5, + n_redundant=2, + flip_y=0.1, + class_sep=0.8, + random_state=42, + ) + return X, y + + +def _check_figure_axes_and_labels(display, pos_label): + """Check mpl axes and figure defaults are correct.""" + import matplotlib as mpl + + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + assert display.ax_.get_adjustable() == "box" + assert display.ax_.get_aspect() in ("equal", 1.0) + assert display.ax_.get_xlim() == display.ax_.get_ylim() == (-0.01, 1.01) + + expected_pos_label = 1 if pos_label is None else pos_label + expected_ylabel = f"True Positive Rate (Positive label: {expected_pos_label})" + expected_xlabel = f"False Positive Rate (Positive label: {expected_pos_label})" + + assert display.ax_.get_ylabel() == expected_ylabel + assert display.ax_.get_xlabel() == expected_xlabel + + +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("drop_intermediate", [True, False]) +@pytest.mark.parametrize("with_strings", [True, False]) +@pytest.mark.parametrize( + "constructor_name, default_name", + [ + ("from_estimator", "LogisticRegression"), + ("from_predictions", "Classifier"), + ], +) +def test_roc_curve_display_plotting( + pyplot, + response_method, + data_binary, + with_sample_weight, + drop_intermediate, + with_strings, + constructor_name, + default_name, +): + """Check the overall plotting behaviour for single curve.""" + 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) + + y_score = getattr(lr, response_method)(X) + y_score = y_score if y_score.ndim == 1 else y_score[:, 1] + + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator( + lr, + X, + y, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + curve_kwargs={"alpha": 0.8}, + ) + else: + display = RocCurveDisplay.from_predictions( + y, + y_score, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + curve_kwargs={"alpha": 0.8}, + ) + + fpr, tpr, _ = roc_curve( + y, + y_score, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + ) + + assert_allclose(display.roc_auc, auc(fpr, tpr)) + assert_allclose(display.fpr, fpr) + assert_allclose(display.tpr, tpr) + + assert display.name == default_name + + import matplotlib as mpl + + _check_figure_axes_and_labels(display, pos_label) + assert isinstance(display.line_, mpl.lines.Line2D) + assert display.line_.get_alpha() == 0.8 + + expected_label = f"{default_name} (AUC = {display.roc_auc:.2f})" + assert display.line_.get_label() == expected_label + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ( + { + "fpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "tpr": [np.array([0, 0.5, 1])], + "roc_auc": None, + "name": None, + }, + "self.fpr and self.tpr from `RocCurveDisplay` initialization,", + ), + ( + { + "fpr": [np.array([0, 0.5, 1])], + "tpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "roc_auc": [0.8, 0.9], + "name": None, + }, + "self.fpr, self.tpr and self.roc_auc from `RocCurveDisplay`", + ), + ( + { + "fpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "tpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "roc_auc": [0.8], + "name": None, + }, + "Got: self.fpr: 2, self.tpr: 2, self.roc_auc: 1", + ), + ( + { + "fpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "tpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "roc_auc": [0.8, 0.9], + "name": ["curve1", "curve2", "curve3"], + }, + r"self.fpr, self.tpr, self.roc_auc and 'name' \(or self.name\)", + ), + ( + { + "fpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "tpr": [np.array([0, 0.5, 1]), np.array([0, 0.5, 1])], + "roc_auc": [0.8, 0.9], + # List of length 1 is always allowed + "name": ["curve1"], + }, + None, + ), + ], +) +def test_roc_curve_plot_parameter_length_validation(pyplot, params, err_msg): + """Check `plot` parameter length validation performed correctly.""" + display = RocCurveDisplay(**params) + if err_msg: + with pytest.raises(ValueError, match=err_msg): + display.plot() + else: + # No error should be raised + display.plot() + + +def test_validate_plot_params(pyplot): + """Check `_validate_plot_params` returns the correct variables.""" + fpr = np.array([0, 0.5, 1]) + tpr = [np.array([0, 0.5, 1])] + roc_auc = None + name = "test_curve" + + # Initialize display with test inputs + display = RocCurveDisplay( + fpr=fpr, + tpr=tpr, + roc_auc=roc_auc, + name=name, + pos_label=None, + ) + fpr_out, tpr_out, roc_auc_out, name_out = display._validate_plot_params( + ax=None, name=None + ) + + assert isinstance(fpr_out, list) + assert isinstance(tpr_out, list) + assert len(fpr_out) == 1 + assert len(tpr_out) == 1 + assert roc_auc_out is None + assert name_out == ["test_curve"] + + +def test_roc_curve_from_cv_results_param_validation(pyplot, data_binary): + """Check parameter validation is correct.""" + X, y = data_binary + + # `cv_results` missing key + cv_results_no_est = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False + ) + cv_results_no_indices = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False + ) + for cv_results in (cv_results_no_est, cv_results_no_indices): + with pytest.raises( + ValueError, + match="`cv_results` does not contain one of the following required", + ): + RocCurveDisplay.from_cv_results(cv_results, X, y) + + cv_results = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True + ) + + # `X` wrong length + with pytest.raises(ValueError, match="`X` does not contain the correct"): + RocCurveDisplay.from_cv_results(cv_results, X[:10, :], y) + + # `y` not binary + y_multi = y.copy() + y_multi[0] = 2 + with pytest.raises(ValueError, match="The target `y` is not binary."): + RocCurveDisplay.from_cv_results(cv_results, X, y_multi) + + # input inconsistent length + with pytest.raises(ValueError, match="Found input variables with inconsistent"): + RocCurveDisplay.from_cv_results(cv_results, X, y[:10]) + with pytest.raises(ValueError, match="Found input variables with inconsistent"): + RocCurveDisplay.from_cv_results(cv_results, X, y, sample_weight=[1, 2]) + + # `pos_label` inconsistency + y_multi[y_multi == 1] = 2 + with pytest.raises(ValueError, match=r"y takes value in \{0, 2\}"): + RocCurveDisplay.from_cv_results(cv_results, X, y_multi) + + # `name` is list while `curve_kwargs` is None or dict + for curve_kwargs in (None, {"alpha": 0.2}): + with pytest.raises(ValueError, match="To avoid labeling individual curves"): + RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + name=["one", "two", "three"], + curve_kwargs=curve_kwargs, + ) + + # `curve_kwargs` incorrect length + with pytest.raises(ValueError, match="`curve_kwargs` must be None, a dictionary"): + RocCurveDisplay.from_cv_results(cv_results, X, y, curve_kwargs=[{"alpha": 1}]) + + # `curve_kwargs` both alias provided + with pytest.raises(TypeError, match="Got both c and"): + RocCurveDisplay.from_cv_results( + cv_results, X, y, curve_kwargs={"c": "blue", "color": "red"} + ) + + +@pytest.mark.parametrize( + "curve_kwargs", + [None, {"alpha": 0.2}, [{"alpha": 0.2}, {"alpha": 0.3}, {"alpha": 0.4}]], +) +def test_roc_curve_display_from_cv_results_curve_kwargs( + pyplot, data_binary, curve_kwargs +): + """Check `curve_kwargs` correctly passed.""" + X, y = data_binary + n_cv = 3 + cv_results = cross_validate( + LogisticRegression(), X, y, cv=n_cv, return_estimator=True, return_indices=True + ) + display = RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + curve_kwargs=curve_kwargs, + ) + if curve_kwargs is None: + # Default `alpha` used + assert all(line.get_alpha() == 0.5 for line in display.line_) + elif isinstance(curve_kwargs, Mapping): + # `alpha` from dict used for all curves + assert all(line.get_alpha() == 0.2 for line in display.line_) + else: + # Different `alpha` used for each curve + assert all( + line.get_alpha() == curve_kwargs[i]["alpha"] + for i, line in enumerate(display.line_) + ) + + +# TODO(1.9): Remove in 1.9 +def test_roc_curve_display_estimator_name_deprecation(pyplot): + """Check deprecation of `estimator_name`.""" + fpr = np.array([0, 0.5, 1]) + tpr = np.array([0, 0.5, 1]) + with pytest.warns(FutureWarning, match="`estimator_name` is deprecated in"): + RocCurveDisplay(fpr=fpr, tpr=tpr, estimator_name="test") + + +# TODO(1.9): Remove in 1.9 +@pytest.mark.parametrize( + "constructor_name", ["from_estimator", "from_predictions", "plot"] +) +def test_roc_curve_display_kwargs_deprecation(pyplot, data_binary, constructor_name): + """Check **kwargs deprecated correctly in favour of `curve_kwargs`.""" + X, y = data_binary + lr = LogisticRegression() + lr.fit(X, y) + fpr = np.array([0, 0.5, 1]) + tpr = np.array([0, 0.5, 1]) + + # Error when both `curve_kwargs` and `**kwargs` provided + with pytest.raises(ValueError, match="Cannot provide both `curve_kwargs`"): + if constructor_name == "from_estimator": + RocCurveDisplay.from_estimator( + lr, X, y, curve_kwargs={"alpha": 1}, label="test" + ) + elif constructor_name == "from_predictions": + RocCurveDisplay.from_predictions( + y, y, curve_kwargs={"alpha": 1}, label="test" + ) + else: + RocCurveDisplay(fpr=fpr, tpr=tpr).plot( + curve_kwargs={"alpha": 1}, label="test" + ) + + # Warning when `**kwargs`` provided + with pytest.warns(FutureWarning, match=r"`\*\*kwargs` is deprecated and will be"): + if constructor_name == "from_estimator": + RocCurveDisplay.from_estimator(lr, X, y, label="test") + elif constructor_name == "from_predictions": + RocCurveDisplay.from_predictions(y, y, label="test") + else: + RocCurveDisplay(fpr=fpr, tpr=tpr).plot(label="test") + + +@pytest.mark.parametrize( + "curve_kwargs", + [ + None, + {"color": "blue"}, + [{"color": "blue"}, {"color": "green"}, {"color": "red"}], + ], +) +@pytest.mark.parametrize("drop_intermediate", [True, False]) +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@pytest.mark.parametrize("with_strings", [True, False]) +def test_roc_curve_display_plotting_from_cv_results( + pyplot, + data_binary, + with_strings, + with_sample_weight, + response_method, + drop_intermediate, + curve_kwargs, +): + """Check overall plotting of `from_cv_results`.""" + 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 + + cv_results = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True + ) + display = RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + sample_weight=sample_weight, + drop_intermediate=drop_intermediate, + response_method=response_method, + pos_label=pos_label, + curve_kwargs=curve_kwargs, + ) + + for idx, (estimator, test_indices) in enumerate( + zip(cv_results["estimator"], cv_results["indices"]["test"]) + ): + y_true = _safe_indexing(y, test_indices) + y_pred = _get_response_values_binary( + estimator, + _safe_indexing(X, test_indices), + response_method=response_method, + pos_label=pos_label, + )[0] + sample_weight_fold = ( + None + if sample_weight is None + else _safe_indexing(sample_weight, test_indices) + ) + fpr, tpr, _ = roc_curve( + y_true, + y_pred, + sample_weight=sample_weight_fold, + drop_intermediate=drop_intermediate, + pos_label=pos_label, + ) + assert_allclose(display.roc_auc[idx], auc(fpr, tpr)) + assert_allclose(display.fpr[idx], fpr) + assert_allclose(display.tpr[idx], tpr) + + assert display.name is None + + import matplotlib as mpl + + _check_figure_axes_and_labels(display, pos_label) + if with_sample_weight: + aggregate_expected_labels = ["AUC = 0.64 +/- 0.04", "_child1", "_child2"] + else: + aggregate_expected_labels = ["AUC = 0.61 +/- 0.05", "_child1", "_child2"] + for idx, line in enumerate(display.line_): + assert isinstance(line, mpl.lines.Line2D) + # Default alpha for `from_cv_results` + line.get_alpha() == 0.5 + if isinstance(curve_kwargs, list): + # Each individual curve labelled + assert line.get_label() == f"AUC = {display.roc_auc[idx]:.2f}" + else: + # Single aggregate label + assert line.get_label() == aggregate_expected_labels[idx] + + +@pytest.mark.parametrize("roc_auc", [[1.0, 1.0, 1.0], None]) +@pytest.mark.parametrize( + "curve_kwargs", + [None, {"color": "red"}, [{"c": "red"}, {"c": "green"}, {"c": "yellow"}]], +) +@pytest.mark.parametrize("name", [None, "single", ["one", "two", "three"]]) +def test_roc_curve_plot_legend_label(pyplot, data_binary, name, curve_kwargs, roc_auc): + """Check legend label correct with all `curve_kwargs`, `name` combinations.""" + fpr = [np.array([0, 0.5, 1]), np.array([0, 0.5, 1]), np.array([0, 0.5, 1])] + tpr = [np.array([0, 0.5, 1]), np.array([0, 0.5, 1]), np.array([0, 0.5, 1])] + if not isinstance(curve_kwargs, list) and isinstance(name, list): + with pytest.raises(ValueError, match="To avoid labeling individual curves"): + RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc).plot( + name=name, curve_kwargs=curve_kwargs + ) + + else: + display = RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc).plot( + name=name, curve_kwargs=curve_kwargs + ) + legend = display.ax_.get_legend() + if legend is None: + # No legend is created, exit test early + assert name is None + assert roc_auc is None + return + else: + legend_labels = [text.get_text() for text in legend.get_texts()] + + if isinstance(curve_kwargs, list): + # Multiple labels in legend + assert len(legend_labels) == 3 + for idx, label in enumerate(legend_labels): + if name is None: + expected_label = "AUC = 1.00" if roc_auc else None + assert label == expected_label + elif isinstance(name, str): + expected_label = "single (AUC = 1.00)" if roc_auc else "single" + assert label == expected_label + else: + # `name` is a list of different strings + expected_label = ( + f"{name[idx]} (AUC = 1.00)" if roc_auc else f"{name[idx]}" + ) + assert label == expected_label + else: + # Single label in legend + assert len(legend_labels) == 1 + if name is None: + expected_label = "AUC = 1.00 +/- 0.00" if roc_auc else None + assert legend_labels[0] == expected_label + else: + # name is single string + expected_label = "single (AUC = 1.00 +/- 0.00)" if roc_auc else "single" + assert legend_labels[0] == expected_label + + +@pytest.mark.parametrize( + "curve_kwargs", + [None, {"color": "red"}, [{"c": "red"}, {"c": "green"}, {"c": "yellow"}]], +) +@pytest.mark.parametrize("name", [None, "single", ["one", "two", "three"]]) +def test_roc_curve_from_cv_results_legend_label( + pyplot, data_binary, name, curve_kwargs +): + """Check legend label correct with all `curve_kwargs`, `name` combinations.""" + X, y = data_binary + n_cv = 3 + cv_results = cross_validate( + LogisticRegression(), X, y, cv=n_cv, return_estimator=True, return_indices=True + ) + + if not isinstance(curve_kwargs, list) and isinstance(name, list): + with pytest.raises(ValueError, match="To avoid labeling individual curves"): + RocCurveDisplay.from_cv_results( + cv_results, X, y, name=name, curve_kwargs=curve_kwargs + ) + else: + display = RocCurveDisplay.from_cv_results( + cv_results, X, y, name=name, curve_kwargs=curve_kwargs + ) + + legend = display.ax_.get_legend() + legend_labels = [text.get_text() for text in legend.get_texts()] + if isinstance(curve_kwargs, list): + # Multiple labels in legend + assert len(legend_labels) == 3 + auc = ["0.62", "0.66", "0.55"] + for idx, label in enumerate(legend_labels): + if name is None: + assert label == f"AUC = {auc[idx]}" + elif isinstance(name, str): + assert label == f"single (AUC = {auc[idx]})" + else: + # `name` is a list of different strings + assert label == f"{name[idx]} (AUC = {auc[idx]})" + else: + # Single label in legend + assert len(legend_labels) == 1 + if name is None: + assert legend_labels[0] == "AUC = 0.61 +/- 0.05" + else: + # name is single string + assert legend_labels[0] == "single (AUC = 0.61 +/- 0.05)" + + +@pytest.mark.parametrize( + "curve_kwargs", + [None, {"color": "red"}, [{"c": "red"}, {"c": "green"}, {"c": "yellow"}]], +) +def test_roc_curve_from_cv_results_curve_kwargs(pyplot, data_binary, curve_kwargs): + """Check line kwargs passed correctly in `from_cv_results`.""" + + X, y = data_binary + cv_results = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True + ) + display = RocCurveDisplay.from_cv_results( + cv_results, X, y, curve_kwargs=curve_kwargs + ) + + for idx, line in enumerate(display.line_): + color = line.get_color() + if curve_kwargs is None: + # Default color + assert color == "blue" + elif isinstance(curve_kwargs, Mapping): + # All curves "red" + assert color == "red" + else: + assert color == curve_kwargs[idx]["c"] + + +def _check_chance_level(plot_chance_level, chance_level_kw, display): + """Check chance level line and line styles correct.""" + import matplotlib as mpl + + if plot_chance_level: + assert isinstance(display.chance_level_, mpl.lines.Line2D) + assert tuple(display.chance_level_.get_xdata()) == (0, 1) + assert tuple(display.chance_level_.get_ydata()) == (0, 1) + else: + assert display.chance_level_ is None + + # Checking for chance level line styles + if plot_chance_level and chance_level_kw is None: + assert display.chance_level_.get_color() == "k" + assert display.chance_level_.get_linestyle() == "--" + assert display.chance_level_.get_label() == "Chance level (AUC = 0.5)" + elif plot_chance_level: + if "c" in chance_level_kw: + assert display.chance_level_.get_color() == chance_level_kw["c"] + else: + assert display.chance_level_.get_color() == chance_level_kw["color"] + if "lw" in chance_level_kw: + assert display.chance_level_.get_linewidth() == chance_level_kw["lw"] + else: + assert display.chance_level_.get_linewidth() == chance_level_kw["linewidth"] + if "ls" in chance_level_kw: + assert display.chance_level_.get_linestyle() == chance_level_kw["ls"] + else: + assert display.chance_level_.get_linestyle() == chance_level_kw["linestyle"] + + +@pytest.mark.parametrize("plot_chance_level", [True, False]) +@pytest.mark.parametrize("label", [None, "Test Label"]) +@pytest.mark.parametrize( + "chance_level_kw", + [ + None, + {"linewidth": 1, "color": "red", "linestyle": "-", "label": "DummyEstimator"}, + {"lw": 1, "c": "red", "ls": "-", "label": "DummyEstimator"}, + {"lw": 1, "color": "blue", "ls": "-", "label": None}, + ], +) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_roc_curve_chance_level_line( + pyplot, + data_binary, + plot_chance_level, + chance_level_kw, + label, + constructor_name, +): + """Check chance level plotting behavior of `from_predictions`, `from_estimator`.""" + X, y = data_binary + + lr = LogisticRegression() + lr.fit(X, y) + + y_score = getattr(lr, "predict_proba")(X) + y_score = y_score if y_score.ndim == 1 else y_score[:, 1] + + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator( + lr, + X, + y, + curve_kwargs={"alpha": 0.8, "label": label}, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + ) + else: + display = RocCurveDisplay.from_predictions( + y, + y_score, + curve_kwargs={"alpha": 0.8, "label": label}, + plot_chance_level=plot_chance_level, + chance_level_kw=chance_level_kw, + ) + + import matplotlib as mpl + + assert isinstance(display.line_, mpl.lines.Line2D) + assert display.line_.get_alpha() == 0.8 + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + + _check_chance_level(plot_chance_level, chance_level_kw, display) + + # Checking for legend behaviour + if plot_chance_level and chance_level_kw is not None: + if label is not None or chance_level_kw.get("label") is not None: + legend = display.ax_.get_legend() + assert legend is not None # Legend should be present if any label is set + legend_labels = [text.get_text() for text in legend.get_texts()] + if label is not None: + assert label in legend_labels + if chance_level_kw.get("label") is not None: + assert chance_level_kw["label"] in legend_labels + else: + assert display.ax_.get_legend() is None + + +@pytest.mark.parametrize("plot_chance_level", [True, False]) +@pytest.mark.parametrize( + "chance_level_kw", + [ + None, + {"linewidth": 1, "color": "red", "linestyle": "-", "label": "DummyEstimator"}, + {"lw": 1, "c": "red", "ls": "-", "label": "DummyEstimator"}, + {"lw": 1, "color": "blue", "ls": "-", "label": None}, + ], +) +@pytest.mark.parametrize("curve_kwargs", [None, {"alpha": 0.8}]) +def test_roc_curve_chance_level_line_from_cv_results( + pyplot, + data_binary, + plot_chance_level, + chance_level_kw, + curve_kwargs, +): + """Check chance level plotting behavior with `from_cv_results`.""" + X, y = data_binary + n_cv = 3 + cv_results = cross_validate( + LogisticRegression(), X, y, cv=n_cv, return_estimator=True, return_indices=True + ) + + display = RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + plot_chance_level=plot_chance_level, + chance_level_kwargs=chance_level_kw, + curve_kwargs=curve_kwargs, + ) + + import matplotlib as mpl + + assert all(isinstance(line, mpl.lines.Line2D) for line in display.line_) + # Ensure both curve line kwargs passed correctly as well + if curve_kwargs: + assert all(line.get_alpha() == 0.8 for line in display.line_) + assert isinstance(display.ax_, mpl.axes.Axes) + assert isinstance(display.figure_, mpl.figure.Figure) + + _check_chance_level(plot_chance_level, chance_level_kw, display) + + legend = display.ax_.get_legend() + # There is always a legend, to indicate each 'Fold' curve + assert legend is not None + legend_labels = [text.get_text() for text in legend.get_texts()] + if plot_chance_level and chance_level_kw is not None: + if chance_level_kw.get("label") is not None: + assert chance_level_kw["label"] in legend_labels + else: + assert len(legend_labels) == 1 + + +@pytest.mark.parametrize( + "clf", + [ + LogisticRegression(), + make_pipeline(StandardScaler(), LogisticRegression()), + make_pipeline( + make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression() + ), + ], +) +@pytest.mark.parametrize("constructor_name", ["from_estimator", "from_predictions"]) +def test_roc_curve_display_complex_pipeline(pyplot, data_binary, clf, constructor_name): + """Check the behaviour with complex pipeline.""" + X, y = data_binary + + clf = clone(clf) + + if constructor_name == "from_estimator": + with pytest.raises(NotFittedError): + RocCurveDisplay.from_estimator(clf, X, y) + + clf.fit(X, y) + + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator(clf, X, y) + name = clf.__class__.__name__ + else: + display = RocCurveDisplay.from_predictions(y, y) + name = "Classifier" + + assert name in display.line_.get_label() + assert display.name == name + + +@pytest.mark.parametrize( + "roc_auc, name, curve_kwargs, expected_labels", + [ + ([0.9, 0.8], None, None, ["AUC = 0.85 +/- 0.05", "_child1"]), + ([0.9, 0.8], "Est name", None, ["Est name (AUC = 0.85 +/- 0.05)", "_child1"]), + ( + [0.8, 0.7], + ["fold1", "fold2"], + [{"c": "blue"}, {"c": "red"}], + ["fold1 (AUC = 0.80)", "fold2 (AUC = 0.70)"], + ), + (None, ["fold1", "fold2"], [{"c": "blue"}, {"c": "red"}], ["fold1", "fold2"]), + ], +) +def test_roc_curve_display_default_labels( + pyplot, roc_auc, name, curve_kwargs, expected_labels +): + """Check the default labels used in the display.""" + fpr = [np.array([0, 0.5, 1]), np.array([0, 0.3, 1])] + tpr = [np.array([0, 0.5, 1]), np.array([0, 0.3, 1])] + disp = RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc, name=name).plot( + curve_kwargs=curve_kwargs + ) + for idx, expected_label in enumerate(expected_labels): + assert disp.line_[idx].get_label() == expected_label + + +def _check_auc(display, constructor_name): + roc_auc_limit = 0.95679 + roc_auc_limit_multi = [0.97007, 0.985915, 0.980952] + + if constructor_name == "from_cv_results": + for idx, roc_auc in enumerate(display.roc_auc): + assert roc_auc == pytest.approx(roc_auc_limit_multi[idx]) + else: + assert display.roc_auc == pytest.approx(roc_auc_limit) + assert trapezoid(display.tpr, display.fpr) == pytest.approx(roc_auc_limit) + + +@pytest.mark.parametrize("response_method", ["predict_proba", "decision_function"]) +@pytest.mark.parametrize( + "constructor_name", ["from_estimator", "from_predictions", "from_cv_results"] +) +def test_plot_roc_curve_pos_label(pyplot, response_method, constructor_name): + # check that we can provide the positive label and display the proper + # statistics + X, y = load_breast_cancer(return_X_y=True) + # create an highly imbalanced + idx_positive = np.flatnonzero(y == 1) + idx_negative = np.flatnonzero(y == 0) + idx_selected = np.hstack([idx_negative, idx_positive[:25]]) + X, y = X[idx_selected], y[idx_selected] + X, y = shuffle(X, y, random_state=42) + # only use 2 features to make the problem even harder + X = X[:, :2] + y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + stratify=y, + random_state=0, + ) + + classifier = LogisticRegression() + classifier.fit(X_train, y_train) + cv_results = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True + ) + + # Sanity check to be sure the positive class is `classes_[0]` + # Class imbalance ensures a large difference in prediction values between classes, + # allowing us to catch errors when we switch `pos_label` + assert classifier.classes_.tolist() == ["cancer", "not cancer"] + + y_score = getattr(classifier, response_method)(X_test) + # we select the corresponding probability columns or reverse the decision + # function otherwise + y_score_cancer = -1 * y_score if y_score.ndim == 1 else y_score[:, 0] + y_score_not_cancer = y_score if y_score.ndim == 1 else y_score[:, 1] + + pos_label = "cancer" + y_score = y_score_cancer + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator( + classifier, + X_test, + y_test, + pos_label=pos_label, + response_method=response_method, + ) + elif constructor_name == "from_predictions": + display = RocCurveDisplay.from_predictions( + y_test, + y_score, + pos_label=pos_label, + ) + else: + display = RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + response_method=response_method, + pos_label=pos_label, + ) + + _check_auc(display, constructor_name) + + pos_label = "not cancer" + y_score = y_score_not_cancer + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator( + classifier, + X_test, + y_test, + response_method=response_method, + pos_label=pos_label, + ) + elif constructor_name == "from_predictions": + display = RocCurveDisplay.from_predictions( + y_test, + y_score, + pos_label=pos_label, + ) + else: + display = RocCurveDisplay.from_cv_results( + cv_results, + X, + y, + response_method=response_method, + pos_label=pos_label, + ) + + _check_auc(display, constructor_name) + + +# TODO(1.9): remove +def test_y_score_and_y_pred_specified_error(): + """Check that an error is raised when both y_score and y_pred are specified.""" + y_true = np.array([0, 1, 1, 0]) + y_score = np.array([0.1, 0.4, 0.35, 0.8]) + y_pred = np.array([0.2, 0.3, 0.5, 0.1]) + + with pytest.raises( + ValueError, match="`y_pred` and `y_score` cannot be both specified" + ): + RocCurveDisplay.from_predictions(y_true, y_score=y_score, y_pred=y_pred) + + +# TODO(1.9): remove +def test_y_pred_deprecation_warning(pyplot): + """Check that a warning is raised when y_pred is specified.""" + y_true = np.array([0, 1, 1, 0]) + y_score = np.array([0.1, 0.4, 0.35, 0.8]) + + with pytest.warns(FutureWarning, match="y_pred is deprecated in 1.7"): + display_y_pred = RocCurveDisplay.from_predictions(y_true, y_pred=y_score) + + assert_allclose(display_y_pred.fpr, [0, 0.5, 0.5, 1]) + assert_allclose(display_y_pred.tpr, [0, 0, 1, 1]) + + display_y_score = RocCurveDisplay.from_predictions(y_true, y_score) + assert_allclose(display_y_score.fpr, [0, 0.5, 0.5, 1]) + assert_allclose(display_y_score.tpr, [0, 0, 1, 1]) + + +@pytest.mark.parametrize("despine", [True, False]) +@pytest.mark.parametrize( + "constructor_name", ["from_estimator", "from_predictions", "from_cv_results"] +) +def test_plot_roc_curve_despine(pyplot, data_binary, despine, constructor_name): + # Check that the despine keyword is working correctly + X, y = data_binary + + lr = LogisticRegression().fit(X, y) + lr.fit(X, y) + cv_results = cross_validate( + LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True + ) + + y_pred = lr.decision_function(X) + + # safe guard for the if/else construction + assert constructor_name in ("from_estimator", "from_predictions", "from_cv_results") + + if constructor_name == "from_estimator": + display = RocCurveDisplay.from_estimator(lr, X, y, despine=despine) + elif constructor_name == "from_predictions": + display = RocCurveDisplay.from_predictions(y, y_pred, despine=despine) + else: + display = RocCurveDisplay.from_cv_results(cv_results, X, y, despine=despine) + + for s in ["top", "right"]: + assert display.ax_.spines[s].get_visible() is not despine + + if despine: + for s in ["bottom", "left"]: + assert display.ax_.spines[s].get_bounds() == (0, 1) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_ranking.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..2d0e5211c236c703676923a65bfe5df75affef96 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_ranking.py @@ -0,0 +1,2077 @@ +"""Metrics to assess performance on classification task given scores. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from functools import partial +from numbers import Integral, Real + +import numpy as np +from scipy.integrate import trapezoid +from scipy.sparse import csr_matrix, issparse +from scipy.stats import rankdata + +from ..exceptions import UndefinedMetricWarning +from ..preprocessing import label_binarize +from ..utils import ( + assert_all_finite, + check_array, + check_consistent_length, + column_or_1d, +) +from ..utils._encode import _encode, _unique +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.extmath import stable_cumsum +from ..utils.multiclass import type_of_target +from ..utils.sparsefuncs import count_nonzero +from ..utils.validation import _check_pos_label_consistency, _check_sample_weight +from ._base import _average_binary_score, _average_multiclass_ovo_score + + +@validate_params( + {"x": ["array-like"], "y": ["array-like"]}, + prefer_skip_nested_validation=True, +) +def auc(x, y): + """Compute Area Under the Curve (AUC) using the trapezoidal rule. + + This is a general function, given points on a curve. For computing the + area under the ROC-curve, see :func:`roc_auc_score`. For an alternative + way to summarize a precision-recall curve, see + :func:`average_precision_score`. + + Parameters + ---------- + x : array-like of shape (n,) + X coordinates. These must be either monotonic increasing or monotonic + decreasing. + y : array-like of shape (n,) + Y coordinates. + + Returns + ------- + auc : float + Area Under the Curve. + + See Also + -------- + roc_auc_score : Compute the area under the ROC curve. + average_precision_score : Compute average precision from prediction scores. + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y_true = np.array([1, 1, 2, 2]) + >>> y_score = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score, pos_label=2) + >>> metrics.auc(fpr, tpr) + 0.75 + """ + check_consistent_length(x, y) + x = column_or_1d(x) + y = column_or_1d(y) + + if x.shape[0] < 2: + raise ValueError( + "At least 2 points are needed to compute area under curve, but x.shape = %s" + % x.shape + ) + + direction = 1 + dx = np.diff(x) + if np.any(dx < 0): + if np.all(dx <= 0): + direction = -1 + else: + raise ValueError("x is neither increasing nor decreasing : {}.".format(x)) + + area = direction * trapezoid(y, x) + if isinstance(area, np.memmap): + # Reductions such as .sum used internally in trapezoid do not return a + # scalar by default for numpy.memmap instances contrary to + # regular numpy.ndarray instances. + area = area.dtype.type(area) + return float(area) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "average": [StrOptions({"micro", "samples", "weighted", "macro"}), None], + "pos_label": [Real, str, "boolean"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def average_precision_score( + y_true, y_score, *, average="macro", pos_label=1, sample_weight=None +): + """Compute average precision (AP) from prediction scores. + + AP summarizes a precision-recall curve as the weighted mean of precisions + achieved at each threshold, with the increase in recall from the previous + threshold used as the weight: + + .. math:: + \\text{AP} = \\sum_n (R_n - R_{n-1}) P_n + + where :math:`P_n` and :math:`R_n` are the precision and recall at the nth + threshold [1]_. This implementation is not interpolated and is different + from computing the area under the precision-recall curve with the + trapezoidal rule, which uses linear interpolation and can be too + optimistic. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_classes) + True binary labels or binary label indicators. + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by :term:`decision_function` on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + average : {'micro', 'samples', 'weighted', 'macro'} or None, \ + default='macro' + If ``None``, the scores for each class are returned. Otherwise, + this determines the type of averaging performed on the data: + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + pos_label : int, float, bool or str, default=1 + The label of the positive class. Only applied to binary ``y_true``. + For multilabel-indicator ``y_true``, ``pos_label`` is fixed to 1. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + average_precision : float + Average precision score. + + See Also + -------- + roc_auc_score : Compute the area under the ROC curve. + precision_recall_curve : Compute precision-recall pairs for different + probability thresholds. + PrecisionRecallDisplay.from_estimator : Plot the precision recall curve + using an estimator and data. + PrecisionRecallDisplay.from_predictions : Plot the precision recall curve + using true and predicted labels. + + Notes + ----- + .. versionchanged:: 0.19 + Instead of linearly interpolating between operating points, precisions + are weighted by the change in recall since the last operating point. + + References + ---------- + .. [1] `Wikipedia entry for the Average precision + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import average_precision_score + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> average_precision_score(y_true, y_scores) + 0.83 + >>> y_true = np.array([0, 0, 1, 1, 2, 2]) + >>> y_scores = np.array([ + ... [0.7, 0.2, 0.1], + ... [0.4, 0.3, 0.3], + ... [0.1, 0.8, 0.1], + ... [0.2, 0.3, 0.5], + ... [0.4, 0.4, 0.2], + ... [0.1, 0.2, 0.7], + ... ]) + >>> average_precision_score(y_true, y_scores) + 0.77 + """ + + def _binary_uninterpolated_average_precision( + y_true, y_score, pos_label=1, sample_weight=None + ): + precision, recall, _ = precision_recall_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + # Return the step function integral + # The following works because the last entry of precision is + # guaranteed to be 1, as returned by precision_recall_curve. + # Due to numerical error, we can get `-0.0` and we therefore clip it. + return float(max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1]))) + + y_type = type_of_target(y_true, input_name="y_true") + + # Convert to Python primitive type to avoid NumPy type / Python str + # comparison. See https://github.com/numpy/numpy/issues/6784 + present_labels = np.unique(y_true).tolist() + + if y_type == "binary": + if len(present_labels) == 2 and pos_label not in present_labels: + raise ValueError( + f"pos_label={pos_label} is not a valid label. It should be " + f"one of {present_labels}" + ) + + elif y_type == "multilabel-indicator" and pos_label != 1: + raise ValueError( + "Parameter pos_label is fixed to 1 for multilabel-indicator y_true. " + "Do not set pos_label or set pos_label to 1." + ) + + elif y_type == "multiclass": + if pos_label != 1: + raise ValueError( + "Parameter pos_label is fixed to 1 for multiclass y_true. " + "Do not set pos_label or set pos_label to 1." + ) + y_true = label_binarize(y_true, classes=present_labels) + + average_precision = partial( + _binary_uninterpolated_average_precision, pos_label=pos_label + ) + return _average_binary_score( + average_precision, y_true, y_score, average, sample_weight=sample_weight + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "pos_label": [Real, str, "boolean", None], + "sample_weight": ["array-like", None], + "drop_intermediate": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def det_curve( + y_true, y_score, pos_label=None, sample_weight=None, drop_intermediate=False +): + """Compute Detection Error Tradeoff (DET) for different probability thresholds. + + .. note:: + This metric is used for evaluation of ranking and error tradeoffs of + a binary classification task. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + .. versionchanged:: 1.7 + An arbitrary threshold at infinity is added to represent a classifier + that always predicts the negative class, i.e. `fpr=0` and `fnr=1`, unless + `fpr=0` is already reached at a finite threshold. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + y_score : ndarray of shape of (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by "decision_function" on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + pos_label : int, float, bool or str, default=None + The label of the positive class. + When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, + ``pos_label`` is set to 1, otherwise an error will be raised. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=False + Whether to drop thresholds where true positives (tp) do not change from + the previous or subsequent threshold. All points with the same tp value + have the same `fnr` and thus same y coordinate. + + .. versionadded:: 1.7 + + Returns + ------- + fpr : ndarray of shape (n_thresholds,) + False positive rate (FPR) such that element i is the false positive + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false acceptance probability or fall-out. + + fnr : ndarray of shape (n_thresholds,) + False negative rate (FNR) such that element i is the false negative + rate of predictions with score >= thresholds[i]. This is occasionally + referred to as false rejection or miss rate. + + thresholds : ndarray of shape (n_thresholds,) + Decreasing thresholds on the decision function (either `predict_proba` + or `decision_function`) used to compute FPR and FNR. + + .. versionchanged:: 1.7 + An arbitrary threshold at infinity is added for the case `fpr=0` + and `fnr=1`. + + See Also + -------- + DetCurveDisplay.from_estimator : Plot DET curve given an estimator and + some data. + DetCurveDisplay.from_predictions : Plot DET curve given the true and + predicted labels. + DetCurveDisplay : DET curve visualization. + roc_curve : Compute Receiver operating characteristic (ROC) curve. + precision_recall_curve : Compute precision-recall curve. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import det_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, fnr, thresholds = det_curve(y_true, y_scores) + >>> fpr + array([0.5, 0.5, 0. ]) + >>> fnr + array([0. , 0.5, 0.5]) + >>> thresholds + array([0.35, 0.4 , 0.8 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + + # add a threshold at inf where the clf always predicts the negative class + # i.e. tps = fps = 0 + tps = np.concatenate(([0], tps)) + fps = np.concatenate(([0], fps)) + thresholds = np.concatenate(([np.inf], thresholds)) + + if drop_intermediate and len(fps) > 2: + # Drop thresholds where true positives (tp) do not change from the + # previous or subsequent threshold. As tp + fn, is fixed for a dataset, + # this means the false negative rate (fnr) remains constant while the + # false positive rate (fpr) changes, producing horizontal line segments + # in the transformed (normal deviate) scale. These intermediate points + # can be dropped to create lighter DET curve plots. + optimal_idxs = np.where( + np.concatenate( + [[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]] + ) + )[0] + fps = fps[optimal_idxs] + tps = tps[optimal_idxs] + thresholds = thresholds[optimal_idxs] + + if len(np.unique(y_true)) != 2: + raise ValueError( + "Only one class is present in y_true. Detection error " + "tradeoff curve is not defined in that case." + ) + + fns = tps[-1] - tps + p_count = tps[-1] + n_count = fps[-1] + + # start with false positives zero, which may be at a finite threshold + 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: + warnings.warn( + ( + "Only one class is present in y_true. ROC AUC score " + "is not defined in that case." + ), + UndefinedMetricWarning, + ) + return np.nan + + fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight) + if max_fpr is None or max_fpr == 1: + return auc(fpr, tpr) + if max_fpr <= 0 or max_fpr > 1: + raise ValueError("Expected max_fpr in range (0, 1], got: %r" % max_fpr) + + # Add a single point at max_fpr by linear interpolation + stop = np.searchsorted(fpr, max_fpr, "right") + x_interp = [fpr[stop - 1], fpr[stop]] + y_interp = [tpr[stop - 1], tpr[stop]] + tpr = np.append(tpr[:stop], np.interp(max_fpr, x_interp, y_interp)) + fpr = np.append(fpr[:stop], max_fpr) + partial_auc = auc(fpr, tpr) + + # McClish correction: standardize result to be 0.5 if non-discriminant + # and 1 if maximal + min_area = 0.5 * max_fpr**2 + max_area = max_fpr + return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "average": [StrOptions({"micro", "macro", "samples", "weighted"}), None], + "sample_weight": ["array-like", None], + "max_fpr": [Interval(Real, 0.0, 1, closed="right"), None], + "multi_class": [StrOptions({"raise", "ovr", "ovo"})], + "labels": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def roc_auc_score( + y_true, + y_score, + *, + average="macro", + sample_weight=None, + max_fpr=None, + multi_class="raise", + labels=None, +): + """Compute Area Under the Receiver Operating Characteristic Curve (ROC AUC) \ + from prediction scores. + + Note: this implementation can be used with binary, multiclass and + multilabel classification, but some restrictions apply (see Parameters). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_classes) + True labels or binary label indicators. The binary and multiclass cases + expect labels with shape (n_samples,) while the multilabel case expects + binary label indicators with shape (n_samples, n_classes). + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores. + + * In the binary case, it corresponds to an array of shape + `(n_samples,)`. Both probability estimates and non-thresholded + decision values can be provided. The probability estimates correspond + to the **probability of the class with the greater label**, + i.e. `estimator.classes_[1]` and thus + `estimator.predict_proba(X, y)[:, 1]`. The decision values + corresponds to the output of `estimator.decision_function(X, y)`. + See more information in the :ref:`User guide `; + * In the multiclass case, it corresponds to an array of shape + `(n_samples, n_classes)` of probability estimates provided by the + `predict_proba` method. The probability estimates **must** + sum to 1 across the possible classes. In addition, the order of the + class scores must correspond to the order of ``labels``, + if provided, or else to the numerical or lexicographical order of + the labels in ``y_true``. See more information in the + :ref:`User guide `; + * In the multilabel case, it corresponds to an array of shape + `(n_samples, n_classes)`. Probability estimates are provided by the + `predict_proba` method and the non-thresholded decision values by + the `decision_function` method. The probability estimates correspond + to the **probability of the class with the greater label for each + output** of the classifier. See more information in the + :ref:`User guide `. + + average : {'micro', 'macro', 'samples', 'weighted'} or None, \ + default='macro' + If ``None``, the scores for each class are returned. + Otherwise, this determines the type of averaging performed on the data. + Note: multiclass ROC AUC currently only handles the 'macro' and + 'weighted' averages. For multiclass targets, `average=None` is only + implemented for `multi_class='ovr'` and `average='micro'` is only + implemented for `multi_class='ovr'`. + + ``'micro'``: + Calculate metrics globally by considering each element of the label + indicator matrix as a label. + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. + ``'weighted'``: + Calculate metrics for each label, and find their average, weighted + by support (the number of true instances for each label). + ``'samples'``: + Calculate metrics for each instance, and find their average. + + Will be ignored when ``y_true`` is binary. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + max_fpr : float > 0 and <= 1, default=None + If not ``None``, the standardized partial AUC [2]_ over the range + [0, max_fpr] is returned. For the multiclass case, ``max_fpr``, + should be either equal to ``None`` or ``1.0`` as AUC ROC partial + computation currently is not supported for multiclass. + + multi_class : {'raise', 'ovr', 'ovo'}, default='raise' + Only used for multiclass targets. Determines the type of configuration + to use. The default value raises an error, so either + ``'ovr'`` or ``'ovo'`` must be passed explicitly. + + ``'ovr'``: + Stands for One-vs-rest. Computes the AUC of each class + against the rest [3]_ [4]_. This + treats the multiclass case in the same way as the multilabel case. + Sensitive to class imbalance even when ``average == 'macro'``, + because class imbalance affects the composition of each of the + 'rest' groupings. + ``'ovo'``: + Stands for One-vs-one. Computes the average AUC of all + possible pairwise combinations of classes [5]_. + Insensitive to class imbalance when + ``average == 'macro'``. + + labels : array-like of shape (n_classes,), default=None + Only used for multiclass targets. List of labels that index the + classes in ``y_score``. If ``None``, the numerical or lexicographical + order of the labels in ``y_true`` is used. + + Returns + ------- + auc : float + Area Under the Curve score. + + See Also + -------- + average_precision_score : Area under the precision-recall curve. + roc_curve : Compute Receiver operating characteristic (ROC) curve. + RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic + (ROC) curve given an estimator and some data. + RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic + (ROC) curve given the true and predicted values. + + Notes + ----- + The Gini Coefficient is a summary measure of the ranking ability of binary + classifiers. It is expressed using the area under of the ROC as follows: + + G = 2 * AUC - 1 + + Where G is the Gini coefficient and AUC is the ROC-AUC score. This normalisation + will ensure that random guessing will yield a score of 0 in expectation, and it is + upper bounded by 1. + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + .. [2] `Analyzing a portion of the ROC curve. McClish, 1989 + `_ + + .. [3] Provost, F., Domingos, P. (2000). Well-trained PETs: Improving + probability estimation trees (Section 6.2), CeDER Working Paper + #IS-00-04, Stern School of Business, New York University. + + .. [4] `Fawcett, T. (2006). An introduction to ROC analysis. Pattern + Recognition Letters, 27(8), 861-874. + `_ + + .. [5] `Hand, D.J., Till, R.J. (2001). A Simple Generalisation of the Area + Under the ROC Curve for Multiple Class Classification Problems. + Machine Learning, 45(2), 171-186. + `_ + .. [6] `Wikipedia entry for the Gini coefficient + `_ + + Examples + -------- + Binary case: + + >>> from sklearn.datasets import load_breast_cancer + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.metrics import roc_auc_score + >>> X, y = load_breast_cancer(return_X_y=True) + >>> clf = LogisticRegression(solver="newton-cholesky", random_state=0).fit(X, y) + >>> roc_auc_score(y, clf.predict_proba(X)[:, 1]) + 0.99 + >>> roc_auc_score(y, clf.decision_function(X)) + 0.99 + + Multiclass case: + + >>> from sklearn.datasets import load_iris + >>> X, y = load_iris(return_X_y=True) + >>> clf = LogisticRegression(solver="newton-cholesky").fit(X, y) + >>> roc_auc_score(y, clf.predict_proba(X), multi_class='ovr') + 0.99 + + Multilabel case: + + >>> import numpy as np + >>> from sklearn.datasets import make_multilabel_classification + >>> from sklearn.multioutput import MultiOutputClassifier + >>> X, y = make_multilabel_classification(random_state=0) + >>> clf = MultiOutputClassifier(clf).fit(X, y) + >>> # get a list of n_output containing probability arrays of shape + >>> # (n_samples, n_classes) + >>> y_score = clf.predict_proba(X) + >>> # extract the positive columns for each output + >>> y_score = np.transpose([score[:, 1] for score in y_score]) + >>> roc_auc_score(y, y_score, average=None) + array([0.828, 0.852, 0.94, 0.869, 0.95]) + >>> from sklearn.linear_model import RidgeClassifierCV + >>> clf = RidgeClassifierCV().fit(X, y) + >>> roc_auc_score(y, clf.decision_function(X), average=None) + array([0.82, 0.847, 0.93, 0.872, 0.944]) + """ + + y_type = type_of_target(y_true, input_name="y_true") + y_true = check_array(y_true, ensure_2d=False, dtype=None) + y_score = check_array(y_score, ensure_2d=False) + + if y_type == "multiclass" or ( + y_type == "binary" and y_score.ndim == 2 and y_score.shape[1] > 2 + ): + # do not support partial ROC computation for multiclass + if max_fpr is not None and max_fpr != 1.0: + raise ValueError( + "Partial AUC computation not available in " + "multiclass setting, 'max_fpr' must be" + " set to `None`, received `max_fpr={0}` " + "instead".format(max_fpr) + ) + if multi_class == "raise": + raise ValueError("multi_class must be in ('ovo', 'ovr')") + return _multiclass_roc_auc_score( + y_true, y_score, labels, multi_class, average, sample_weight + ) + elif y_type == "binary": + labels = np.unique(y_true) + y_true = label_binarize(y_true, classes=labels)[:, 0] + return _average_binary_score( + partial(_binary_roc_auc_score, max_fpr=max_fpr), + y_true, + y_score, + average, + sample_weight=sample_weight, + ) + else: # multilabel-indicator + return _average_binary_score( + partial(_binary_roc_auc_score, max_fpr=max_fpr), + y_true, + y_score, + average, + sample_weight=sample_weight, + ) + + +def _multiclass_roc_auc_score( + y_true, y_score, labels, multi_class, average, sample_weight +): + """Multiclass roc auc score. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True multiclass labels. + + y_score : array-like of shape (n_samples, n_classes) + Target scores corresponding to probability estimates of a sample + belonging to a particular class + + labels : array-like of shape (n_classes,) or None + List of labels to index ``y_score`` used for multiclass. If ``None``, + the lexical order of ``y_true`` is used to index ``y_score``. + + multi_class : {'ovr', 'ovo'} + Determines the type of multiclass configuration to use. + ``'ovr'``: + Calculate metrics for the multiclass case using the one-vs-rest + approach. + ``'ovo'``: + Calculate metrics for the multiclass case using the one-vs-one + approach. + + average : {'micro', 'macro', 'weighted'} + Determines the type of averaging performed on the pairwise binary + metric scores + ``'micro'``: + Calculate metrics for the binarized-raveled classes. Only supported + for `multi_class='ovr'`. + + .. versionadded:: 1.2 + + ``'macro'``: + Calculate metrics for each label, and find their unweighted + mean. This does not take label imbalance into account. Classes + are assumed to be uniformly distributed. + ``'weighted'``: + Calculate metrics for each label, taking into account the + prevalence of the classes. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. + + """ + # validation of the input y_score + if not np.allclose(1, y_score.sum(axis=1)): + raise ValueError( + "Target scores need to be probabilities for multiclass " + "roc_auc, i.e. they should sum up to 1.0 over classes" + ) + + # validation for multiclass parameter specifications + average_options = ("macro", "weighted", None) + if multi_class == "ovr": + average_options = ("micro",) + average_options + if average not in average_options: + raise ValueError( + "average must be one of {0} for multiclass problems".format(average_options) + ) + + multiclass_options = ("ovo", "ovr") + if multi_class not in multiclass_options: + raise ValueError( + "multi_class='{0}' is not supported " + "for multiclass ROC AUC, multi_class must be " + "in {1}".format(multi_class, multiclass_options) + ) + + if average is None and multi_class == "ovo": + raise NotImplementedError( + "average=None is not implemented for multi_class='ovo'." + ) + + if labels is not None: + labels = column_or_1d(labels) + classes = _unique(labels) + if len(classes) != len(labels): + raise ValueError("Parameter 'labels' must be unique") + if not np.array_equal(classes, labels): + raise ValueError("Parameter 'labels' must be ordered") + if len(classes) != y_score.shape[1]: + raise ValueError( + "Number of given labels, {0}, not equal to the number " + "of columns in 'y_score', {1}".format(len(classes), y_score.shape[1]) + ) + if len(np.setdiff1d(y_true, classes)): + raise ValueError("'y_true' contains labels not in parameter 'labels'") + else: + classes = _unique(y_true) + if len(classes) != y_score.shape[1]: + raise ValueError( + "Number of classes in y_true not equal to the number of " + "columns in 'y_score'" + ) + + if multi_class == "ovo": + if sample_weight is not None: + raise ValueError( + "sample_weight is not supported " + "for multiclass one-vs-one ROC AUC, " + "'sample_weight' must be None in this case." + ) + y_true_encoded = _encode(y_true, uniques=classes) + # Hand & Till (2001) implementation (ovo) + return _average_multiclass_ovo_score( + _binary_roc_auc_score, y_true_encoded, y_score, average=average + ) + else: + # ovr is same as multi-label + y_true_multilabel = label_binarize(y_true, classes=classes) + return _average_binary_score( + _binary_roc_auc_score, + y_true_multilabel, + y_score, + average, + sample_weight=sample_weight, + ) + + +def _binary_clf_curve(y_true, y_score, pos_label=None, sample_weight=None): + """Calculate true and false positives per binary classification threshold. + + Parameters + ---------- + y_true : ndarray of shape (n_samples,) + True targets of binary classification. + + y_score : ndarray of shape (n_samples,) + Estimated probabilities or output of a decision function. + + pos_label : int, float, bool or str, default=None + The label of the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + fps : ndarray of shape (n_thresholds,) + A count of false positives, at index i being the number of negative + samples assigned a score >= thresholds[i]. The total number of + negative samples is equal to fps[-1] (thus true negatives are given by + fps[-1] - fps). + + tps : ndarray of shape (n_thresholds,) + An increasing count of true positives, at index i being the number + of positive samples assigned a score >= thresholds[i]. The total + number of positive samples is equal to tps[-1] (thus false negatives + are given by tps[-1] - tps). + + thresholds : ndarray of shape (n_thresholds,) + Decreasing score values. + """ + # Check to make sure y_true is valid + y_type = type_of_target(y_true, input_name="y_true") + if not (y_type == "binary" or (y_type == "multiclass" and pos_label is not None)): + raise ValueError("{0} format is not supported".format(y_type)) + + check_consistent_length(y_true, y_score, sample_weight) + y_true = column_or_1d(y_true) + y_score = column_or_1d(y_score) + assert_all_finite(y_true) + assert_all_finite(y_score) + + # Filter out zero-weighted samples, as they should not impact the result + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = _check_sample_weight(sample_weight, y_true) + nonzero_weight_mask = sample_weight != 0 + y_true = y_true[nonzero_weight_mask] + y_score = y_score[nonzero_weight_mask] + sample_weight = sample_weight[nonzero_weight_mask] + + pos_label = _check_pos_label_consistency(pos_label, y_true) + + # make y_true a boolean vector + y_true = y_true == pos_label + + # sort scores and corresponding truth values + desc_score_indices = np.argsort(y_score, kind="mergesort")[::-1] + y_score = y_score[desc_score_indices] + y_true = y_true[desc_score_indices] + if sample_weight is not None: + weight = sample_weight[desc_score_indices] + else: + weight = 1.0 + + # y_score typically has many tied values. Here we extract + # the indices associated with the distinct values. We also + # concatenate a value for the end of the curve. + distinct_value_indices = np.where(np.diff(y_score))[0] + threshold_idxs = np.r_[distinct_value_indices, y_true.size - 1] + + # accumulate the true positives with decreasing threshold + tps = stable_cumsum(y_true * weight)[threshold_idxs] + if sample_weight is not None: + # express fps as a cumsum to ensure fps is increasing even in + # the presence of floating point errors + fps = stable_cumsum((1 - y_true) * weight)[threshold_idxs] + else: + fps = 1 + threshold_idxs - tps + return fps, tps, y_score[threshold_idxs] + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "pos_label": [Real, str, "boolean", None], + "sample_weight": ["array-like", None], + "drop_intermediate": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def precision_recall_curve( + y_true, + y_score, + *, + pos_label=None, + sample_weight=None, + drop_intermediate=False, +): + """Compute precision-recall pairs for different probability thresholds. + + Note: this implementation is restricted to the binary classification task. + + The precision is the ratio ``tp / (tp + fp)`` where ``tp`` is the number of + true positives and ``fp`` the number of false positives. The precision is + intuitively the ability of the classifier not to label as positive a sample + that is negative. + + The recall is the ratio ``tp / (tp + fn)`` where ``tp`` is the number of + true positives and ``fn`` the number of false negatives. The recall is + intuitively the ability of the classifier to find all the positive samples. + + The last precision and recall values are 1. and 0. respectively and do not + have a corresponding threshold. This ensures that the graph starts on the + y axis. + + The first precision and recall values are precision=class balance and recall=1.0 + which corresponds to a classifier that always predicts the positive class. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + y_score : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, or non-thresholded measure of decisions (as returned by + `decision_function` on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + pos_label : int, float, bool or str, default=None + The label of the positive class. + When ``pos_label=None``, if y_true is in {-1, 1} or {0, 1}, + ``pos_label`` is set to 1, otherwise an error will be raised. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=False + Whether to drop some suboptimal thresholds which would not appear + on a plotted precision-recall curve. This is useful in order to create + lighter precision-recall curves. + + .. versionadded:: 1.3 + + Returns + ------- + precision : ndarray of shape (n_thresholds + 1,) + Precision values such that element i is the precision of + predictions with score >= thresholds[i] and the last element is 1. + + recall : ndarray of shape (n_thresholds + 1,) + Decreasing recall values such that element i is the recall of + predictions with score >= thresholds[i] and the last element is 0. + + thresholds : ndarray of shape (n_thresholds,) + Increasing thresholds on the decision function used to compute + precision and recall where `n_thresholds = len(np.unique(y_score))`. + + See Also + -------- + PrecisionRecallDisplay.from_estimator : Plot Precision Recall Curve given + a binary classifier. + PrecisionRecallDisplay.from_predictions : Plot Precision Recall Curve + using predictions from a binary classifier. + average_precision_score : Compute average precision from prediction scores. + det_curve: Compute error rates for different probability thresholds. + roc_curve : Compute Receiver operating characteristic (ROC) curve. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import precision_recall_curve + >>> y_true = np.array([0, 0, 1, 1]) + >>> y_scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> precision, recall, thresholds = precision_recall_curve( + ... y_true, y_scores) + >>> precision + array([0.5 , 0.66666667, 0.5 , 1. , 1. ]) + >>> recall + array([1. , 1. , 0.5, 0.5, 0. ]) + >>> thresholds + array([0.1 , 0.35, 0.4 , 0.8 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + + if drop_intermediate and len(fps) > 2: + # Drop thresholds corresponding to points where true positives (tps) + # do not change from the previous or subsequent point. This will keep + # only the first and last point for each tps value. All points + # with the same tps value have the same recall and thus x coordinate. + # They appear as a vertical line on the plot. + optimal_idxs = np.where( + np.concatenate( + [[True], np.logical_or(np.diff(tps[:-1]), np.diff(tps[1:])), [True]] + ) + )[0] + fps = fps[optimal_idxs] + tps = tps[optimal_idxs] + thresholds = thresholds[optimal_idxs] + + ps = tps + fps + # Initialize the result array with zeros to make sure that precision[ps == 0] + # does not contain uninitialized values. + precision = np.zeros_like(tps) + np.divide(tps, ps, out=precision, where=(ps != 0)) + + # When no positive label in y_true, recall is set to 1 for all thresholds + # tps[-1] == 0 <=> y_true == all negative labels + if tps[-1] == 0: + warnings.warn( + "No positive class found in y_true, " + "recall is set to one for all thresholds." + ) + recall = np.ones_like(tps) + else: + recall = tps / tps[-1] + + # reverse the outputs so recall is decreasing + sl = slice(None, None, -1) + return np.hstack((precision[sl], 1)), np.hstack((recall[sl], 0)), thresholds[sl] + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "pos_label": [Real, str, "boolean", None], + "sample_weight": ["array-like", None], + "drop_intermediate": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def roc_curve( + y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=True +): + """Compute Receiver operating characteristic (ROC). + + Note: this implementation is restricted to the binary classification task. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True binary labels. If labels are not either {-1, 1} or {0, 1}, then + pos_label should be explicitly given. + + y_score : array-like of shape (n_samples,) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by "decision_function" on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + pos_label : int, float, bool or str, default=None + The label of the positive class. + When ``pos_label=None``, if `y_true` is in {-1, 1} or {0, 1}, + ``pos_label`` is set to 1, otherwise an error will be raised. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + drop_intermediate : bool, default=True + Whether to drop thresholds where the resulting point is collinear with + its neighbors in ROC space. This has no effect on the ROC AUC or visual + shape of the curve, but reduces the number of plotted points. + + .. versionadded:: 0.17 + parameter *drop_intermediate*. + + Returns + ------- + fpr : ndarray of shape (>2,) + Increasing false positive rates such that element i is the false + positive rate of predictions with score >= `thresholds[i]`. + + tpr : ndarray of shape (>2,) + Increasing true positive rates such that element `i` is the true + positive rate of predictions with score >= `thresholds[i]`. + + thresholds : ndarray of shape (n_thresholds,) + Decreasing thresholds on the decision function used to compute + fpr and tpr. The first threshold is set to `np.inf`. + + .. versionchanged:: 1.3 + An arbitrary threshold at infinity (stored in `thresholds[0]`) is + added to represent a classifier that always predicts the negative + class, i.e. `fpr=0` and `tpr=0`. + + See Also + -------- + RocCurveDisplay.from_estimator : Plot Receiver Operating Characteristic + (ROC) curve given an estimator and some data. + RocCurveDisplay.from_predictions : Plot Receiver Operating Characteristic + (ROC) curve given the true and predicted values. + det_curve: Compute error rates for different probability thresholds. + roc_auc_score : Compute the area under the ROC curve. + + Notes + ----- + Since the thresholds are sorted from low to high values, they + are reversed upon returning them to ensure they correspond to both ``fpr`` + and ``tpr``, which are sorted in reversed order during their calculation. + + References + ---------- + .. [1] `Wikipedia entry for the Receiver operating characteristic + `_ + + .. [2] Fawcett T. An introduction to ROC analysis[J]. Pattern Recognition + Letters, 2006, 27(8):861-874. + + Examples + -------- + >>> import numpy as np + >>> from sklearn import metrics + >>> y = np.array([1, 1, 2, 2]) + >>> scores = np.array([0.1, 0.4, 0.35, 0.8]) + >>> fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2) + >>> fpr + array([0. , 0. , 0.5, 0.5, 1. ]) + >>> tpr + array([0. , 0.5, 0.5, 1. , 1. ]) + >>> thresholds + array([ inf, 0.8 , 0.4 , 0.35, 0.1 ]) + """ + fps, tps, thresholds = _binary_clf_curve( + y_true, y_score, pos_label=pos_label, sample_weight=sample_weight + ) + + # Attempt to drop thresholds corresponding to points in between and + # collinear with other points. These are always suboptimal and do not + # appear on a plotted ROC curve (and thus do not affect the AUC). + # Here np.diff(_, 2) is used as a "second derivative" to tell if there + # is a corner at the point. Both fps and tps must be tested to handle + # thresholds with multiple data points (which are combined in + # _binary_clf_curve). This keeps all cases where the point should be kept, + # but does not drop more complicated cases like fps = [1, 3, 7], + # tps = [1, 2, 4]; there is no harm in keeping too many thresholds. + if drop_intermediate and len(fps) > 2: + optimal_idxs = np.where( + np.r_[True, np.logical_or(np.diff(fps, 2), np.diff(tps, 2)), True] + )[0] + fps = fps[optimal_idxs] + tps = tps[optimal_idxs] + thresholds = thresholds[optimal_idxs] + + # Add an extra threshold position + # to make sure that the curve starts at (0, 0) + tps = np.r_[0, tps] + fps = np.r_[0, fps] + # get dtype of `y_score` even if it is an array-like + thresholds = np.r_[np.inf, thresholds] + + if fps[-1] <= 0: + warnings.warn( + "No negative samples in y_true, false positive value should be meaningless", + UndefinedMetricWarning, + ) + fpr = np.repeat(np.nan, fps.shape) + else: + fpr = fps / fps[-1] + + if tps[-1] <= 0: + warnings.warn( + "No positive samples in y_true, true positive value should be meaningless", + UndefinedMetricWarning, + ) + tpr = np.repeat(np.nan, tps.shape) + else: + tpr = tps / tps[-1] + + return fpr, tpr, thresholds + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_score": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None): + """Compute ranking-based average precision. + + Label ranking average precision (LRAP) is the average over each ground + truth label assigned to each sample, of the ratio of true vs. total + labels with lower score. + + This metric is used in multilabel ranking problem, where the goal + is to give better rank to the labels associated to each sample. + + The obtained score is always strictly greater than 0 and + the best value is 1. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : array-like of shape (n_samples, n_labels) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by "decision_function" on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.20 + + Returns + ------- + score : float + Ranking-based average precision score. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import label_ranking_average_precision_score + >>> y_true = np.array([[1, 0, 0], [0, 0, 1]]) + >>> y_score = np.array([[0.75, 0.5, 1], [1, 0.2, 0.1]]) + >>> label_ranking_average_precision_score(y_true, y_score) + 0.416 + """ + check_consistent_length(y_true, y_score, sample_weight) + y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") + y_score = check_array(y_score, ensure_2d=False) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + # Handle badly formatted array and the degenerate case with one label + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "multilabel-indicator" and not ( + y_type == "binary" and y_true.ndim == 2 + ): + raise ValueError("{0} format is not supported".format(y_type)) + + if not issparse(y_true): + y_true = csr_matrix(y_true) + + y_score = -y_score + + n_samples, n_labels = y_true.shape + + out = 0.0 + for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): + relevant = y_true.indices[start:stop] + + if relevant.size == 0 or relevant.size == n_labels: + # If all labels are relevant or unrelevant, the score is also + # equal to 1. The label ranking has no meaning. + aux = 1.0 + else: + scores_i = y_score[i] + rank = rankdata(scores_i, "max")[relevant] + L = rankdata(scores_i[relevant], "max") + aux = (L / rank).mean() + + if sample_weight is not None: + aux = aux * sample_weight[i] + out += aux + + if sample_weight is None: + out /= n_samples + else: + out /= np.sum(sample_weight) + + return float(out) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def coverage_error(y_true, y_score, *, sample_weight=None): + """Coverage error measure. + + Compute how far we need to go through the ranked scores to cover all + true labels. The best value is equal to the average number + of labels in ``y_true`` per sample. + + Ties in ``y_scores`` are broken by giving maximal rank that would have + been assigned to all tied values. + + Note: Our implementation's score is 1 greater than the one given in + Tsoumakas et al., 2010. This extends it to handle the degenerate case + in which an instance has 0 true labels. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : array-like of shape (n_samples, n_labels) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by "decision_function" on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + coverage_error : float + The coverage error. + + References + ---------- + .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). + Mining multi-label data. In Data mining and knowledge discovery + handbook (pp. 667-685). Springer US. + + Examples + -------- + >>> from sklearn.metrics import coverage_error + >>> y_true = [[1, 0, 0], [0, 1, 1]] + >>> y_score = [[1, 0, 0], [0, 1, 1]] + >>> coverage_error(y_true, y_score) + 1.5 + """ + y_true = check_array(y_true, ensure_2d=True) + y_score = check_array(y_score, ensure_2d=True) + check_consistent_length(y_true, y_score, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type != "multilabel-indicator": + raise ValueError("{0} format is not supported".format(y_type)) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + y_score_mask = np.ma.masked_array(y_score, mask=np.logical_not(y_true)) + y_min_relevant = y_score_mask.min(axis=1).reshape((-1, 1)) + coverage = (y_score >= y_min_relevant).sum(axis=1) + coverage = coverage.filled(0) + + return float(np.average(coverage, weights=sample_weight)) + + +@validate_params( + { + "y_true": ["array-like", "sparse matrix"], + "y_score": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def label_ranking_loss(y_true, y_score, *, sample_weight=None): + """Compute Ranking loss measure. + + Compute the average number of label pairs that are incorrectly ordered + given y_score weighted by the size of the label set and the number of + labels not in the label set. + + This is similar to the error set size, but weighted by the number of + relevant and irrelevant labels. The best performance is achieved with + a ranking loss of zero. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.17 + A function *label_ranking_loss* + + Parameters + ---------- + y_true : {array-like, sparse matrix} of shape (n_samples, n_labels) + True binary labels in binary indicator format. + + y_score : array-like of shape (n_samples, n_labels) + Target scores, can either be probability estimates of the positive + class, confidence values, or non-thresholded measure of decisions + (as returned by "decision_function" on some classifiers). + For :term:`decision_function` scores, values greater than or equal to + zero should indicate the positive class. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + Average number of label pairs that are incorrectly ordered given + y_score weighted by the size of the label set and the number of labels not + in the label set. + + References + ---------- + .. [1] Tsoumakas, G., Katakis, I., & Vlahavas, I. (2010). + Mining multi-label data. In Data mining and knowledge discovery + handbook (pp. 667-685). Springer US. + + Examples + -------- + >>> from sklearn.metrics import label_ranking_loss + >>> y_true = [[1, 0, 0], [0, 0, 1]] + >>> y_score = [[0.75, 0.5, 1], [1, 0.2, 0.1]] + >>> label_ranking_loss(y_true, y_score) + 0.75 + """ + y_true = check_array(y_true, ensure_2d=False, accept_sparse="csr") + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + + y_type = type_of_target(y_true, input_name="y_true") + if y_type not in ("multilabel-indicator",): + raise ValueError("{0} format is not supported".format(y_type)) + + if y_true.shape != y_score.shape: + raise ValueError("y_true and y_score have different shape") + + n_samples, n_labels = y_true.shape + + y_true = csr_matrix(y_true) + + loss = np.zeros(n_samples) + for i, (start, stop) in enumerate(zip(y_true.indptr, y_true.indptr[1:])): + # Sort and bin the label scores + unique_scores, unique_inverse = np.unique(y_score[i], return_inverse=True) + true_at_reversed_rank = np.bincount( + unique_inverse[y_true.indices[start:stop]], minlength=len(unique_scores) + ) + all_at_reversed_rank = np.bincount(unique_inverse, minlength=len(unique_scores)) + false_at_reversed_rank = all_at_reversed_rank - true_at_reversed_rank + + # if the scores are ordered, it's possible to count the number of + # incorrectly ordered paires in linear time by cumulatively counting + # how many false labels of a given score have a score higher than the + # accumulated true labels with lower score. + loss[i] = np.dot(true_at_reversed_rank.cumsum(), false_at_reversed_rank) + + n_positives = count_nonzero(y_true, axis=1) + with np.errstate(divide="ignore", invalid="ignore"): + loss /= (n_labels - n_positives) * n_positives + + # When there is no positive or no negative labels, those values should + # be consider as correct, i.e. the ranking doesn't matter. + loss[np.logical_or(n_positives == 0, n_positives == n_labels)] = 0.0 + + return float(np.average(loss, weights=sample_weight)) + + +def _dcg_sample_scores(y_true, y_score, k=None, log_base=2, ignore_ties=False): + """Compute Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If `None`, use all + outputs. + + log_base : float, default=2 + Base of the logarithm used for the discount. A low value means a + sharper discount (top results are more important). + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + discounted_cumulative_gain : ndarray of shape (n_samples,) + The DCG score for each sample. + + See Also + -------- + ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted + Cumulative Gain (the DCG obtained for a perfect ranking), in order to + have a score between 0 and 1. + """ + discount = 1 / (np.log(np.arange(y_true.shape[1]) + 2) / np.log(log_base)) + if k is not None: + discount[k:] = 0 + if ignore_ties: + ranking = np.argsort(y_score)[:, ::-1] + ranked = y_true[np.arange(ranking.shape[0])[:, np.newaxis], ranking] + cumulative_gains = discount.dot(ranked.T) + else: + discount_cumsum = np.cumsum(discount) + cumulative_gains = [ + _tie_averaged_dcg(y_t, y_s, discount_cumsum) + for y_t, y_s in zip(y_true, y_score) + ] + cumulative_gains = np.asarray(cumulative_gains) + return cumulative_gains + + +def _tie_averaged_dcg(y_true, y_score, discount_cumsum): + """ + Compute DCG by averaging over possible permutations of ties. + + The gain (`y_true`) of an index falling inside a tied group (in the order + induced by `y_score`) is replaced by the average gain within this group. + The discounted gain for a tied group is then the average `y_true` within + this group times the sum of discounts of the corresponding ranks. + + This amounts to averaging scores for all possible orderings of the tied + groups. + + (note in the case of dcg@k the discount is 0 after index k) + + Parameters + ---------- + y_true : ndarray + The true relevance scores. + + y_score : ndarray + Predicted scores. + + discount_cumsum : ndarray + Precomputed cumulative sum of the discounts. + + Returns + ------- + discounted_cumulative_gain : float + The discounted cumulative gain. + + References + ---------- + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + """ + _, inv, counts = np.unique(-y_score, return_inverse=True, return_counts=True) + ranked = np.zeros(len(counts)) + np.add.at(ranked, inv, y_true) + ranked /= counts + groups = np.cumsum(counts) - 1 + discount_sums = np.empty(len(counts)) + discount_sums[0] = discount_cumsum[groups[0]] + discount_sums[1:] = np.diff(discount_cumsum[groups]) + return (ranked * discount_sums).sum() + + +def _check_dcg_target_type(y_true): + y_type = type_of_target(y_true, input_name="y_true") + supported_fmt = ( + "multilabel-indicator", + "continuous-multioutput", + "multiclass-multioutput", + ) + if y_type not in supported_fmt: + raise ValueError( + "Only {} formats are supported. Got {} instead".format( + supported_fmt, y_type + ) + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "k": [Interval(Integral, 1, None, closed="left"), None], + "log_base": [Interval(Real, 0.0, None, closed="neither")], + "sample_weight": ["array-like", None], + "ignore_ties": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def dcg_score( + y_true, y_score, *, k=None, log_base=2, sample_weight=None, ignore_ties=False +): + """Compute Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Usually the Normalized Discounted Cumulative Gain (NDCG, computed by + ndcg_score) is preferred. + + Parameters + ---------- + y_true : array-like of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : array-like of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If None, use all + outputs. + + log_base : float, default=2 + Base of the logarithm used for the discount. A low value means a + sharper discount (top results are more important). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + discounted_cumulative_gain : float + The averaged sample DCG scores. + + See Also + -------- + ndcg_score : The Discounted Cumulative Gain divided by the Ideal Discounted + Cumulative Gain (the DCG obtained for a perfect ranking), in order to + have a score between 0 and 1. + + References + ---------- + `Wikipedia entry for Discounted Cumulative Gain + `_. + + Jarvelin, K., & Kekalainen, J. (2002). + Cumulated gain-based evaluation of IR techniques. ACM Transactions on + Information Systems (TOIS), 20(4), 422-446. + + Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). + A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th + Annual Conference on Learning Theory (COLT 2013). + + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import dcg_score + >>> # we have ground-truth relevance of some answers to a query: + >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) + >>> # we predict scores for the answers + >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) + >>> dcg_score(true_relevance, scores) + 9.49 + >>> # we can set k to truncate the sum; only top k answers contribute + >>> dcg_score(true_relevance, scores, k=2) + 5.63 + >>> # now we have some ties in our prediction + >>> scores = np.asarray([[1, 0, 0, 0, 1]]) + >>> # by default ties are averaged, so here we get the average true + >>> # relevance of our top predictions: (10 + 5) / 2 = 7.5 + >>> dcg_score(true_relevance, scores, k=1) + 7.5 + >>> # we can choose to ignore ties for faster results, but only + >>> # if we know there aren't ties in our scores, otherwise we get + >>> # wrong results: + >>> dcg_score(true_relevance, + ... scores, k=1, ignore_ties=True) + 5.0 + """ + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + _check_dcg_target_type(y_true) + return float( + np.average( + _dcg_sample_scores( + y_true, y_score, k=k, log_base=log_base, ignore_ties=ignore_ties + ), + weights=sample_weight, + ) + ) + + +def _ndcg_sample_scores(y_true, y_score, k=None, ignore_ties=False): + """Compute Normalized Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. Then divide by the best possible + score (Ideal DCG, obtained for a perfect ranking) to obtain a score between + 0 and 1. + + This ranking metric yields a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : ndarray of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. + + y_score : ndarray of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If None, use all + outputs. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + normalized_discounted_cumulative_gain : ndarray of shape (n_samples,) + The NDCG score for each sample (float in [0., 1.]). + + See Also + -------- + dcg_score : Discounted Cumulative Gain (not normalized). + + """ + gain = _dcg_sample_scores(y_true, y_score, k, ignore_ties=ignore_ties) + # Here we use the order induced by y_true so we can ignore ties since + # the gain associated to tied indices is the same (permuting ties doesn't + # change the value of the re-ordered y_true) + normalizing_gain = _dcg_sample_scores(y_true, y_true, k, ignore_ties=True) + all_irrelevant = normalizing_gain == 0 + gain[all_irrelevant] = 0 + gain[~all_irrelevant] /= normalizing_gain[~all_irrelevant] + return gain + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "k": [Interval(Integral, 1, None, closed="left"), None], + "sample_weight": ["array-like", None], + "ignore_ties": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def ndcg_score(y_true, y_score, *, k=None, sample_weight=None, ignore_ties=False): + """Compute Normalized Discounted Cumulative Gain. + + Sum the true scores ranked in the order induced by the predicted scores, + after applying a logarithmic discount. Then divide by the best possible + score (Ideal DCG, obtained for a perfect ranking) to obtain a score between + 0 and 1. + + This ranking metric returns a high value if true labels are ranked high by + ``y_score``. + + Parameters + ---------- + y_true : array-like of shape (n_samples, n_labels) + True targets of multilabel classification, or true scores of entities + to be ranked. Negative values in `y_true` may result in an output + that is not between 0 and 1. + + y_score : array-like of shape (n_samples, n_labels) + Target scores, can either be probability estimates, confidence values, + or non-thresholded measure of decisions (as returned by + "decision_function" on some classifiers). + + k : int, default=None + Only consider the highest k scores in the ranking. If `None`, use all + outputs. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + ignore_ties : bool, default=False + Assume that there are no ties in y_score (which is likely to be the + case if y_score is continuous) for efficiency gains. + + Returns + ------- + normalized_discounted_cumulative_gain : float in [0., 1.] + The averaged NDCG scores for all samples. + + See Also + -------- + dcg_score : Discounted Cumulative Gain (not normalized). + + References + ---------- + `Wikipedia entry for Discounted Cumulative Gain + `_ + + Jarvelin, K., & Kekalainen, J. (2002). + Cumulated gain-based evaluation of IR techniques. ACM Transactions on + Information Systems (TOIS), 20(4), 422-446. + + Wang, Y., Wang, L., Li, Y., He, D., Chen, W., & Liu, T. Y. (2013, May). + A theoretical analysis of NDCG ranking measures. In Proceedings of the 26th + Annual Conference on Learning Theory (COLT 2013) + + McSherry, F., & Najork, M. (2008, March). Computing information retrieval + performance measures efficiently in the presence of tied scores. In + European conference on information retrieval (pp. 414-421). Springer, + Berlin, Heidelberg. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import ndcg_score + >>> # we have ground-truth relevance of some answers to a query: + >>> true_relevance = np.asarray([[10, 0, 0, 1, 5]]) + >>> # we predict some scores (relevance) for the answers + >>> scores = np.asarray([[.1, .2, .3, 4, 70]]) + >>> ndcg_score(true_relevance, scores) + 0.69 + >>> scores = np.asarray([[.05, 1.1, 1., .5, .0]]) + >>> ndcg_score(true_relevance, scores) + 0.49 + >>> # we can set k to truncate the sum; only top k answers contribute. + >>> ndcg_score(true_relevance, scores, k=4) + 0.35 + >>> # the normalization takes k into account so a perfect answer + >>> # would still get 1.0 + >>> ndcg_score(true_relevance, true_relevance, k=4) + 1.0... + >>> # now we have some ties in our prediction + >>> scores = np.asarray([[1, 0, 0, 0, 1]]) + >>> # by default ties are averaged, so here we get the average (normalized) + >>> # true relevance of our top predictions: (10 / 10 + 5 / 10) / 2 = .75 + >>> ndcg_score(true_relevance, scores, k=1) + 0.75 + >>> # we can choose to ignore ties for faster results, but only + >>> # if we know there aren't ties in our scores, otherwise we get + >>> # wrong results: + >>> ndcg_score(true_relevance, + ... scores, k=1, ignore_ties=True) + 0.5... + """ + y_true = check_array(y_true, ensure_2d=False) + y_score = check_array(y_score, ensure_2d=False) + check_consistent_length(y_true, y_score, sample_weight) + + if y_true.min() < 0: + raise ValueError("ndcg_score should not be used on negative y_true values.") + if y_true.ndim > 1 and y_true.shape[1] <= 1: + raise ValueError( + "Computing NDCG is only meaningful when there is more than 1 document. " + f"Got {y_true.shape[1]} instead." + ) + _check_dcg_target_type(y_true) + gain = _ndcg_sample_scores(y_true, y_score, k=k, ignore_ties=ignore_ties) + return float(np.average(gain, weights=sample_weight)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_score": ["array-like"], + "k": [Interval(Integral, 1, None, closed="left")], + "normalize": ["boolean"], + "sample_weight": ["array-like", None], + "labels": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def top_k_accuracy_score( + y_true, y_score, *, k=2, normalize=True, sample_weight=None, labels=None +): + """Top-k Accuracy classification score. + + This metric computes the number of times where the correct label is among + the top `k` labels predicted (ranked by predicted scores). Note that the + multilabel case isn't covered here. + + Read more in the :ref:`User Guide ` + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + True labels. + + y_score : array-like of shape (n_samples,) or (n_samples, n_classes) + Target scores. These can be either probability estimates or + non-thresholded decision values (as returned by + :term:`decision_function` on some classifiers). + The binary case expects scores with shape (n_samples,) while the + multiclass case expects scores with shape (n_samples, n_classes). + In the multiclass case, the order of the class scores must + correspond to the order of ``labels``, if provided, or else to + the numerical or lexicographical order of the labels in ``y_true``. + If ``y_true`` does not contain all the labels, ``labels`` must be + provided. + + k : int, default=2 + Number of most likely outcomes considered to find the correct label. + + normalize : bool, default=True + If `True`, return the fraction of correctly classified samples. + Otherwise, return the number of correctly classified samples. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. If `None`, all samples are given the same weight. + + labels : array-like of shape (n_classes,), default=None + Multiclass only. List of labels that index the classes in ``y_score``. + If ``None``, the numerical or lexicographical order of the labels in + ``y_true`` is used. If ``y_true`` does not contain all the labels, + ``labels`` must be provided. + + Returns + ------- + score : float + The top-k accuracy score. The best performance is 1 with + `normalize == True` and the number of samples with + `normalize == False`. + + See Also + -------- + accuracy_score : Compute the accuracy score. By default, the function will + return the fraction of correct predictions divided by the total number + of predictions. + + Notes + ----- + In cases where two or more labels are assigned equal predicted scores, + the labels with the highest indices will be chosen first. This might + impact the result if the correct label falls after the threshold because + of that. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.metrics import top_k_accuracy_score + >>> y_true = np.array([0, 1, 2, 2]) + >>> y_score = np.array([[0.5, 0.2, 0.2], # 0 is in top 2 + ... [0.3, 0.4, 0.2], # 1 is in top 2 + ... [0.2, 0.4, 0.3], # 2 is in top 2 + ... [0.7, 0.2, 0.1]]) # 2 isn't in top 2 + >>> top_k_accuracy_score(y_true, y_score, k=2) + 0.75 + >>> # Not normalizing gives the number of "correctly" classified samples + >>> top_k_accuracy_score(y_true, y_score, k=2, normalize=False) + 3.0 + """ + y_true = check_array(y_true, ensure_2d=False, dtype=None) + y_true = column_or_1d(y_true) + y_type = type_of_target(y_true, input_name="y_true") + if y_type == "binary" and labels is not None and len(labels) > 2: + y_type = "multiclass" + if y_type not in {"binary", "multiclass"}: + raise ValueError( + f"y type must be 'binary' or 'multiclass', got '{y_type}' instead." + ) + y_score = check_array(y_score, ensure_2d=False) + if y_type == "binary": + if y_score.ndim == 2 and y_score.shape[1] != 1: + raise ValueError( + "`y_true` is binary while y_score is 2d with" + f" {y_score.shape[1]} classes. If `y_true` does not contain all the" + " labels, `labels` must be provided." + ) + y_score = column_or_1d(y_score) + + check_consistent_length(y_true, y_score, sample_weight) + y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2 + + if labels is None: + classes = _unique(y_true) + n_classes = len(classes) + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of classes in 'y_true' ({n_classes}) not equal " + f"to the number of classes in 'y_score' ({y_score_n_classes})." + "You can provide a list of all known classes by assigning it " + "to the `labels` parameter." + ) + else: + labels = column_or_1d(labels) + classes = _unique(labels) + n_labels = len(labels) + n_classes = len(classes) + + if n_classes != n_labels: + raise ValueError("Parameter 'labels' must be unique.") + + if not np.array_equal(classes, labels): + raise ValueError("Parameter 'labels' must be ordered.") + + if n_classes != y_score_n_classes: + raise ValueError( + f"Number of given labels ({n_classes}) not equal to the " + f"number of classes in 'y_score' ({y_score_n_classes})." + ) + + if len(np.setdiff1d(y_true, classes)): + raise ValueError("'y_true' contains labels not in parameter 'labels'.") + + if k >= n_classes: + warnings.warn( + ( + f"'k' ({k}) greater than or equal to 'n_classes' ({n_classes}) " + "will result in a perfect score and is therefore meaningless." + ), + UndefinedMetricWarning, + ) + + y_true_encoded = _encode(y_true, uniques=classes) + + if y_type == "binary": + if k == 1: + threshold = 0.5 if y_score.min() >= 0 and y_score.max() <= 1 else 0 + y_pred = (y_score > threshold).astype(np.int64) + hits = y_pred == y_true_encoded + else: + hits = np.ones_like(y_score, dtype=np.bool_) + elif y_type == "multiclass": + sorted_pred = np.argsort(y_score, axis=1, kind="mergesort")[:, ::-1] + hits = (y_true_encoded == sorted_pred[:, :k].T).any(axis=0) + + if normalize: + return float(np.average(hits, weights=sample_weight)) + elif sample_weight is None: + return float(np.sum(hits)) + else: + return float(np.dot(hits, sample_weight)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_regression.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..0731e00ce3a1ab24adb2e33ed17ac948455586e8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_regression.py @@ -0,0 +1,1930 @@ +"""Metrics to assess performance on regression task. + +Functions named as ``*_score`` return a scalar value to maximize: the higher +the better. + +Function named as ``*_error`` or ``*_loss`` return a scalar value to minimize: +the lower the better. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np + +from ..exceptions import UndefinedMetricWarning +from ..utils._array_api import ( + _average, + _find_matching_floating_dtype, + get_namespace, + get_namespace_and_device, + size, +) +from ..utils._array_api import ( + _xlogy as xlogy, +) +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.stats import _weighted_percentile +from ..utils.validation import ( + _check_sample_weight, + _num_samples, + check_array, + check_consistent_length, + column_or_1d, +) + +__ALL__ = [ + "max_error", + "mean_absolute_error", + "mean_squared_error", + "mean_squared_log_error", + "median_absolute_error", + "mean_absolute_percentage_error", + "mean_pinball_loss", + "r2_score", + "root_mean_squared_log_error", + "root_mean_squared_error", + "explained_variance_score", + "mean_tweedie_deviance", + "mean_poisson_deviance", + "mean_gamma_deviance", + "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", +] + + +def _check_reg_targets( + y_true, y_pred, sample_weight, multioutput, dtype="numeric", xp=None +): + """Check that y_true, y_pred and sample_weight belong to the same regression task. + + To reduce redundancy when calling `_find_matching_floating_dtype`, + please use `_check_reg_targets_with_floating_dtype` instead. + + 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,) or None + Sample weights. + + multioutput : array-like or string in ['raw_values', uniform_average', + 'variance_weighted'] or None + None is accepted due to backward compatibility of r2_score(). + + dtype : str or list, default="numeric" + the dtype argument passed to check_array. + + xp : module, default=None + Precomputed array namespace module. When passed, typically from a caller + that has already performed inspection of its own inputs, skips array + namespace inspection. + + Returns + ------- + type_true : one of {'continuous', continuous-multioutput'} + The type of the true target data, as output by + 'utils.multiclass.type_of_target'. + + y_true : array-like of shape (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,) or None + Sample weights. + + multioutput : array-like of shape (n_outputs) or string in ['raw_values', + uniform_average', 'variance_weighted'] or None + Custom output weights if ``multioutput`` is array-like or + just the corresponding argument if ``multioutput`` is a + correct keyword. + """ + xp, _ = get_namespace(y_true, y_pred, multioutput, xp=xp) + + check_consistent_length(y_true, y_pred, sample_weight) + y_true = check_array(y_true, ensure_2d=False, dtype=dtype) + y_pred = check_array(y_pred, ensure_2d=False, dtype=dtype) + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, y_true, dtype=dtype) + + if y_true.ndim == 1: + y_true = xp.reshape(y_true, (-1, 1)) + + if y_pred.ndim == 1: + y_pred = xp.reshape(y_pred, (-1, 1)) + + if y_true.shape[1] != y_pred.shape[1]: + raise ValueError( + "y_true and y_pred have different number of output ({0}!={1})".format( + y_true.shape[1], y_pred.shape[1] + ) + ) + + n_outputs = y_true.shape[1] + allowed_multioutput_str = ("raw_values", "uniform_average", "variance_weighted") + if isinstance(multioutput, str): + if multioutput not in allowed_multioutput_str: + raise ValueError( + "Allowed 'multioutput' string values are {}. " + "You provided multioutput={!r}".format( + allowed_multioutput_str, multioutput + ) + ) + elif multioutput is not None: + multioutput = check_array(multioutput, ensure_2d=False) + if n_outputs == 1: + raise ValueError("Custom weights are useful only in multi-output cases.") + elif n_outputs != multioutput.shape[0]: + raise ValueError( + "There must be equally many custom weights " + f"({multioutput.shape[0]}) as outputs ({n_outputs})." + ) + y_type = "continuous" if n_outputs == 1 else "continuous-multioutput" + + return y_type, y_true, y_pred, sample_weight, multioutput + + +def _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=None +): + """Ensures y_true, y_pred, and sample_weight correspond to same regression task. + + Extends `_check_reg_targets` by automatically selecting a suitable floating-point + data type for inputs using `_find_matching_floating_dtype`. + + Use this private method only when converting inputs to array API-compatibles. + + 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,) + + multioutput : array-like or string in ['raw_values', 'uniform_average', \ + 'variance_weighted'] or None + None is accepted due to backward compatibility of r2_score(). + + xp : module, default=None + Precomputed array namespace module. When passed, typically from a caller + that has already performed inspection of its own inputs, skips array + namespace inspection. + + Returns + ------- + type_true : one of {'continuous', 'continuous-multioutput'} + The type of the true target data, as output by + 'utils.multiclass.type_of_target'. + + y_true : array-like of shape (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : array-like of shape (n_outputs) or string in ['raw_values', \ + 'uniform_average', 'variance_weighted'] or None + Custom output weights if ``multioutput`` is array-like or + just the corresponding argument if ``multioutput`` is a + correct keyword. + """ + dtype_name = _find_matching_floating_dtype(y_true, y_pred, sample_weight, xp=xp) + + y_type, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput, dtype=dtype_name, xp=xp + ) + + return y_type, y_true, y_pred, sample_weight, multioutput + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_absolute_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute error regression loss. + + The mean absolute error is a non-negative floating point value, where best value + is 0.0. Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or array of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAE output is non-negative floating point. The best value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_error(y_true, y_pred) + 0.75 + >>> mean_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> mean_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85... + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + output_errors = _average( + xp.abs(y_pred - y_true), weights=sample_weight, axis=0, xp=xp + ) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_absolute_error = _average(output_errors, weights=multioutput) + + return float(mean_absolute_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "alpha": [Interval(Real, 0, 1, closed="both")], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_pinball_loss( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """Pinball loss for quantile regression. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha : float, slope of the pinball loss, default=0.5, + This loss is equivalent to :ref:`mean_absolute_error` when `alpha=0.5`, + `alpha=0.95` is minimized by estimators of the 95th percentile. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + The pinball loss output is a non-negative floating point. The best + value is 0.0. + + Examples + -------- + >>> from sklearn.metrics import mean_pinball_loss + >>> y_true = [1, 2, 3] + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.1) + 0.03... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.1) + 0.3... + >>> mean_pinball_loss(y_true, [0, 2, 3], alpha=0.9) + 0.3... + >>> mean_pinball_loss(y_true, [1, 2, 4], alpha=0.9) + 0.03... + >>> mean_pinball_loss(y_true, y_true, alpha=0.1) + 0.0 + >>> mean_pinball_loss(y_true, y_true, alpha=0.9) + 0.0 + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + diff = y_true - y_pred + sign = xp.astype(diff >= 0, diff.dtype) + loss = alpha * sign * diff - (1 - alpha) * (1 - sign) * diff + output_errors = _average(loss, weights=sample_weight, axis=0) + + if isinstance(multioutput, str) and multioutput == "raw_values": + return output_errors + + if isinstance(multioutput, str) and multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + return float(_average(output_errors, weights=multioutput)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_absolute_percentage_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Mean absolute percentage error (MAPE) regression loss. + + Note that we are not using the common "percentage" definition: the percentage + in the range [0, 100] is converted to a relative value in the range [0, 1] + by dividing by 100. Thus, an error of 200% corresponds to a relative error of 2. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.24 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + If input is list then the shape must be (n_outputs,). + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute percentage error + is returned for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + MAPE output is non-negative floating point. The best value is 0.0. + But note that bad predictions can lead to arbitrarily large + MAPE values, especially if some `y_true` values are very close to zero. + Note that we return a large value instead of `inf` when `y_true` is zero. + + Examples + -------- + >>> from sklearn.metrics import mean_absolute_percentage_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.3273... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> mean_absolute_percentage_error(y_true, y_pred) + 0.5515... + >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.6198... + >>> # the value when some element of the y_true is zero is arbitrarily high because + >>> # of the division by epsilon + >>> y_true = [1., 0., 2.4, 7.] + >>> y_pred = [1.2, 0.1, 2.4, 8.] + >>> mean_absolute_percentage_error(y_true, y_pred) + 112589990684262.48 + """ + xp, _, device_ = get_namespace_and_device( + y_true, y_pred, sample_weight, multioutput + ) + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + epsilon = xp.asarray(xp.finfo(xp.float64).eps, dtype=y_true.dtype, device=device_) + y_true_abs = xp.abs(y_true) + mape = xp.abs(y_pred - y_true) / xp.maximum(y_true_abs, epsilon) + output_errors = _average(mape, weights=sample_weight, axis=0) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_absolute_percentage_error = _average(output_errors, weights=multioutput) + + return float(mean_absolute_percentage_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_squared_error( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", +): + """Mean squared error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or array of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> mean_squared_error(y_true, y_pred) + 0.375 + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> mean_squared_error(y_true, y_pred) + 0.708... + >>> mean_squared_error(y_true, y_pred, multioutput='raw_values') + array([0.41666667, 1. ]) + >>> mean_squared_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.825... + """ + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + output_errors = _average((y_true - y_pred) ** 2, axis=0, weights=sample_weight) + + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + mean_squared_error = _average(output_errors, weights=multioutput) + + return float(mean_squared_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def root_mean_squared_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Root mean squared error regression loss. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.4 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import root_mean_squared_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> root_mean_squared_error(y_true, y_pred) + 0.612... + >>> y_true = [[0.5, 1],[-1, 1],[7, -6]] + >>> y_pred = [[0, 2],[-1, 2],[8, -5]] + >>> root_mean_squared_error(y_true, y_pred) + 0.822... + """ + + xp, _ = get_namespace(y_true, y_pred, sample_weight, multioutput) + + output_errors = xp.sqrt( + mean_squared_error( + y_true, y_pred, sample_weight=sample_weight, multioutput="raw_values" + ) + ) + + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to _average: uniform mean + multioutput = None + + # Average across the outputs (if needed). + # The second call to `_average` should always return + # a scalar array that we convert to a Python float to + # consistently return the same eager evaluated value. + # Therefore, `axis=None`. + root_mean_squared_error = _average(output_errors, weights=multioutput) + + return float(root_mean_squared_error) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def mean_squared_log_error( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", +): + """Mean squared logarithmic error regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors when the input is of multioutput + format. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import mean_squared_log_error + >>> y_true = [3, 5, 2.5, 7] + >>> y_pred = [2.5, 5, 4, 8] + >>> mean_squared_log_error(y_true, y_pred) + 0.039... + >>> y_true = [[0.5, 1], [1, 2], [7, 6]] + >>> y_pred = [[0.5, 2], [1, 2.5], [8, 8]] + >>> mean_squared_log_error(y_true, y_pred) + 0.044... + >>> mean_squared_log_error(y_true, y_pred, multioutput='raw_values') + array([0.00462428, 0.08377444]) + >>> mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.060... + """ + xp, _ = get_namespace(y_true, y_pred) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if xp.any(y_true <= -1) or xp.any(y_pred <= -1): + raise ValueError( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + return mean_squared_error( + xp.log1p(y_true), + xp.log1p(y_pred), + sample_weight=sample_weight, + multioutput=multioutput, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + }, + prefer_skip_nested_validation=True, +) +def root_mean_squared_log_error( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """Root mean squared logarithmic error regression loss. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.4 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + + Defines aggregating of multiple output values. + Array-like value defines weights used to average errors. + + 'raw_values' : + Returns a full set of errors when the input is of multioutput + format. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + Returns + ------- + loss : float or ndarray of floats + A non-negative floating point value (the best value is 0.0), or an + array of floating point values, one for each individual target. + + Examples + -------- + >>> from sklearn.metrics import root_mean_squared_log_error + >>> y_true = [3, 5, 2.5, 7] + >>> y_pred = [2.5, 5, 4, 8] + >>> root_mean_squared_log_error(y_true, y_pred) + 0.199... + """ + xp, _ = get_namespace(y_true, y_pred) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if xp.any(y_true <= -1) or xp.any(y_pred <= -1): + raise ValueError( + "Root Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + return root_mean_squared_error( + xp.log1p(y_true), + xp.log1p(y_pred), + sample_weight=sample_weight, + multioutput=multioutput, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "multioutput": [StrOptions({"raw_values", "uniform_average"}), "array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def median_absolute_error( + y_true, y_pred, *, multioutput="uniform_average", sample_weight=None +): + """Median absolute error regression loss. + + Median absolute error output is non-negative floating point. The best value + is 0.0. Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. Array-like value defines + weights used to average errors. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Errors of all outputs are averaged with uniform weight. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 0.24 + + Returns + ------- + loss : float or ndarray of floats + If multioutput is 'raw_values', then mean absolute error is returned + for each output separately. + If multioutput is 'uniform_average' or an ndarray of weights, then the + weighted average of all output errors is returned. + + Examples + -------- + >>> from sklearn.metrics import median_absolute_error + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> median_absolute_error(y_true, y_pred) + 0.5 + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> median_absolute_error(y_true, y_pred) + 0.75 + >>> median_absolute_error(y_true, y_pred, multioutput='raw_values') + array([0.5, 1. ]) + >>> median_absolute_error(y_true, y_pred, multioutput=[0.3, 0.7]) + 0.85 + """ + _, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput + ) + if sample_weight is None: + output_errors = np.median(np.abs(y_pred - y_true), axis=0) + else: + output_errors = _weighted_percentile( + np.abs(y_pred - y_true), sample_weight=sample_weight + ) + if isinstance(multioutput, str): + if multioutput == "raw_values": + return output_errors + elif multioutput == "uniform_average": + # pass None as weights to np.average: uniform mean + multioutput = None + + return float(np.average(output_errors, weights=multioutput)) + + +def _assemble_r2_explained_variance( + numerator, denominator, n_outputs, multioutput, force_finite, xp, device +): + """Common part used by explained variance score and :math:`R^2` score.""" + dtype = numerator.dtype + + 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 = xp.ones([n_outputs], device=device, dtype=dtype) + # 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": + # pass None as weights to _average: uniform mean + avg_weights = None + elif multioutput == "variance_weighted": + avg_weights = denominator + if not xp.any(nonzero_denominator): + # All weights are zero, _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 + + result = _average(output_scores, weights=avg_weights) + if size(result) == 1: + return float(result) + return result + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average", "variance_weighted"}), + "array-like", + ], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def explained_variance_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """Explained variance regression score function. + + Best possible score is 1.0, lower values are worse. + + In the particular case when ``y_true`` is constant, the explained variance + score is not finite: it is either ``NaN`` (perfect predictions) or + ``-Inf`` (imperfect predictions). To prevent such non-finite numbers to + pollute higher-level experiments such as a grid search cross-validation, + by default these cases are replaced with 1.0 (perfect predictions) or 0.0 + (imperfect predictions) respectively. If ``force_finite`` + is set to ``False``, this score falls back on the original :math:`R^2` + definition. + + .. note:: + The Explained Variance score is similar to the + :func:`R^2 score `, with the notable difference that it + does not account for systematic offsets in the prediction. Most often + the :func:`R^2 score ` should be preferred. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'} or \ + array-like of shape (n_outputs,), default='uniform_average' + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + score : float or ndarray of floats + The explained variance or ndarray if 'multioutput' is 'raw_values'. + + See Also + -------- + r2_score : + Similar metric, but accounting for systematic offsets in + prediction. + + Notes + ----- + This is not a symmetric function. + + Examples + -------- + >>> from sklearn.metrics import explained_variance_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> explained_variance_score(y_true, y_pred) + 0.957... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> explained_variance_score(y_true, y_pred, multioutput='uniform_average') + 0.983... + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> explained_variance_score(y_true, y_pred) + 1.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> explained_variance_score(y_true, y_pred) + 0.0 + >>> explained_variance_score(y_true, y_pred, force_finite=False) + -inf + """ + xp, _, device = get_namespace_and_device(y_true, y_pred, sample_weight, multioutput) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + y_diff_avg = _average(y_true - y_pred, weights=sample_weight, axis=0) + numerator = _average( + (y_true - y_pred - y_diff_avg) ** 2, weights=sample_weight, axis=0 + ) + + y_true_avg = _average(y_true, weights=sample_weight, axis=0) + denominator = _average((y_true - y_true_avg) ** 2, weights=sample_weight, axis=0) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + xp=xp, + device=device, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average", "variance_weighted"}), + "array-like", + None, + ], + "force_finite": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def r2_score( + y_true, + y_pred, + *, + sample_weight=None, + multioutput="uniform_average", + force_finite=True, +): + """:math:`R^2` (coefficient of determination) regression score function. + + Best possible score is 1.0 and it can be negative (because the + model can be arbitrarily worse). In the general case when the true y is + non-constant, a constant model that always predicts the average y + disregarding the input features would get a :math:`R^2` score of 0.0. + + In the particular case when ``y_true`` is constant, the :math:`R^2` score + is not finite: it is either ``NaN`` (perfect predictions) or ``-Inf`` + (imperfect predictions). To prevent such non-finite numbers to pollute + higher-level experiments such as a grid search cross-validation, by default + these cases are replaced with 1.0 (perfect predictions) or 0.0 (imperfect + predictions) respectively. You can set ``force_finite`` to ``False`` to + prevent this fix from happening. + + Note: when the prediction residuals have zero mean, the :math:`R^2` score + is identical to the + :func:`Explained Variance score `. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average', 'variance_weighted'}, \ + array-like of shape (n_outputs,) or None, default='uniform_average' + + Defines aggregating of multiple output scores. + Array-like value defines weights used to average scores. + Default is "uniform_average". + + 'raw_values' : + Returns a full set of scores in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + 'variance_weighted' : + Scores of all outputs are averaged, weighted by the variances + of each individual output. + + .. versionchanged:: 0.19 + Default value of multioutput is 'uniform_average'. + + force_finite : bool, default=True + Flag indicating if ``NaN`` and ``-Inf`` scores resulting from constant + data should be replaced with real numbers (``1.0`` if prediction is + perfect, ``0.0`` otherwise). Default is ``True``, a convenient setting + for hyperparameters' search procedures (e.g. grid search + cross-validation). + + .. versionadded:: 1.1 + + Returns + ------- + z : float or ndarray of floats + The :math:`R^2` score or ndarray of scores if 'multioutput' is + 'raw_values'. + + Notes + ----- + This is not a symmetric function. + + Unlike most other scores, :math:`R^2` score may be negative (it need not + actually be the square of a quantity R). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] `Wikipedia entry on the Coefficient of determination + `_ + + Examples + -------- + >>> from sklearn.metrics import r2_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> r2_score(y_true, y_pred) + 0.948... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> r2_score(y_true, y_pred, + ... multioutput='variance_weighted') + 0.938... + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> r2_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> r2_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> r2_score(y_true, y_pred) + -3.0 + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2] + >>> r2_score(y_true, y_pred) + 1.0 + >>> r2_score(y_true, y_pred, force_finite=False) + nan + >>> y_true = [-2, -2, -2] + >>> y_pred = [-2, -2, -2 + 1e-8] + >>> r2_score(y_true, y_pred) + 0.0 + >>> r2_score(y_true, y_pred, force_finite=False) + -inf + """ + xp, _, device_ = get_namespace_and_device( + y_true, y_pred, sample_weight, multioutput + ) + + _, y_true, y_pred, sample_weight, multioutput = ( + _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput, xp=xp + ) + ) + + if _num_samples(y_pred) < 2: + msg = "R^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + weight = sample_weight[:, None] + else: + weight = 1.0 + + numerator = xp.sum(weight * (y_true - y_pred) ** 2, axis=0) + denominator = xp.sum( + weight * (y_true - _average(y_true, axis=0, weights=sample_weight, xp=xp)) ** 2, + axis=0, + ) + + return _assemble_r2_explained_variance( + numerator=numerator, + denominator=denominator, + n_outputs=y_true.shape[1], + multioutput=multioutput, + force_finite=force_finite, + xp=xp, + device=device_, + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def max_error(y_true, y_pred): + """ + The max_error metric calculates the maximum residual error. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + Returns + ------- + max_error : float + A positive floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import max_error + >>> y_true = [3, 2, 7, 1] + >>> y_pred = [4, 2, 7, 1] + >>> max_error(y_true, y_pred) + 1.0 + """ + xp, _ = get_namespace(y_true, y_pred) + y_type, y_true, y_pred, _, _ = _check_reg_targets( + y_true, y_pred, sample_weight=None, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in max_error") + return float(xp.max(xp.abs(y_true - y_pred))) + + +def _mean_tweedie_deviance(y_true, y_pred, sample_weight, power): + """Mean Tweedie deviance regression loss.""" + xp, _, device_ = get_namespace_and_device(y_true, y_pred) + p = power + if p < 0: + # 'Extreme stable', y any real number, y_pred > 0 + dev = 2 * ( + xp.pow( + xp.where(y_true > 0, y_true, 0.0), + 2 - p, + ) + / ((1 - p) * (2 - p)) + - y_true * xp.pow(y_pred, 1 - p) / (1 - p) + + xp.pow(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 * (xp.log(y_pred / y_true) + y_true / y_pred - 1) + else: + dev = 2 * ( + xp.pow(y_true, 2 - p) / ((1 - p) * (2 - p)) + - y_true * xp.pow(y_pred, 1 - p) / (1 - p) + + xp.pow(y_pred, 2 - p) / (2 - p) + ) + return float(_average(dev, weights=sample_weight)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "power": [ + Interval(Real, None, 0, closed="right"), + Interval(Real, 1, None, closed="left"), + ], + }, + prefer_skip_nested_validation=True, +) +def mean_tweedie_deviance(y_true, y_pred, *, sample_weight=None, power=0): + """Mean Tweedie deviance regression loss. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to + mean_squared_error. y_true and y_pred can be any real numbers. + - power = 1 : Poisson distribution. Requires: y_true >= 0 and + y_pred > 0. + - 1 < p < 2 : Compound Poisson distribution. Requires: y_true >= 0 + and y_pred > 0. + - power = 2 : Gamma distribution. Requires: y_true > 0 and y_pred > 0. + - power = 3 : Inverse Gaussian distribution. Requires: y_true > 0 + and y_pred > 0. + - otherwise : Positive stable distribution. Requires: y_true > 0 + and y_pred > 0. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_tweedie_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_tweedie_deviance(y_true, y_pred, power=1) + 1.4260... + """ + xp, _ = get_namespace(y_true, y_pred) + y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in mean_tweedie_deviance") + + if sample_weight is not None: + sample_weight = column_or_1d(sample_weight) + sample_weight = sample_weight[:, np.newaxis] + + message = f"Mean Tweedie deviance error with power={power} can only be used on " + if power < 0: + # 'Extreme stable', y any real number, y_pred > 0 + if xp.any(y_pred <= 0): + raise ValueError(message + "strictly positive y_pred.") + elif power == 0: + # Normal, y and y_pred can be any real number + pass + elif 1 <= power < 2: + # Poisson and compound Poisson distribution, y >= 0, y_pred > 0 + if xp.any(y_true < 0) or xp.any(y_pred <= 0): + raise ValueError(message + "non-negative y and strictly positive y_pred.") + elif power >= 2: + # Gamma and Extreme stable distribution, y and y_pred > 0 + if xp.any(y_true <= 0) or xp.any(y_pred <= 0): + 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 + ) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def mean_poisson_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Poisson deviance regression loss. + + Poisson deviance is equivalent to the Tweedie deviance with + the power parameter `power=1`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true >= 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_poisson_deviance + >>> y_true = [2, 0, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_poisson_deviance(y_true, y_pred) + 1.4260... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=1) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def mean_gamma_deviance(y_true, y_pred, *, sample_weight=None): + """Mean Gamma deviance regression loss. + + Gamma deviance is equivalent to the Tweedie deviance with + the power parameter `power=2`. It is invariant to scaling of + the target variable, and measures relative errors. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. Requires y_true > 0. + + y_pred : array-like of shape (n_samples,) + Estimated target values. Requires y_pred > 0. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + loss : float + A non-negative floating point value (the best value is 0.0). + + Examples + -------- + >>> from sklearn.metrics import mean_gamma_deviance + >>> y_true = [2, 0.5, 1, 4] + >>> y_pred = [0.5, 0.5, 2., 2.] + >>> mean_gamma_deviance(y_true, y_pred) + 1.0568... + """ + return mean_tweedie_deviance(y_true, y_pred, sample_weight=sample_weight, power=2) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "power": [ + Interval(Real, None, 0, closed="right"), + Interval(Real, 1, None, closed="left"), + ], + }, + prefer_skip_nested_validation=True, +) +def d2_tweedie_score(y_true, y_pred, *, sample_weight=None, power=0): + """ + :math:`D^2` regression score function, fraction of Tweedie deviance explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical mean of `y_true` as + constant prediction, disregarding the input features, gets a D^2 score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.0 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + power : float, default=0 + Tweedie power parameter. Either power <= 0 or power >= 1. + + The higher `p` the less weight is given to extreme + deviations between true and predicted targets. + + - power < 0: Extreme stable distribution. Requires: y_pred > 0. + - power = 0 : Normal distribution, output corresponds to 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 + The D^2 score. + + Notes + ----- + This is not a symmetric function. + + Like R^2, D^2 score may be negative (it need not actually be the square of + a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_tweedie_score + >>> y_true = [0.5, 1, 2.5, 7] + >>> y_pred = [1, 1, 5, 3.5] + >>> d2_tweedie_score(y_true, y_pred) + 0.285... + >>> d2_tweedie_score(y_true, y_pred, power=1) + 0.487... + >>> d2_tweedie_score(y_true, y_pred, power=2) + 0.630... + >>> d2_tweedie_score(y_true, y_true, power=2) + 1.0 + """ + xp, _ = get_namespace(y_true, y_pred) + + y_type, y_true, y_pred, sample_weight, _ = _check_reg_targets_with_floating_dtype( + y_true, y_pred, sample_weight, multioutput=None, xp=xp + ) + if y_type == "continuous-multioutput": + raise ValueError("Multioutput not supported in d2_tweedie_score") + + if _num_samples(y_pred) < 2: + msg = "D^2 score is not well-defined with less than two samples." + warnings.warn(msg, UndefinedMetricWarning) + return float("nan") + + y_true, y_pred = xp.squeeze(y_true, axis=1), xp.squeeze(y_pred, axis=1) + numerator = mean_tweedie_deviance( + y_true, y_pred, sample_weight=sample_weight, power=power + ) + + y_avg = _average(y_true, weights=sample_weight, xp=xp) + denominator = _mean_tweedie_deviance( + y_true, y_avg, sample_weight=sample_weight, power=power + ) + + return 1 - numerator / denominator + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "alpha": [Interval(Real, 0, 1, closed="both")], + "multioutput": [ + StrOptions({"raw_values", "uniform_average"}), + "array-like", + ], + }, + prefer_skip_nested_validation=True, +) +def d2_pinball_score( + y_true, y_pred, *, sample_weight=None, alpha=0.5, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of pinball loss explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical alpha-quantile of + `y_true` as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + alpha : float, default=0.5 + Slope of the pinball deviance. It determines the quantile level alpha + for which the pinball deviance and also D2 are optimal. + The default `alpha=0.5` is equivalent to `d2_absolute_error_score`. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with a pinball deviance + or ndarray of scores if `multioutput='raw_values'`. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for a single point and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (7) of `Koenker, Roger; Machado, José A. F. (1999). + "Goodness of Fit and Related Inference Processes for Quantile Regression" + `_ + .. [2] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_pinball_score + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 3, 3] + >>> d2_pinball_score(y_true, y_pred) + 0.5 + >>> d2_pinball_score(y_true, y_pred, alpha=0.9) + 0.772... + >>> d2_pinball_score(y_true, y_pred, alpha=0.1) + -1.045... + >>> d2_pinball_score(y_true, y_true, alpha=0.1) + 1.0 + """ + _, y_true, y_pred, sample_weight, multioutput = _check_reg_targets( + y_true, y_pred, sample_weight, multioutput + ) + + 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: + y_quantile = np.tile( + _weighted_percentile( + y_true, sample_weight=sample_weight, percentile_rank=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 + else: # multioutput == "uniform_average" + # passing None as weights to np.average results in uniform mean + avg_weights = None + else: + avg_weights = multioutput + + return float(np.average(output_scores, weights=avg_weights)) + + +@validate_params( + { + "y_true": ["array-like"], + "y_pred": ["array-like"], + "sample_weight": ["array-like", None], + "multioutput": [ + StrOptions({"raw_values", "uniform_average"}), + "array-like", + ], + }, + prefer_skip_nested_validation=True, +) +def d2_absolute_error_score( + y_true, y_pred, *, sample_weight=None, multioutput="uniform_average" +): + """ + :math:`D^2` regression score function, fraction of absolute error explained. + + Best possible score is 1.0 and it can be negative (because the model can be + arbitrarily worse). A model that always uses the empirical median of `y_true` + as constant prediction, disregarding the input features, + gets a :math:`D^2` score of 0.0. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.1 + + Parameters + ---------- + y_true : array-like of shape (n_samples,) or (n_samples, n_outputs) + Ground truth (correct) target values. + + y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs) + Estimated target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + multioutput : {'raw_values', 'uniform_average'} or array-like of shape \ + (n_outputs,), default='uniform_average' + Defines aggregating of multiple output values. + Array-like value defines weights used to average scores. + + 'raw_values' : + Returns a full set of errors in case of multioutput input. + + 'uniform_average' : + Scores of all outputs are averaged with uniform weight. + + Returns + ------- + score : float or ndarray of floats + The :math:`D^2` score with an absolute error deviance + or ndarray of scores if 'multioutput' is 'raw_values'. + + Notes + ----- + Like :math:`R^2`, :math:`D^2` score may be negative + (it need not actually be the square of a quantity D). + + This metric is not well-defined for single samples and will return a NaN + value if n_samples is less than two. + + References + ---------- + .. [1] Eq. (3.11) of Hastie, Trevor J., Robert Tibshirani and Martin J. + Wainwright. "Statistical Learning with Sparsity: The Lasso and + Generalizations." (2015). https://hastie.su.domains/StatLearnSparsity/ + + Examples + -------- + >>> from sklearn.metrics import d2_absolute_error_score + >>> y_true = [3, -0.5, 2, 7] + >>> y_pred = [2.5, 0.0, 2, 8] + >>> d2_absolute_error_score(y_true, y_pred) + 0.764... + >>> y_true = [[0.5, 1], [-1, 1], [7, -6]] + >>> y_pred = [[0, 2], [-1, 2], [8, -5]] + >>> d2_absolute_error_score(y_true, y_pred, multioutput='uniform_average') + 0.691... + >>> d2_absolute_error_score(y_true, y_pred, multioutput='raw_values') + array([0.8125 , 0.57142857]) + >>> y_true = [1, 2, 3] + >>> y_pred = [1, 2, 3] + >>> d2_absolute_error_score(y_true, y_pred) + 1.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [2, 2, 2] + >>> d2_absolute_error_score(y_true, y_pred) + 0.0 + >>> y_true = [1, 2, 3] + >>> y_pred = [3, 2, 1] + >>> d2_absolute_error_score(y_true, y_pred) + -1.0 + """ + return d2_pinball_score( + y_true, y_pred, sample_weight=sample_weight, alpha=0.5, multioutput=multioutput + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_scorer.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_scorer.py new file mode 100644 index 0000000000000000000000000000000000000000..08e5a20187de7f5c15985ed337603f442bda9fec --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/_scorer.py @@ -0,0 +1,1166 @@ +""" +The :mod:`sklearn.metrics.scorer` submodule implements a flexible +interface for model selection and evaluation using +arbitrary score functions. + +A scorer object is a callable that can be passed to +:class:`~sklearn.model_selection.GridSearchCV` or +:func:`sklearn.model_selection.cross_val_score` as the ``scoring`` +parameter, to specify how a model should be evaluated. + +The signature of the call is ``(estimator, X, y)`` where ``estimator`` +is the model to be evaluated, ``X`` is the test data and ``y`` is the +ground truth labeling (or ``None`` in the case of unsupervised models). +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import copy +import warnings +from collections import Counter +from functools import partial +from inspect import signature +from numbers import Integral +from traceback import format_exc + +import numpy as np + +from ..base import is_regressor +from ..utils import Bunch +from ..utils._param_validation import HasMethods, Hidden, StrOptions, validate_params +from ..utils._response import _get_response_values +from ..utils.metadata_routing import ( + MetadataRequest, + MetadataRouter, + MethodMapping, + _MetadataRequester, + _raise_for_params, + _routing_enabled, + get_routing_for_object, + process_routing, +) +from ..utils.validation import _check_response_method +from . import ( + accuracy_score, + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + class_likelihood_ratios, + d2_absolute_error_score, + explained_variance_score, + f1_score, + jaccard_score, + log_loss, + matthews_corrcoef, + max_error, + mean_absolute_error, + mean_absolute_percentage_error, + mean_gamma_deviance, + mean_poisson_deviance, + mean_squared_error, + mean_squared_log_error, + median_absolute_error, + precision_score, + r2_score, + recall_score, + roc_auc_score, + root_mean_squared_error, + root_mean_squared_log_error, + top_k_accuracy_score, +) +from .cluster import ( + adjusted_mutual_info_score, + adjusted_rand_score, + completeness_score, + fowlkes_mallows_score, + homogeneity_score, + mutual_info_score, + normalized_mutual_info_score, + rand_score, + v_measure_score, +) + + +def _cached_call(cache, estimator, response_method, *args, **kwargs): + """Call estimator with method and args and kwargs.""" + if cache is not None and response_method in cache: + return cache[response_method] + + result, _ = _get_response_values( + estimator, *args, response_method=response_method, **kwargs + ) + + if cache is not None: + cache[response_method] = result + + return result + + +class _MultimetricScorer: + """Callable for multimetric scoring used to avoid repeated calls + to `predict_proba`, `predict`, and `decision_function`. + + `_MultimetricScorer` will return a dictionary of scores corresponding to + the scorers in the dictionary. Note that `_MultimetricScorer` can be + created with a dictionary with one key (i.e. only one actual scorer). + + Parameters + ---------- + scorers : dict + Dictionary mapping names to callable scorers. + + raise_exc : bool, default=True + Whether to raise the exception in `__call__` or not. If set to `False` + a formatted string of the exception details is passed as result of + the failing scorer. + """ + + def __init__(self, *, scorers, raise_exc=True): + self._scorers = scorers + self._raise_exc = raise_exc + + def __call__(self, estimator, *args, **kwargs): + """Evaluate predicted target values.""" + scores = {} + cache = {} if self._use_cache(estimator) else None + cached_call = partial(_cached_call, cache) + + if _routing_enabled(): + routed_params = process_routing(self, "score", **kwargs) + else: + # Scorers all get the same args, and get all of them except sample_weight. + # Only the ones having `sample_weight` in their signature will receive it. + # This does not work for metadata other than sample_weight, and for those + # users have to enable metadata routing. + common_kwargs = { + arg: value for arg, value in kwargs.items() if arg != "sample_weight" + } + routed_params = Bunch( + **{name: Bunch(score=common_kwargs.copy()) for name in self._scorers} + ) + if "sample_weight" in kwargs: + for name, scorer in self._scorers.items(): + if scorer._accept_sample_weight(): + routed_params[name].score["sample_weight"] = kwargs[ + "sample_weight" + ] + + for name, scorer in self._scorers.items(): + try: + if isinstance(scorer, _BaseScorer): + score = scorer._score( + cached_call, estimator, *args, **routed_params.get(name).score + ) + else: + score = scorer(estimator, *args, **routed_params.get(name).score) + scores[name] = score + except Exception as e: + if self._raise_exc: + raise e + else: + scores[name] = format_exc() + return scores + + def __repr__(self): + scorers = ", ".join([f'"{s}"' for s in self._scorers]) + return f"MultiMetricScorer({scorers})" + + def _accept_sample_weight(self): + # TODO(slep006): remove when metadata routing is the only way + return any(scorer._accept_sample_weight() for scorer in self._scorers.values()) + + def _use_cache(self, estimator): + """Return True if using a cache is beneficial, thus when a response method will + be called several time. + """ + if len(self._scorers) == 1: # Only one scorer + return False + + counter = Counter( + [ + _check_response_method(estimator, scorer._response_method).__name__ + for scorer in self._scorers.values() + if isinstance(scorer, _BaseScorer) + ] + ) + if any(val > 1 for val in counter.values()): + # The exact same response method or iterable of response methods + # will be called more than once. + return True + + return False + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.3 + + Returns + ------- + routing : MetadataRouter + A :class:`~utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + return MetadataRouter(owner=self.__class__.__name__).add( + **self._scorers, + method_mapping=MethodMapping().add(caller="score", callee="score"), + ) + + +class _BaseScorer(_MetadataRequester): + """Base scorer that is used as `scorer(estimator, X, y_true)`. + + Parameters + ---------- + score_func : callable + The score function to use. It will be called as + `score_func(y_true, y_pred, **kwargs)`. + + sign : int + Either 1 or -1 to returns the score with `sign * score_func(estimator, X, y)`. + Thus, `sign` defined if higher scores are better or worse. + + kwargs : dict + Additional parameters to pass to the score function. + + response_method : str + The method to call on the estimator to get the response values. + """ + + def __init__(self, score_func, sign, kwargs, response_method="predict"): + self._score_func = score_func + self._sign = sign + self._kwargs = kwargs + self._response_method = response_method + # TODO (1.8): remove in 1.8 (scoring="max_error" has been deprecated in 1.6) + self._deprecation_msg = None + + def _get_pos_label(self): + if "pos_label" in self._kwargs: + return self._kwargs["pos_label"] + score_func_params = signature(self._score_func).parameters + if "pos_label" in score_func_params: + return score_func_params["pos_label"].default + return None + + def _accept_sample_weight(self): + # TODO(slep006): remove when metadata routing is the only way + return "sample_weight" in signature(self._score_func).parameters + + def __repr__(self): + sign_string = "" if self._sign > 0 else ", greater_is_better=False" + response_method_string = f", response_method={self._response_method!r}" + kwargs_string = "".join([f", {k}={v}" for k, v in self._kwargs.items()]) + + return ( + f"make_scorer({self._score_func.__name__}{sign_string}" + f"{response_method_string}{kwargs_string})" + ) + + def __call__(self, estimator, X, y_true, sample_weight=None, **kwargs): + """Evaluate predicted target values for X relative to y_true. + + Parameters + ---------- + estimator : object + Trained estimator to use for scoring. Must have a predict_proba + method; the output of that is used to compute the score. + + X : {array-like, sparse matrix} + Test data that will be fed to estimator.predict. + + y_true : array-like + Gold standard target values for X. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + **kwargs : dict + Other parameters passed to the scorer. Refer to + :func:`set_score_request` for more details. + + Only available if `enable_metadata_routing=True`. See the + :ref:`User Guide `. + + .. versionadded:: 1.3 + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + # TODO (1.8): remove in 1.8 (scoring="max_error" has been deprecated in 1.6) + if self._deprecation_msg is not None: + warnings.warn( + self._deprecation_msg, category=DeprecationWarning, stacklevel=2 + ) + + _raise_for_params(kwargs, self, None) + + _kwargs = copy.deepcopy(kwargs) + if sample_weight is not None: + _kwargs["sample_weight"] = sample_weight + + return self._score(partial(_cached_call, None), estimator, X, y_true, **_kwargs) + + def _warn_overlap(self, message, kwargs): + """Warn if there is any overlap between ``self._kwargs`` and ``kwargs``. + + This method is intended to be used to check for overlap between + ``self._kwargs`` and ``kwargs`` passed as metadata. + """ + _kwargs = set() if self._kwargs is None else set(self._kwargs.keys()) + overlap = _kwargs.intersection(kwargs.keys()) + if overlap: + warnings.warn( + f"{message} Overlapping parameters are: {overlap}", UserWarning + ) + + def set_score_request(self, **kwargs): + """Set requested parameters by the scorer. + + Please see :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.3 + + Parameters + ---------- + kwargs : dict + Arguments should be of the form ``param_name=alias``, and `alias` + can be one of ``{True, False, None, str}``. + """ + if not _routing_enabled(): + raise RuntimeError( + "This method is only available when metadata routing is enabled." + " You can enable it using" + " sklearn.set_config(enable_metadata_routing=True)." + ) + + self._warn_overlap( + message=( + "You are setting metadata request for parameters which are " + "already set as kwargs for this metric. These set values will be " + "overridden by passed metadata if provided. Please pass them either " + "as metadata or kwargs to `make_scorer`." + ), + kwargs=kwargs, + ) + self._metadata_request = MetadataRequest(owner=self.__class__.__name__) + for param, alias in kwargs.items(): + self._metadata_request.score.add_request(param=param, alias=alias) + return self + + +class _Scorer(_BaseScorer): + def _score(self, method_caller, estimator, X, y_true, **kwargs): + """Evaluate the response method of `estimator` on `X` and `y_true`. + + Parameters + ---------- + method_caller : callable + Returns predictions given an estimator, method name, and other + arguments, potentially caching results. + + estimator : object + Trained estimator to use for scoring. + + X : {array-like, sparse matrix} + Test data that will be fed to clf.decision_function or + clf.predict_proba. + + y_true : array-like + Gold standard target values for X. These must be class labels, + not decision function values. + + **kwargs : dict + Other parameters passed to the scorer. Refer to + :func:`set_score_request` for more details. + + Returns + ------- + score : float + Score function applied to prediction of estimator on X. + """ + self._warn_overlap( + message=( + "There is an overlap between set kwargs of this scorer instance and" + " passed metadata. Please pass them either as kwargs to `make_scorer`" + " or metadata, but not both." + ), + kwargs=kwargs, + ) + + pos_label = None if is_regressor(estimator) else self._get_pos_label() + response_method = _check_response_method(estimator, self._response_method) + y_pred = method_caller( + estimator, + _get_response_method_name(response_method), + X, + pos_label=pos_label, + ) + + scoring_kwargs = {**self._kwargs, **kwargs} + return self._sign * self._score_func(y_true, y_pred, **scoring_kwargs) + + +@validate_params( + { + "scoring": [str, callable, None], + }, + prefer_skip_nested_validation=True, +) +def get_scorer(scoring): + """Get a scorer from string. + + Read more in the :ref:`User Guide `. + :func:`~sklearn.metrics.get_scorer_names` can be used to retrieve the names + of all available scorers. + + Parameters + ---------- + scoring : str, callable or None + Scoring method as string. If callable it is returned as is. + If None, returns None. + + Returns + ------- + scorer : callable + The scorer. + + Notes + ----- + When passed a string, this function always returns a copy of the scorer + object. Calling `get_scorer` twice for the same scorer results in two + separate scorer objects. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.dummy import DummyClassifier + >>> from sklearn.metrics import get_scorer + >>> X = np.reshape([0, 1, -1, -0.5, 2], (-1, 1)) + >>> y = np.array([0, 1, 1, 0, 1]) + >>> classifier = DummyClassifier(strategy="constant", constant=0).fit(X, y) + >>> accuracy = get_scorer("accuracy") + >>> accuracy(classifier, X, y) + 0.4 + """ + if isinstance(scoring, str): + try: + if scoring == "max_error": + # TODO (1.8): scoring="max_error" has been deprecated in 1.6, + # remove in 1.8 + scorer = max_error_scorer + else: + scorer = copy.deepcopy(_SCORERS[scoring]) + except KeyError: + raise ValueError( + "%r is not a valid scoring value. " + "Use sklearn.metrics.get_scorer_names() " + "to get valid options." % scoring + ) + else: + scorer = scoring + return scorer + + +class _PassthroughScorer(_MetadataRequester): + # Passes scoring of estimator's `score` method back to estimator if scoring + # is `None`. + + def __init__(self, estimator): + self._estimator = estimator + + requests = MetadataRequest(owner=self.__class__.__name__) + try: + requests.score = copy.deepcopy(estimator._metadata_request.score) + except AttributeError: + try: + requests.score = copy.deepcopy(estimator._get_default_requests().score) + except AttributeError: + pass + + self._metadata_request = requests + + def __call__(self, estimator, *args, **kwargs): + """Method that wraps estimator.score""" + return estimator.score(*args, **kwargs) + + def __repr__(self): + return f"{self._estimator.__class__}.score" + + def _accept_sample_weight(self): + # TODO(slep006): remove when metadata routing is the only way + return "sample_weight" in signature(self._estimator.score).parameters + + def get_metadata_routing(self): + """Get requested data properties. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.3 + + Returns + ------- + routing : MetadataRouter + A :class:`~utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + return get_routing_for_object(self._metadata_request) + + def set_score_request(self, **kwargs): + """Set requested parameters by the scorer. + + Please see :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.5 + + Parameters + ---------- + kwargs : dict + Arguments should be of the form ``param_name=alias``, and `alias` + can be one of ``{True, False, None, str}``. + """ + if not _routing_enabled(): + raise RuntimeError( + "This method is only available when metadata routing is enabled." + " You can enable it using" + " sklearn.set_config(enable_metadata_routing=True)." + ) + + for param, alias in kwargs.items(): + self._metadata_request.score.add_request(param=param, alias=alias) + return self + + +def _check_multimetric_scoring(estimator, scoring): + """Check the scoring parameter in cases when multiple metrics are allowed. + + In addition, multimetric scoring leverages a caching mechanism to not call the same + estimator response method multiple times. Hence, the scorer is modified to only use + a single response method given a list of response methods and the estimator. + + Parameters + ---------- + estimator : sklearn estimator instance + The estimator for which the scoring will be applied. + + scoring : list, tuple or dict + Strategy to evaluate the performance of the cross-validated model on + the test set. + + The possibilities are: + + - a list or tuple of unique strings; + - a callable returning a dictionary where they keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables a values. + + See :ref:`multimetric_grid_search` for an example. + + Returns + ------- + scorers_dict : dict + A dict mapping each scorer name to its validated scorer. + """ + err_msg_generic = ( + f"scoring is invalid (got {scoring!r}). Refer to the " + "scoring glossary for details: " + "https://scikit-learn.org/stable/glossary.html#term-scoring" + ) + + if isinstance(scoring, (list, tuple, set)): + err_msg = ( + "The list/tuple elements must be unique strings of predefined scorers. " + ) + try: + keys = set(scoring) + except TypeError as e: + raise ValueError(err_msg) from e + + if len(keys) != len(scoring): + raise ValueError( + f"{err_msg} Duplicate elements were found in" + f" the given list. {scoring!r}" + ) + elif len(keys) > 0: + if not all(isinstance(k, str) for k in keys): + if any(callable(k) for k in keys): + raise ValueError( + f"{err_msg} One or more of the elements " + "were callables. Use a dict of score " + "name mapped to the scorer callable. " + f"Got {scoring!r}" + ) + else: + raise ValueError( + f"{err_msg} Non-string types were found " + f"in the given list. Got {scoring!r}" + ) + scorers = { + scorer: check_scoring(estimator, scoring=scorer) for scorer in scoring + } + else: + raise ValueError(f"{err_msg} Empty list was given. {scoring!r}") + + elif isinstance(scoring, dict): + keys = set(scoring) + if not all(isinstance(k, str) for k in keys): + raise ValueError( + "Non-string types were found in the keys of " + f"the given dict. scoring={scoring!r}" + ) + if len(keys) == 0: + raise ValueError(f"An empty dict was passed. {scoring!r}") + scorers = { + key: check_scoring(estimator, scoring=scorer) + for key, scorer in scoring.items() + } + else: + raise ValueError(err_msg_generic) + + return scorers + + +def _get_response_method_name(response_method): + try: + return response_method.__name__ + except AttributeError: + return _get_response_method_name(response_method.func) + + +@validate_params( + { + "score_func": [callable], + "response_method": [ + None, + list, + tuple, + StrOptions({"predict", "predict_proba", "decision_function"}), + Hidden(StrOptions({"default"})), + ], + "greater_is_better": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def make_scorer( + score_func, *, response_method="default", greater_is_better=True, **kwargs +): + """Make a scorer from a performance metric or loss function. + + A scorer is a wrapper around an arbitrary metric or loss function that is called + with the signature `scorer(estimator, X, y_true, **kwargs)`. + + It is accepted in all scikit-learn estimators or functions allowing a `scoring` + parameter. + + The parameter `response_method` allows to specify which method of the estimator + should be used to feed the scoring/loss function. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + score_func : callable + Score function (or loss function) with signature + ``score_func(y, y_pred, **kwargs)``. + + response_method : {"predict_proba", "decision_function", "predict"} or \ + list/tuple of such str, default=None + + Specifies the response method to use get prediction from an estimator + (i.e. :term:`predict_proba`, :term:`decision_function` or + :term:`predict`). Possible choices are: + + - if `str`, it corresponds to the name to the method to return; + - if a list or tuple of `str`, it provides the method names in order of + preference. The method returned corresponds to the first method in + the list and which is implemented by `estimator`. + - if `None`, it is equivalent to `"predict"`. + + .. versionadded:: 1.4 + + .. deprecated:: 1.6 + None is equivalent to 'predict' and is deprecated. It will be removed in + version 1.8. + + greater_is_better : bool, default=True + Whether `score_func` is a score function (default), meaning high is + good, or a loss function, meaning low is good. In the latter case, the + scorer object will sign-flip the outcome of the `score_func`. + + **kwargs : additional arguments + Additional parameters to be passed to `score_func`. + + Returns + ------- + scorer : callable + Callable object that returns a scalar score; greater is better. + + Examples + -------- + >>> from sklearn.metrics import fbeta_score, make_scorer + >>> ftwo_scorer = make_scorer(fbeta_score, beta=2) + >>> ftwo_scorer + make_scorer(fbeta_score, response_method='predict', beta=2) + >>> from sklearn.model_selection import GridSearchCV + >>> from sklearn.svm import LinearSVC + >>> grid = GridSearchCV(LinearSVC(), param_grid={'C': [1, 10]}, + ... scoring=ftwo_scorer) + """ + sign = 1 if greater_is_better else -1 + + if response_method is None: + warnings.warn( + "response_method=None is deprecated in version 1.6 and will be removed " + "in version 1.8. Leave it to its default value to avoid this warning.", + FutureWarning, + ) + response_method = "predict" + elif response_method == "default": + response_method = "predict" + + return _Scorer(score_func, sign, kwargs, response_method) + + +# Standard regression scores +explained_variance_scorer = make_scorer(explained_variance_score) +r2_scorer = make_scorer(r2_score) +neg_max_error_scorer = make_scorer(max_error, greater_is_better=False) +max_error_scorer = make_scorer(max_error, greater_is_better=False) +# TODO (1.8): remove in 1.8 (scoring="max_error" has been deprecated in 1.6) +deprecation_msg = ( + "Scoring method max_error was renamed to " + "neg_max_error in version 1.6 and will " + "be removed in 1.8." +) +max_error_scorer._deprecation_msg = deprecation_msg +neg_mean_squared_error_scorer = make_scorer(mean_squared_error, greater_is_better=False) +neg_mean_squared_log_error_scorer = make_scorer( + mean_squared_log_error, greater_is_better=False +) +neg_mean_absolute_error_scorer = make_scorer( + mean_absolute_error, greater_is_better=False +) +neg_mean_absolute_percentage_error_scorer = make_scorer( + mean_absolute_percentage_error, greater_is_better=False +) +neg_median_absolute_error_scorer = make_scorer( + median_absolute_error, greater_is_better=False +) +neg_root_mean_squared_error_scorer = make_scorer( + root_mean_squared_error, greater_is_better=False +) +neg_root_mean_squared_log_error_scorer = make_scorer( + root_mean_squared_log_error, greater_is_better=False +) +neg_mean_poisson_deviance_scorer = make_scorer( + mean_poisson_deviance, greater_is_better=False +) + +neg_mean_gamma_deviance_scorer = make_scorer( + mean_gamma_deviance, greater_is_better=False +) +d2_absolute_error_scorer = make_scorer(d2_absolute_error_score) + +# Standard Classification Scores +accuracy_scorer = make_scorer(accuracy_score) +balanced_accuracy_scorer = make_scorer(balanced_accuracy_score) +matthews_corrcoef_scorer = make_scorer(matthews_corrcoef) + + +def positive_likelihood_ratio(y_true, y_pred): + return class_likelihood_ratios(y_true, y_pred, replace_undefined_by=1.0)[0] + + +def negative_likelihood_ratio(y_true, y_pred): + return class_likelihood_ratios(y_true, y_pred, replace_undefined_by=1.0)[1] + + +positive_likelihood_ratio_scorer = make_scorer(positive_likelihood_ratio) +neg_negative_likelihood_ratio_scorer = make_scorer( + negative_likelihood_ratio, greater_is_better=False +) + +# Score functions that need decision values +top_k_accuracy_scorer = make_scorer( + top_k_accuracy_score, + greater_is_better=True, + response_method=("decision_function", "predict_proba"), +) +roc_auc_scorer = make_scorer( + roc_auc_score, + greater_is_better=True, + response_method=("decision_function", "predict_proba"), +) +average_precision_scorer = make_scorer( + average_precision_score, + response_method=("decision_function", "predict_proba"), +) +roc_auc_ovo_scorer = make_scorer( + roc_auc_score, response_method="predict_proba", multi_class="ovo" +) +roc_auc_ovo_weighted_scorer = make_scorer( + roc_auc_score, + response_method="predict_proba", + multi_class="ovo", + average="weighted", +) +roc_auc_ovr_scorer = make_scorer( + roc_auc_score, response_method="predict_proba", multi_class="ovr" +) +roc_auc_ovr_weighted_scorer = make_scorer( + roc_auc_score, + response_method="predict_proba", + multi_class="ovr", + average="weighted", +) + +# Score function for probabilistic classification +neg_log_loss_scorer = make_scorer( + log_loss, greater_is_better=False, response_method="predict_proba" +) +neg_brier_score_scorer = make_scorer( + brier_score_loss, greater_is_better=False, response_method="predict_proba" +) +brier_score_loss_scorer = make_scorer( + brier_score_loss, greater_is_better=False, response_method="predict_proba" +) + + +# Clustering scores +adjusted_rand_scorer = make_scorer(adjusted_rand_score) +rand_scorer = make_scorer(rand_score) +homogeneity_scorer = make_scorer(homogeneity_score) +completeness_scorer = make_scorer(completeness_score) +v_measure_scorer = make_scorer(v_measure_score) +mutual_info_scorer = make_scorer(mutual_info_score) +adjusted_mutual_info_scorer = make_scorer(adjusted_mutual_info_score) +normalized_mutual_info_scorer = make_scorer(normalized_mutual_info_score) +fowlkes_mallows_scorer = make_scorer(fowlkes_mallows_score) + + +_SCORERS = dict( + explained_variance=explained_variance_scorer, + r2=r2_scorer, + neg_max_error=neg_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, + neg_mean_squared_error=neg_mean_squared_error_scorer, + neg_mean_squared_log_error=neg_mean_squared_log_error_scorer, + neg_root_mean_squared_error=neg_root_mean_squared_error_scorer, + neg_root_mean_squared_log_error=neg_root_mean_squared_log_error_scorer, + neg_mean_poisson_deviance=neg_mean_poisson_deviance_scorer, + neg_mean_gamma_deviance=neg_mean_gamma_deviance_scorer, + d2_absolute_error_score=d2_absolute_error_scorer, + accuracy=accuracy_scorer, + top_k_accuracy=top_k_accuracy_scorer, + roc_auc=roc_auc_scorer, + roc_auc_ovr=roc_auc_ovr_scorer, + roc_auc_ovo=roc_auc_ovo_scorer, + roc_auc_ovr_weighted=roc_auc_ovr_weighted_scorer, + roc_auc_ovo_weighted=roc_auc_ovo_weighted_scorer, + balanced_accuracy=balanced_accuracy_scorer, + average_precision=average_precision_scorer, + neg_log_loss=neg_log_loss_scorer, + neg_brier_score=neg_brier_score_scorer, + positive_likelihood_ratio=positive_likelihood_ratio_scorer, + neg_negative_likelihood_ratio=neg_negative_likelihood_ratio_scorer, + # Cluster metrics that use supervised evaluation + adjusted_rand_score=adjusted_rand_scorer, + rand_score=rand_scorer, + homogeneity_score=homogeneity_scorer, + completeness_score=completeness_scorer, + v_measure_score=v_measure_scorer, + mutual_info_score=mutual_info_scorer, + adjusted_mutual_info_score=adjusted_mutual_info_scorer, + normalized_mutual_info_score=normalized_mutual_info_scorer, + fowlkes_mallows_score=fowlkes_mallows_scorer, +) + + +def get_scorer_names(): + """Get the names of all available scorers. + + These names can be passed to :func:`~sklearn.metrics.get_scorer` to + retrieve the scorer object. + + Returns + ------- + list of str + Names of all available scorers. + + Examples + -------- + >>> from sklearn.metrics import get_scorer_names + >>> all_scorers = get_scorer_names() + >>> type(all_scorers) + + >>> all_scorers[:3] + ['accuracy', 'adjusted_mutual_info_score', 'adjusted_rand_score'] + >>> "roc_auc" in all_scorers + True + """ + return sorted(_SCORERS.keys()) + + +for name, metric in [ + ("precision", precision_score), + ("recall", recall_score), + ("f1", f1_score), + ("jaccard", jaccard_score), +]: + _SCORERS[name] = make_scorer(metric, average="binary") + for average in ["macro", "micro", "samples", "weighted"]: + qualified_name = "{0}_{1}".format(name, average) + _SCORERS[qualified_name] = make_scorer(metric, pos_label=None, average=average) + + +@validate_params( + { + "estimator": [HasMethods("fit"), None], + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + list, + set, + tuple, + dict, + None, + ], + "allow_none": ["boolean"], + "raise_exc": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def check_scoring(estimator=None, scoring=None, *, allow_none=False, raise_exc=True): + """Determine scorer from user options. + + A TypeError will be thrown if the estimator cannot be scored. + + Parameters + ---------- + estimator : estimator object implementing 'fit' or None, default=None + The object to use to fit the data. If `None`, then this function may error + depending on `allow_none`. + + scoring : str, callable, list, tuple, set, or dict, default=None + Scorer to use. If `scoring` represents a single score, one can use: + + - a single string (see :ref:`scoring_string_names`); + - a callable (see :ref:`scoring_callable`) that returns a single value; + - `None`, the `estimator`'s + :ref:`default evaluation criterion ` is used. + + If `scoring` represents multiple scores, one can use: + + - a list, tuple or set of unique strings; + - a callable returning a dictionary where the keys are the metric names and the + values are the metric scorers; + - a dictionary with metric names as keys and callables a values. The callables + need to have the signature `callable(estimator, X, y)`. + + allow_none : bool, default=False + Whether to return None or raise an error if no `scoring` is specified and the + estimator has no `score` method. + + raise_exc : bool, default=True + Whether to raise an exception (if a subset of the scorers in multimetric scoring + fails) or to return an error code. + + - If set to `True`, raises the failing scorer's exception. + - If set to `False`, a formatted string of the exception details is passed as + result of the failing scorer(s). + + This applies if `scoring` is list, tuple, set, or dict. Ignored if `scoring` is + a str or a callable. + + .. versionadded:: 1.6 + + Returns + ------- + scoring : callable + A scorer callable object / function with signature ``scorer(estimator, X, y)``. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.metrics import check_scoring + >>> from sklearn.tree import DecisionTreeClassifier + >>> X, y = load_iris(return_X_y=True) + >>> classifier = DecisionTreeClassifier(max_depth=2).fit(X, y) + >>> scorer = check_scoring(classifier, scoring='accuracy') + >>> scorer(classifier, X, y) + 0.96... + + >>> from sklearn.metrics import make_scorer, accuracy_score, mean_squared_log_error + >>> X, y = load_iris(return_X_y=True) + >>> y *= -1 + >>> clf = DecisionTreeClassifier().fit(X, y) + >>> scoring = { + ... "accuracy": make_scorer(accuracy_score), + ... "mean_squared_log_error": make_scorer(mean_squared_log_error), + ... } + >>> scoring_call = check_scoring(estimator=clf, scoring=scoring, raise_exc=False) + >>> scores = scoring_call(clf, X, y) + >>> scores + {'accuracy': 1.0, 'mean_squared_log_error': 'Traceback ...'} + """ + if isinstance(scoring, str): + return get_scorer(scoring) + if callable(scoring): + # Heuristic to ensure user has not passed a metric + module = getattr(scoring, "__module__", None) + if ( + hasattr(module, "startswith") + and module.startswith("sklearn.metrics.") + and not module.startswith("sklearn.metrics._scorer") + and not module.startswith("sklearn.metrics.tests.") + ): + raise ValueError( + "scoring value %r looks like it is a metric " + "function rather than a scorer. A scorer should " + "require an estimator as its first parameter. " + "Please use `make_scorer` to convert a metric " + "to a scorer." % scoring + ) + return get_scorer(scoring) + if isinstance(scoring, (list, tuple, set, dict)): + scorers = _check_multimetric_scoring(estimator, scoring=scoring) + return _MultimetricScorer(scorers=scorers, raise_exc=raise_exc) + if scoring is None: + if hasattr(estimator, "score"): + return _PassthroughScorer(estimator) + elif allow_none: + return None + else: + raise TypeError( + "If no scoring is specified, the estimator passed should " + "have a 'score' method. The estimator %r does not." % estimator + ) + + +def _threshold_scores_to_class_labels(y_score, threshold, classes, pos_label): + """Threshold `y_score` and return the associated class labels.""" + if pos_label is None: + map_thresholded_score_to_label = np.array([0, 1]) + else: + pos_label_idx = np.flatnonzero(classes == pos_label)[0] + neg_label_idx = np.flatnonzero(classes != pos_label)[0] + map_thresholded_score_to_label = np.array([neg_label_idx, pos_label_idx]) + + return classes[map_thresholded_score_to_label[(y_score >= threshold).astype(int)]] + + +class _CurveScorer(_BaseScorer): + """Scorer taking a continuous response and output a score for each threshold. + + Parameters + ---------- + score_func : callable + The score function to use. It will be called as + `score_func(y_true, y_pred, **kwargs)`. + + sign : int + Either 1 or -1 to returns the score with `sign * score_func(estimator, X, y)`. + Thus, `sign` defined if higher scores are better or worse. + + kwargs : dict + Additional parameters to pass to the score function. + + thresholds : int or array-like + Related to the number of decision thresholds for which we want to compute the + score. If an integer, it will be used to generate `thresholds` thresholds + uniformly distributed between the minimum and maximum predicted scores. If an + array-like, it will be used as the thresholds. + + response_method : str + The method to call on the estimator to get the response values. + """ + + def __init__(self, score_func, sign, kwargs, thresholds, response_method): + super().__init__( + score_func=score_func, + sign=sign, + kwargs=kwargs, + response_method=response_method, + ) + self._thresholds = thresholds + + @classmethod + def from_scorer(cls, scorer, response_method, thresholds): + """Create a continuous scorer from a normal scorer.""" + instance = cls( + score_func=scorer._score_func, + sign=scorer._sign, + response_method=response_method, + thresholds=thresholds, + kwargs=scorer._kwargs, + ) + # transfer the metadata request + instance._metadata_request = scorer._get_metadata_request() + return instance + + def _score(self, method_caller, estimator, X, y_true, **kwargs): + """Evaluate predicted target values for X relative to y_true. + + Parameters + ---------- + method_caller : callable + Returns predictions given an estimator, method name, and other + arguments, potentially caching results. + + estimator : object + Trained estimator to use for scoring. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Test data that will be fed to estimator.predict. + + y_true : array-like of shape (n_samples,) + Gold standard target values for X. + + **kwargs : dict + Other parameters passed to the scorer. Refer to + :func:`set_score_request` for more details. + + Returns + ------- + scores : ndarray of shape (thresholds,) + The scores associated to each threshold. + + potential_thresholds : ndarray of shape (thresholds,) + The potential thresholds used to compute the scores. + """ + pos_label = self._get_pos_label() + y_score = method_caller( + estimator, self._response_method, X, pos_label=pos_label + ) + + scoring_kwargs = {**self._kwargs, **kwargs} + if isinstance(self._thresholds, Integral): + potential_thresholds = np.linspace( + np.min(y_score), np.max(y_score), self._thresholds + ) + else: + potential_thresholds = np.asarray(self._thresholds) + score_thresholds = [ + self._sign + * self._score_func( + y_true, + _threshold_scores_to_class_labels( + y_score, th, estimator.classes_, pos_label + ), + **scoring_kwargs, + ) + for th in potential_thresholds + ] + return np.array(score_thresholds), potential_thresholds diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..76020d80f8eb02a4647dada4415e5286a0bebe59 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/__init__.py @@ -0,0 +1,55 @@ +"""Evaluation metrics for cluster analysis results. + +- Supervised evaluation uses a ground truth class values for each sample. +- Unsupervised evaluation does not use ground truths and measures the "quality" of the + model itself. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._bicluster import consensus_score +from ._supervised import ( + adjusted_mutual_info_score, + adjusted_rand_score, + completeness_score, + contingency_matrix, + entropy, + expected_mutual_information, + fowlkes_mallows_score, + homogeneity_completeness_v_measure, + homogeneity_score, + mutual_info_score, + normalized_mutual_info_score, + pair_confusion_matrix, + rand_score, + v_measure_score, +) +from ._unsupervised import ( + calinski_harabasz_score, + davies_bouldin_score, + silhouette_samples, + silhouette_score, +) + +__all__ = [ + "adjusted_mutual_info_score", + "adjusted_rand_score", + "calinski_harabasz_score", + "completeness_score", + "consensus_score", + "contingency_matrix", + "davies_bouldin_score", + "entropy", + "expected_mutual_information", + "fowlkes_mallows_score", + "homogeneity_completeness_v_measure", + "homogeneity_score", + "mutual_info_score", + "normalized_mutual_info_score", + "pair_confusion_matrix", + "rand_score", + "silhouette_samples", + "silhouette_score", + "v_measure_score", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..bb306c025b69466817de26661eaf286ea59024bc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_bicluster.py @@ -0,0 +1,114 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +from scipy.optimize import linear_sum_assignment + +from ...utils._param_validation import StrOptions, validate_params +from ...utils.validation import check_array, check_consistent_length + +__all__ = ["consensus_score"] + + +def _check_rows_and_columns(a, b): + """Unpacks the row and column arrays and checks their shape.""" + check_consistent_length(*a) + check_consistent_length(*b) + checks = lambda x: check_array(x, ensure_2d=False) + a_rows, a_cols = map(checks, a) + b_rows, b_cols = map(checks, b) + return a_rows, a_cols, b_rows, b_cols + + +def _jaccard(a_rows, a_cols, b_rows, b_cols): + """Jaccard coefficient on the elements of the two biclusters.""" + intersection = (a_rows * b_rows).sum() * (a_cols * b_cols).sum() + + a_size = a_rows.sum() * a_cols.sum() + b_size = b_rows.sum() * b_cols.sum() + + return intersection / (a_size + b_size - intersection) + + +def _pairwise_similarity(a, b, similarity): + """Computes pairwise similarity matrix. + + result[i, j] is the Jaccard coefficient of a's bicluster i and b's + bicluster j. + + """ + a_rows, a_cols, b_rows, b_cols = _check_rows_and_columns(a, b) + n_a = a_rows.shape[0] + n_b = b_rows.shape[0] + result = np.array( + [ + [similarity(a_rows[i], a_cols[i], b_rows[j], b_cols[j]) for j in range(n_b)] + for i in range(n_a) + ] + ) + return result + + +@validate_params( + { + "a": [tuple], + "b": [tuple], + "similarity": [callable, StrOptions({"jaccard"})], + }, + prefer_skip_nested_validation=True, +) +def consensus_score(a, b, *, similarity="jaccard"): + """The similarity of two sets of biclusters. + + Similarity between individual biclusters is computed. Then the best + matching between sets is found by solving a linear sum assignment problem, + using a modified Jonker-Volgenant algorithm. + The final score is the sum of similarities divided by the size of + the larger set. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + a : tuple (rows, columns) + Tuple of row and column indicators for a set of biclusters. + + b : tuple (rows, columns) + Another set of biclusters like ``a``. + + similarity : 'jaccard' or callable, default='jaccard' + May be the string "jaccard" to use the Jaccard coefficient, or + any function that takes four arguments, each of which is a 1d + indicator vector: (a_rows, a_columns, b_rows, b_columns). + + Returns + ------- + consensus_score : float + Consensus score, a non-negative value, sum of similarities + divided by size of larger set. + + See Also + -------- + scipy.optimize.linear_sum_assignment : Solve the linear sum assignment problem. + + References + ---------- + * Hochreiter, Bodenhofer, et. al., 2010. `FABIA: factor analysis + for bicluster acquisition + `__. + + Examples + -------- + >>> from sklearn.metrics import consensus_score + >>> a = ([[True, False], [False, True]], [[False, True], [True, False]]) + >>> b = ([[False, True], [True, False]], [[True, False], [False, True]]) + >>> consensus_score(a, b, similarity='jaccard') + 1.0 + """ + if similarity == "jaccard": + similarity = _jaccard + matrix = _pairwise_similarity(a, b, similarity) + row_indices, col_indices = linear_sum_assignment(1.0 - matrix) + n_a = len(a[0]) + n_b = len(b[0]) + return float(matrix[row_indices, col_indices].sum() / max(n_a, n_b)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_expected_mutual_info_fast.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_expected_mutual_info_fast.pyx new file mode 100644 index 0000000000000000000000000000000000000000..3d51def36c255b7479fea1ae516fdc47c0c4faeb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_expected_mutual_info_fast.pyx @@ -0,0 +1,69 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from libc.math cimport exp, lgamma + +from ...utils._typedefs cimport float64_t, int64_t + +import numpy as np +from scipy.special import gammaln + + +def expected_mutual_information(contingency, int64_t n_samples): + """Calculate the expected mutual information for two labelings.""" + cdef: + float64_t emi = 0 + int64_t n_rows, n_cols + float64_t term2, term3, gln + int64_t[::1] a_view, b_view + float64_t[::1] term1 + float64_t[::1] gln_a, gln_b, gln_Na, gln_Nb, gln_Nnij, log_Nnij + float64_t[::1] log_a, log_b + Py_ssize_t i, j, nij + int64_t start, end + + n_rows, n_cols = contingency.shape + a = np.ravel(contingency.sum(axis=1).astype(np.int64, copy=False)) + b = np.ravel(contingency.sum(axis=0).astype(np.int64, copy=False)) + a_view = a + b_view = b + + # any labelling with zero entropy implies EMI = 0 + if a.size == 1 or b.size == 1: + return 0.0 + + # There are three major terms to the EMI equation, which are multiplied to + # and then summed over varying nij values. + # While nijs[0] will never be used, having it simplifies the indexing. + nijs = np.arange(0, max(np.max(a), np.max(b)) + 1, dtype='float') + nijs[0] = 1 # Stops divide by zero warnings. As its not used, no issue. + # term1 is nij / N + term1 = nijs / n_samples + # term2 is log((N*nij) / (a * b)) == log(N * nij) - log(a * b) + log_a = np.log(a) + log_b = np.log(b) + # term2 uses log(N * nij) = log(N) + log(nij) + log_Nnij = np.log(n_samples) + np.log(nijs) + # term3 is large, and involved many factorials. Calculate these in log + # space to stop overflows. + gln_a = gammaln(a + 1) + gln_b = gammaln(b + 1) + gln_Na = gammaln(n_samples - a + 1) + gln_Nb = gammaln(n_samples - b + 1) + gln_Nnij = gammaln(nijs + 1) + gammaln(n_samples + 1) + + # emi itself is a summation over the various values. + for i in range(n_rows): + for j in range(n_cols): + start = max(1, a_view[i] - n_samples + b_view[j]) + end = min(a_view[i], b_view[j]) + 1 + for nij in range(start, end): + term2 = log_Nnij[nij] - log_a[i] - log_b[j] + # Numerators are positive, denominators are negative. + gln = (gln_a[i] + gln_b[j] + gln_Na[i] + gln_Nb[j] + - gln_Nnij[nij] - lgamma(a_view[i] - nij + 1) + - lgamma(b_view[j] - nij + 1) + - lgamma(n_samples - a_view[i] - b_view[j] + nij + 1)) + term3 = exp(gln) + emi += (term1[nij] * term2 * term3) + return emi diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..ccc11d752adbacd4960592e154a2c886276bc3f9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_supervised.py @@ -0,0 +1,1314 @@ +"""Utilities to evaluate the clustering performance of models. + +Functions named as *_score return a scalar value to maximize: the higher the +better. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from math import log +from numbers import Real + +import numpy as np +from scipy import sparse as sp + +from ...utils._array_api import _max_precision_float_dtype, get_namespace_and_device +from ...utils._param_validation import Hidden, Interval, StrOptions, validate_params +from ...utils.multiclass import type_of_target +from ...utils.validation import check_array, check_consistent_length +from ._expected_mutual_info_fast import expected_mutual_information + + +def check_clusterings(labels_true, labels_pred): + """Check that the labels arrays are 1D and of same dimension. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + The true labels. + + labels_pred : array-like of shape (n_samples,) + The predicted labels. + """ + labels_true = check_array( + labels_true, + ensure_2d=False, + ensure_min_samples=0, + dtype=None, + ) + + labels_pred = check_array( + labels_pred, + ensure_2d=False, + ensure_min_samples=0, + dtype=None, + ) + + type_label = type_of_target(labels_true) + type_pred = type_of_target(labels_pred) + + if "continuous" in (type_pred, type_label): + msg = ( + "Clustering metrics expects discrete values but received" + f" {type_label} values for label, and {type_pred} values " + "for target" + ) + warnings.warn(msg, UserWarning) + + # input checks + if labels_true.ndim != 1: + raise ValueError("labels_true must be 1D: shape is %r" % (labels_true.shape,)) + if labels_pred.ndim != 1: + raise ValueError("labels_pred must be 1D: shape is %r" % (labels_pred.shape,)) + check_consistent_length(labels_true, labels_pred) + + return labels_true, labels_pred + + +def _generalized_average(U, V, average_method): + """Return a particular mean of two numbers.""" + if average_method == "min": + return min(U, V) + elif average_method == "geometric": + return np.sqrt(U * V) + elif average_method == "arithmetic": + return np.mean([U, V]) + elif average_method == "max": + return max(U, V) + else: + raise ValueError( + "'average_method' must be 'min', 'geometric', 'arithmetic', or 'max'" + ) + + +@validate_params( + { + "labels_true": ["array-like", None], + "labels_pred": ["array-like", None], + "eps": [Interval(Real, 0, None, closed="left"), None], + "sparse": ["boolean"], + "dtype": "no_validation", # delegate the validation to SciPy + }, + prefer_skip_nested_validation=True, +) +def contingency_matrix( + labels_true, labels_pred, *, eps=None, sparse=False, dtype=np.int64 +): + """Build a contingency matrix describing the relationship between labels. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,) + Cluster labels to evaluate. + + eps : float, default=None + If a float, that value is added to all values in the contingency + matrix. This helps to stop NaN propagation. + If ``None``, nothing is adjusted. + + sparse : bool, default=False + If `True`, return a sparse CSR contingency matrix. If `eps` is not + `None` and `sparse` is `True` will raise ValueError. + + .. versionadded:: 0.18 + + dtype : numeric type, default=np.int64 + Output dtype. Ignored if `eps` is not `None`. + + .. versionadded:: 0.24 + + Returns + ------- + contingency : {array-like, sparse}, shape=[n_classes_true, n_classes_pred] + Matrix :math:`C` such that :math:`C_{i, j}` is the number of samples in + true class :math:`i` and in predicted class :math:`j`. If + ``eps is None``, the dtype of this array will be integer unless set + otherwise with the ``dtype`` argument. If ``eps`` is given, the dtype + will be float. + Will be a ``sklearn.sparse.csr_matrix`` if ``sparse=True``. + + Examples + -------- + >>> from sklearn.metrics.cluster import contingency_matrix + >>> labels_true = [0, 0, 1, 1, 2, 2] + >>> labels_pred = [1, 0, 2, 1, 0, 2] + >>> contingency_matrix(labels_true, labels_pred) + array([[1, 1, 0], + [0, 1, 1], + [1, 0, 1]]) + """ + + if eps is not None and sparse: + raise ValueError("Cannot set 'eps' when sparse=True") + + classes, class_idx = np.unique(labels_true, return_inverse=True) + clusters, cluster_idx = np.unique(labels_pred, return_inverse=True) + n_classes = classes.shape[0] + n_clusters = clusters.shape[0] + # Using coo_matrix to accelerate simple histogram calculation, + # i.e. bins are consecutive integers + # Currently, coo_matrix is faster than histogram2d for simple cases + contingency = sp.coo_matrix( + (np.ones(class_idx.shape[0]), (class_idx, cluster_idx)), + shape=(n_classes, n_clusters), + dtype=dtype, + ) + if sparse: + contingency = contingency.tocsr() + contingency.sum_duplicates() + else: + contingency = contingency.toarray() + if eps is not None: + # don't use += as contingency is integer + contingency = contingency + eps + return contingency + + +# clustering measures + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def pair_confusion_matrix(labels_true, labels_pred): + """Pair confusion matrix arising from two clusterings. + + The pair confusion matrix :math:`C` computes a 2 by 2 similarity matrix + between two clusterings by considering all pairs of samples and counting + pairs that are assigned into the same or into different clusters under + the true and predicted clusterings [1]_. + + Considering a pair of samples that is clustered together a positive pair, + then as in binary classification the count of true negatives is + :math:`C_{00}`, false negatives is :math:`C_{10}`, true positives is + :math:`C_{11}` and false positives is :math:`C_{01}`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,), dtype=integral + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,), dtype=integral + Cluster labels to evaluate. + + Returns + ------- + C : ndarray of shape (2, 2), dtype=np.int64 + The contingency matrix. + + See Also + -------- + sklearn.metrics.rand_score : Rand Score. + sklearn.metrics.adjusted_rand_score : Adjusted Rand Score. + sklearn.metrics.adjusted_mutual_info_score : Adjusted Mutual Information. + + References + ---------- + .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." + Journal of Classification 2, 193–218 (1985). + <10.1007/BF01908075>` + + Examples + -------- + Perfectly matching labelings have all non-zero entries on the + diagonal regardless of actual label values: + + >>> from sklearn.metrics.cluster import pair_confusion_matrix + >>> pair_confusion_matrix([0, 0, 1, 1], [1, 1, 0, 0]) + array([[8, 0], + [0, 4]]... + + Labelings that assign all classes members to the same clusters + are complete but may be not always pure, hence penalized, and + have some off-diagonal non-zero entries: + + >>> pair_confusion_matrix([0, 0, 1, 2], [0, 0, 1, 1]) + array([[8, 2], + [0, 2]]... + + Note that the matrix is not symmetric. + """ + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + n_samples = np.int64(labels_true.shape[0]) + + # Computation using the contingency data + contingency = contingency_matrix( + labels_true, labels_pred, sparse=True, dtype=np.int64 + ) + n_c = np.ravel(contingency.sum(axis=1)) + n_k = np.ravel(contingency.sum(axis=0)) + sum_squares = (contingency.data**2).sum() + C = np.empty((2, 2), dtype=np.int64) + C[1, 1] = sum_squares - n_samples + C[0, 1] = contingency.dot(n_k).sum() - sum_squares + C[1, 0] = contingency.transpose().dot(n_c).sum() - sum_squares + C[0, 0] = n_samples**2 - C[0, 1] - C[1, 0] - sum_squares + return C + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def rand_score(labels_true, labels_pred): + """Rand index. + + The Rand Index computes a similarity measure between two clusterings + by considering all pairs of samples and counting pairs that are + assigned in the same or different clusters in the predicted and + true clusterings [1]_ [2]_. + + The raw RI score [3]_ is: + + .. code-block:: text + + RI = (number of agreeing pairs) / (number of pairs) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,), dtype=integral + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,), dtype=integral + Cluster labels to evaluate. + + Returns + ------- + RI : float + Similarity score between 0.0 and 1.0, inclusive, 1.0 stands for + perfect match. + + See Also + -------- + adjusted_rand_score: Adjusted Rand Score. + adjusted_mutual_info_score: Adjusted Mutual Information. + + References + ---------- + .. [1] :doi:`Hubert, L., Arabie, P. "Comparing partitions." + Journal of Classification 2, 193–218 (1985). + <10.1007/BF01908075>`. + + .. [2] `Wikipedia: Simple Matching Coefficient + `_ + + .. [3] `Wikipedia: Rand Index `_ + + Examples + -------- + Perfectly matching labelings have a score of 1 even + + >>> from sklearn.metrics.cluster import rand_score + >>> rand_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + Labelings that assign all classes members to the same clusters + are complete but may not always be pure, hence penalized: + + >>> rand_score([0, 0, 1, 2], [0, 0, 1, 1]) + 0.83 + """ + contingency = pair_confusion_matrix(labels_true, labels_pred) + numerator = contingency.diagonal().sum() + denominator = contingency.sum() + + if numerator == denominator or denominator == 0: + # Special limit cases: no clustering since the data is not split; + # or trivial clustering where each document is assigned a unique + # cluster. These are perfect matches hence return 1.0. + return 1.0 + + return float(numerator / denominator) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def adjusted_rand_score(labels_true, labels_pred): + """Rand index adjusted for chance. + + The Rand Index computes a similarity measure between two clusterings + by considering all pairs of samples and counting pairs that are + assigned in the same or different clusters in the predicted and + true clusterings. + + The raw RI score is then "adjusted for chance" into the ARI score + using the following scheme:: + + ARI = (RI - Expected_RI) / (max(RI) - Expected_RI) + + The adjusted Rand index is thus ensured to have a value close to + 0.0 for random labeling independently of the number of clusters and + samples and exactly 1.0 when the clusterings are identical (up to + a permutation). The adjusted Rand index is bounded below by -0.5 for + especially discordant clusterings. + + ARI is a symmetric measure:: + + adjusted_rand_score(a, b) == adjusted_rand_score(b, a) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,), dtype=int + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,), dtype=int + Cluster labels to evaluate. + + Returns + ------- + ARI : float + Similarity score between -0.5 and 1.0. Random labelings have an ARI + close to 0.0. 1.0 stands for perfect match. + + See Also + -------- + adjusted_mutual_info_score : Adjusted Mutual Information. + + References + ---------- + .. [Hubert1985] L. Hubert and P. Arabie, Comparing Partitions, + Journal of Classification 1985 + https://link.springer.com/article/10.1007%2FBF01908075 + + .. [Steinley2004] D. Steinley, Properties of the Hubert-Arabie + adjusted Rand index, Psychological Methods 2004 + + .. [wk] https://en.wikipedia.org/wiki/Rand_index#Adjusted_Rand_index + + .. [Chacon] :doi:`Minimum adjusted Rand index for two clusterings of a given size, + 2022, J. E. Chacón and A. I. Rastrojo <10.1007/s11634-022-00491-w>` + + Examples + -------- + Perfectly matching labelings have a score of 1 even + + >>> from sklearn.metrics.cluster import adjusted_rand_score + >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 1]) + 1.0 + >>> adjusted_rand_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + Labelings that assign all classes members to the same clusters + are complete but may not always be pure, hence penalized:: + + >>> adjusted_rand_score([0, 0, 1, 2], [0, 0, 1, 1]) + 0.57 + + ARI is symmetric, so labelings that have pure clusters with members + coming from the same classes but unnecessary splits are penalized:: + + >>> adjusted_rand_score([0, 0, 1, 1], [0, 0, 1, 2]) + 0.57 + + If classes members are completely split across different clusters, the + assignment is totally incomplete, hence the ARI is very low:: + + >>> adjusted_rand_score([0, 0, 0, 0], [0, 1, 2, 3]) + 0.0 + + ARI may take a negative value for especially discordant labelings that + are a worse choice than the expected value of random labels:: + + >>> adjusted_rand_score([0, 0, 1, 1], [0, 1, 0, 1]) + -0.5 + + See :ref:`sphx_glr_auto_examples_cluster_plot_adjusted_for_chance_measures.py` + for a more detailed example. + """ + (tn, fp), (fn, tp) = pair_confusion_matrix(labels_true, labels_pred) + # convert to Python integer types, to avoid overflow or underflow + tn, fp, fn, tp = int(tn), int(fp), int(fn), int(tp) + + # Special cases: empty data or full agreement + if fn == 0 and fp == 0: + return 1.0 + + return 2.0 * (tp * tn - fn * fp) / ((tp + fn) * (fn + tn) + (tp + fp) * (fp + tn)) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + "beta": [Interval(Real, 0, None, closed="left")], + }, + prefer_skip_nested_validation=True, +) +def homogeneity_completeness_v_measure(labels_true, labels_pred, *, beta=1.0): + """Compute the homogeneity and completeness and V-Measure scores at once. + + Those metrics are based on normalized conditional entropy measures of + the clustering labeling to evaluate given the knowledge of a Ground + Truth class labels of the same samples. + + A clustering result satisfies homogeneity if all of its clusters + contain only data points which are members of a single class. + + A clustering result satisfies completeness if all the data points + that are members of a given class are elements of the same cluster. + + Both scores have positive values between 0.0 and 1.0, larger values + being desirable. + + Those 3 metrics are independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score values in any way. + + V-Measure is furthermore symmetric: swapping ``labels_true`` and + ``label_pred`` will give the same score. This does not hold for + homogeneity and completeness. V-Measure is identical to + :func:`normalized_mutual_info_score` with the arithmetic averaging + method. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,) + Cluster labels to evaluate. + + beta : float, default=1.0 + Ratio of weight attributed to ``homogeneity`` vs ``completeness``. + If ``beta`` is greater than 1, ``completeness`` is weighted more + strongly in the calculation. If ``beta`` is less than 1, + ``homogeneity`` is weighted more strongly. + + Returns + ------- + homogeneity : float + Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling. + + completeness : float + Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling. + + v_measure : float + Harmonic mean of the first two. + + See Also + -------- + homogeneity_score : Homogeneity metric of cluster labeling. + completeness_score : Completeness metric of cluster labeling. + v_measure_score : V-Measure (NMI with arithmetic mean option). + + Examples + -------- + >>> from sklearn.metrics import homogeneity_completeness_v_measure + >>> y_true, y_pred = [0, 0, 1, 1, 2, 2], [0, 0, 1, 2, 2, 2] + >>> homogeneity_completeness_v_measure(y_true, y_pred) + (0.71, 0.771, 0.74) + """ + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + + if len(labels_true) == 0: + return 1.0, 1.0, 1.0 + + entropy_C = entropy(labels_true) + entropy_K = entropy(labels_pred) + + contingency = contingency_matrix(labels_true, labels_pred, sparse=True) + MI = mutual_info_score(None, None, contingency=contingency) + + homogeneity = MI / (entropy_C) if entropy_C else 1.0 + completeness = MI / (entropy_K) if entropy_K else 1.0 + + if homogeneity + completeness == 0.0: + v_measure_score = 0.0 + else: + v_measure_score = ( + (1 + beta) + * homogeneity + * completeness + / (beta * homogeneity + completeness) + ) + + return float(homogeneity), float(completeness), float(v_measure_score) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def homogeneity_score(labels_true, labels_pred): + """Homogeneity metric of a cluster labeling given a ground truth. + + A clustering result satisfies homogeneity if all of its clusters + contain only data points which are members of a single class. + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is not symmetric: switching ``label_true`` with ``label_pred`` + will return the :func:`completeness_score` which will be different in + general. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,) + Cluster labels to evaluate. + + Returns + ------- + homogeneity : float + Score between 0.0 and 1.0. 1.0 stands for perfectly homogeneous labeling. + + See Also + -------- + completeness_score : Completeness metric of cluster labeling. + v_measure_score : V-Measure (NMI with arithmetic mean option). + + References + ---------- + + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ + + Examples + -------- + + Perfect labelings are homogeneous:: + + >>> from sklearn.metrics.cluster import homogeneity_score + >>> homogeneity_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + Non-perfect labelings that further split classes into more clusters can be + perfectly homogeneous:: + + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 1, 2])) + 1.000000 + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 2, 3])) + 1.000000 + + Clusters that include samples from different classes do not make for an + homogeneous labeling:: + + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 1, 0, 1])) + 0.0... + >>> print("%.6f" % homogeneity_score([0, 0, 1, 1], [0, 0, 0, 0])) + 0.0... + """ + return homogeneity_completeness_v_measure(labels_true, labels_pred)[0] + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def completeness_score(labels_true, labels_pred): + """Compute completeness metric of a cluster labeling given a ground truth. + + A clustering result satisfies completeness if all the data points + that are members of a given class are elements of the same cluster. + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is not symmetric: switching ``label_true`` with ``label_pred`` + will return the :func:`homogeneity_score` which will be different in + general. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,) + Cluster labels to evaluate. + + Returns + ------- + completeness : float + Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling. + + See Also + -------- + homogeneity_score : Homogeneity metric of cluster labeling. + v_measure_score : V-Measure (NMI with arithmetic mean option). + + References + ---------- + + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ + + Examples + -------- + + Perfect labelings are complete:: + + >>> from sklearn.metrics.cluster import completeness_score + >>> completeness_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + Non-perfect labelings that assign all classes members to the same clusters + are still complete:: + + >>> print(completeness_score([0, 0, 1, 1], [0, 0, 0, 0])) + 1.0 + >>> print(completeness_score([0, 1, 2, 3], [0, 0, 1, 1])) + 0.999 + + If classes members are split across different clusters, the + assignment cannot be complete:: + + >>> print(completeness_score([0, 0, 1, 1], [0, 1, 0, 1])) + 0.0 + >>> print(completeness_score([0, 0, 0, 0], [0, 1, 2, 3])) + 0.0 + """ + return homogeneity_completeness_v_measure(labels_true, labels_pred)[1] + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + "beta": [Interval(Real, 0, None, closed="left")], + }, + prefer_skip_nested_validation=True, +) +def v_measure_score(labels_true, labels_pred, *, beta=1.0): + """V-measure cluster labeling given a ground truth. + + This score is identical to :func:`normalized_mutual_info_score` with + the ``'arithmetic'`` option for averaging. + + The V-measure is the harmonic mean between homogeneity and completeness:: + + v = (1 + beta) * homogeneity * completeness + / (beta * homogeneity + completeness) + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to + measure the agreement of two independent label assignments strategies + on the same dataset when the real ground truth is not known. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,) + Ground truth class labels to be used as a reference. + + labels_pred : array-like of shape (n_samples,) + Cluster labels to evaluate. + + beta : float, default=1.0 + Ratio of weight attributed to ``homogeneity`` vs ``completeness``. + If ``beta`` is greater than 1, ``completeness`` is weighted more + strongly in the calculation. If ``beta`` is less than 1, + ``homogeneity`` is weighted more strongly. + + Returns + ------- + v_measure : float + Score between 0.0 and 1.0. 1.0 stands for perfectly complete labeling. + + See Also + -------- + homogeneity_score : Homogeneity metric of cluster labeling. + completeness_score : Completeness metric of cluster labeling. + normalized_mutual_info_score : Normalized Mutual Information. + + References + ---------- + + .. [1] `Andrew Rosenberg and Julia Hirschberg, 2007. V-Measure: A + conditional entropy-based external cluster evaluation measure + `_ + + Examples + -------- + Perfect labelings are both homogeneous and complete, hence have score 1.0:: + + >>> from sklearn.metrics.cluster import v_measure_score + >>> v_measure_score([0, 0, 1, 1], [0, 0, 1, 1]) + 1.0 + >>> v_measure_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + Labelings that assign all classes members to the same clusters + are complete but not homogeneous, hence penalized:: + + >>> print("%.6f" % v_measure_score([0, 0, 1, 2], [0, 0, 1, 1])) + 0.8 + >>> print("%.6f" % v_measure_score([0, 1, 2, 3], [0, 0, 1, 1])) + 0.67 + + Labelings that have pure clusters with members coming from the same + classes are homogeneous but un-necessary splits harm completeness + and thus penalize V-measure as well:: + + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 1, 2])) + 0.8 + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 1, 2, 3])) + 0.67 + + If classes members are completely split across different clusters, + the assignment is totally incomplete, hence the V-Measure is null:: + + >>> print("%.6f" % v_measure_score([0, 0, 0, 0], [0, 1, 2, 3])) + 0.0 + + Clusters that include samples from totally different classes totally + destroy the homogeneity of the labeling, hence:: + + >>> print("%.6f" % v_measure_score([0, 0, 1, 1], [0, 0, 0, 0])) + 0.0 + """ + return homogeneity_completeness_v_measure(labels_true, labels_pred, beta=beta)[2] + + +@validate_params( + { + "labels_true": ["array-like", None], + "labels_pred": ["array-like", None], + "contingency": ["array-like", "sparse matrix", None], + }, + prefer_skip_nested_validation=True, +) +def mutual_info_score(labels_true, labels_pred, *, contingency=None): + """Mutual Information between two clusterings. + + The Mutual Information is a measure of the similarity between two labels + of the same data. Where :math:`|U_i|` is the number of the samples + in cluster :math:`U_i` and :math:`|V_j|` is the number of the + samples in cluster :math:`V_j`, the Mutual Information + between clusterings :math:`U` and :math:`V` is given as: + + .. math:: + + MI(U,V)=\\sum_{i=1}^{|U|} \\sum_{j=1}^{|V|} \\frac{|U_i\\cap V_j|}{N} + \\log\\frac{N|U_i \\cap V_j|}{|U_i||V_j|} + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is furthermore symmetric: switching :math:`U` (i.e + ``label_true``) with :math:`V` (i.e. ``label_pred``) will return the + same score value. This can be useful to measure the agreement of two + independent label assignments strategies on the same dataset when the + real ground truth is not known. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,), dtype=integral + A clustering of the data into disjoint subsets, called :math:`U` in + the above formula. + + labels_pred : array-like of shape (n_samples,), dtype=integral + A clustering of the data into disjoint subsets, called :math:`V` in + the above formula. + + contingency : {array-like, sparse matrix} of shape \ + (n_classes_true, n_classes_pred), default=None + A contingency matrix given by the + :func:`~sklearn.metrics.cluster.contingency_matrix` function. If value + is ``None``, it will be computed, otherwise the given value is used, + with ``labels_true`` and ``labels_pred`` ignored. + + Returns + ------- + mi : float + Mutual information, a non-negative value, measured in nats using the + natural logarithm. + + See Also + -------- + adjusted_mutual_info_score : Adjusted against chance Mutual Information. + normalized_mutual_info_score : Normalized Mutual Information. + + Notes + ----- + The logarithm used is the natural logarithm (base-e). + + Examples + -------- + >>> from sklearn.metrics import mutual_info_score + >>> labels_true = [0, 1, 1, 0, 1, 0] + >>> labels_pred = [0, 1, 0, 0, 1, 1] + >>> mutual_info_score(labels_true, labels_pred) + 0.0566 + """ + if contingency is None: + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + contingency = contingency_matrix(labels_true, labels_pred, sparse=True) + else: + contingency = check_array( + contingency, + accept_sparse=["csr", "csc", "coo"], + dtype=[int, np.int32, np.int64], + ) + + if isinstance(contingency, np.ndarray): + # For an array + nzx, nzy = np.nonzero(contingency) + nz_val = contingency[nzx, nzy] + else: + # For a sparse matrix + nzx, nzy, nz_val = sp.find(contingency) + + contingency_sum = contingency.sum() + pi = np.ravel(contingency.sum(axis=1)) + pj = np.ravel(contingency.sum(axis=0)) + + # Since MI <= min(H(X), H(Y)), any labelling with zero entropy, i.e. containing a + # single cluster, implies MI = 0 + if pi.size == 1 or pj.size == 1: + return 0.0 + + log_contingency_nm = np.log(nz_val) + contingency_nm = nz_val / contingency_sum + # Don't need to calculate the full outer product, just for non-zeroes + outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype( + np.int64, copy=False + ) + log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum()) + mi = ( + contingency_nm * (log_contingency_nm - log(contingency_sum)) + + contingency_nm * log_outer + ) + mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi) + return float(np.clip(mi.sum(), 0.0, None)) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + "average_method": [StrOptions({"arithmetic", "max", "min", "geometric"})], + }, + prefer_skip_nested_validation=True, +) +def adjusted_mutual_info_score( + labels_true, labels_pred, *, average_method="arithmetic" +): + """Adjusted Mutual Information between two clusterings. + + Adjusted Mutual Information (AMI) is an adjustment of the Mutual + Information (MI) score to account for chance. It accounts for the fact that + the MI is generally higher for two clusterings with a larger number of + clusters, regardless of whether there is actually more information shared. + For two clusterings :math:`U` and :math:`V`, the AMI is given as:: + + AMI(U, V) = [MI(U, V) - E(MI(U, V))] / [avg(H(U), H(V)) - E(MI(U, V))] + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is furthermore symmetric: switching :math:`U` (``label_true``) + with :math:`V` (``labels_pred``) will return the same score value. This can + be useful to measure the agreement of two independent label assignments + strategies on the same dataset when the real ground truth is not known. + + Be mindful that this function is an order of magnitude slower than other + metrics, such as the Adjusted Rand Index. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : int array-like of shape (n_samples,) + A clustering of the data into disjoint subsets, called :math:`U` in + the above formula. + + labels_pred : int array-like of shape (n_samples,) + A clustering of the data into disjoint subsets, called :math:`V` in + the above formula. + + average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic' + How to compute the normalizer in the denominator. + + .. versionadded:: 0.20 + + .. versionchanged:: 0.22 + The default value of ``average_method`` changed from 'max' to + 'arithmetic'. + + Returns + ------- + ami: float (upperlimited by 1.0) + The AMI returns a value of 1 when the two partitions are identical + (ie perfectly matched). Random partitions (independent labellings) have + an expected AMI around 0 on average hence can be negative. The value is + in adjusted nats (based on the natural logarithm). + + See Also + -------- + adjusted_rand_score : Adjusted Rand Index. + mutual_info_score : Mutual Information (not adjusted for chance). + + References + ---------- + .. [1] `Vinh, Epps, and Bailey, (2010). Information Theoretic Measures for + Clusterings Comparison: Variants, Properties, Normalization and + Correction for Chance, JMLR + `_ + + .. [2] `Wikipedia entry for the Adjusted Mutual Information + `_ + + Examples + -------- + + Perfect labelings are both homogeneous and complete, hence have + score 1.0:: + + >>> from sklearn.metrics.cluster import adjusted_mutual_info_score + >>> adjusted_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) + 1.0 + >>> adjusted_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + If classes members are completely split across different clusters, + the assignment is totally in-complete, hence the AMI is null:: + + >>> adjusted_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) + 0.0 + """ + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + n_samples = labels_true.shape[0] + classes = np.unique(labels_true) + clusters = np.unique(labels_pred) + + # Special limit cases: no clustering since the data is not split. + # It corresponds to both labellings having zero entropy. + # This is a perfect match hence return 1.0. + if ( + classes.shape[0] == clusters.shape[0] == 1 + or classes.shape[0] == clusters.shape[0] == 0 + ): + return 1.0 + # if there is only one class or one cluster return 0.0. + elif classes.shape[0] == 1 or clusters.shape[0] == 1: + return 0.0 + + contingency = contingency_matrix(labels_true, labels_pred, sparse=True) + # Calculate the MI for the two clusterings + mi = mutual_info_score(labels_true, labels_pred, contingency=contingency) + # Calculate the expected value for the mutual information + emi = expected_mutual_information(contingency, n_samples) + # Calculate entropy for each labeling + h_true, h_pred = entropy(labels_true), entropy(labels_pred) + normalizer = _generalized_average(h_true, h_pred, average_method) + denominator = normalizer - emi + # Avoid 0.0 / 0.0 when expectation equals maximum, i.e. a perfect match. + # normalizer should always be >= emi, but because of floating-point + # representation, sometimes emi is slightly larger. Correct this + # by preserving the sign. + if denominator < 0: + denominator = min(denominator, -np.finfo("float64").eps) + else: + denominator = max(denominator, np.finfo("float64").eps) + # The same applies analogously to mi and emi. + numerator = mi - emi + if numerator < 0: + numerator = min(numerator, -np.finfo("float64").eps) + else: + numerator = max(numerator, np.finfo("float64").eps) + return float(numerator / denominator) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + "average_method": [StrOptions({"arithmetic", "max", "min", "geometric"})], + }, + prefer_skip_nested_validation=True, +) +def normalized_mutual_info_score( + labels_true, labels_pred, *, average_method="arithmetic" +): + """Normalized Mutual Information between two clusterings. + + Normalized Mutual Information (NMI) is a normalization of the Mutual + Information (MI) score to scale the results between 0 (no mutual + information) and 1 (perfect correlation). In this function, mutual + information is normalized by some generalized mean of ``H(labels_true)`` + and ``H(labels_pred))``, defined by the `average_method`. + + This measure is not adjusted for chance. Therefore + :func:`adjusted_mutual_info_score` might be preferred. + + This metric is independent of the absolute values of the labels: + a permutation of the class or cluster label values won't change the + score value in any way. + + This metric is furthermore symmetric: switching ``label_true`` with + ``label_pred`` will return the same score value. This can be useful to + measure the agreement of two independent label assignments strategies + on the same dataset when the real ground truth is not known. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : int array-like of shape (n_samples,) + A clustering of the data into disjoint subsets. + + labels_pred : int array-like of shape (n_samples,) + A clustering of the data into disjoint subsets. + + average_method : {'min', 'geometric', 'arithmetic', 'max'}, default='arithmetic' + How to compute the normalizer in the denominator. + + .. versionadded:: 0.20 + + .. versionchanged:: 0.22 + The default value of ``average_method`` changed from 'geometric' to + 'arithmetic'. + + Returns + ------- + nmi : float + Score between 0.0 and 1.0 in normalized nats (based on the natural + logarithm). 1.0 stands for perfectly complete labeling. + + See Also + -------- + v_measure_score : V-Measure (NMI with arithmetic mean option). + adjusted_rand_score : Adjusted Rand Index. + adjusted_mutual_info_score : Adjusted Mutual Information (adjusted + against chance). + + Examples + -------- + + Perfect labelings are both homogeneous and complete, hence have + score 1.0:: + + >>> from sklearn.metrics.cluster import normalized_mutual_info_score + >>> normalized_mutual_info_score([0, 0, 1, 1], [0, 0, 1, 1]) + 1.0 + >>> normalized_mutual_info_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + If classes members are completely split across different clusters, + the assignment is totally in-complete, hence the NMI is null:: + + >>> normalized_mutual_info_score([0, 0, 0, 0], [0, 1, 2, 3]) + 0.0 + """ + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + classes = np.unique(labels_true) + clusters = np.unique(labels_pred) + + # Special limit cases: no clustering since the data is not split. + # It corresponds to both labellings having zero entropy. + # This is a perfect match hence return 1.0. + if ( + classes.shape[0] == clusters.shape[0] == 1 + or classes.shape[0] == clusters.shape[0] == 0 + ): + return 1.0 + + contingency = contingency_matrix(labels_true, labels_pred, sparse=True) + contingency = contingency.astype(np.float64, copy=False) + # Calculate the MI for the two clusterings + mi = mutual_info_score(labels_true, labels_pred, contingency=contingency) + + # At this point mi = 0 can't be a perfect match (the special case of a single + # cluster has been dealt with before). Hence, if mi = 0, the nmi must be 0 whatever + # the normalization. + if mi == 0: + return 0.0 + + # Calculate entropy for each labeling + h_true, h_pred = entropy(labels_true), entropy(labels_pred) + + normalizer = _generalized_average(h_true, h_pred, average_method) + return float(mi / normalizer) + + +@validate_params( + { + "labels_true": ["array-like"], + "labels_pred": ["array-like"], + "sparse": ["boolean", Hidden(StrOptions({"deprecated"}))], + }, + prefer_skip_nested_validation=True, +) +def fowlkes_mallows_score(labels_true, labels_pred, *, sparse="deprecated"): + """Measure the similarity of two clusterings of a set of points. + + .. versionadded:: 0.18 + + The Fowlkes-Mallows index (FMI) is defined as the geometric mean of + the precision and recall:: + + FMI = TP / sqrt((TP + FP) * (TP + FN)) + + Where ``TP`` is the number of **True Positive** (i.e. the number of pairs of + points that belong to the same cluster in both ``labels_true`` and + ``labels_pred``), ``FP`` is the number of **False Positive** (i.e. the + number of pairs of points that belong to the same cluster in + ``labels_pred`` but not in ``labels_true``) and ``FN`` is the number of + **False Negative** (i.e. the number of pairs of points that belong to the + same cluster in ``labels_true`` but not in ``labels_pred``). + + The score ranges from 0 to 1. A high value indicates a good similarity + between two clusters. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + labels_true : array-like of shape (n_samples,), dtype=int + A clustering of the data into disjoint subsets. + + labels_pred : array-like of shape (n_samples,), dtype=int + A clustering of the data into disjoint subsets. + + sparse : bool, default=False + Compute contingency matrix internally with sparse matrix. + + .. deprecated:: 1.7 + The ``sparse`` parameter is deprecated and will be removed in 1.9. It has + no effect. + + Returns + ------- + score : float + The resulting Fowlkes-Mallows score. + + References + ---------- + .. [1] `E. B. Fowkles and C. L. Mallows, 1983. "A method for comparing two + hierarchical clusterings". Journal of the American Statistical + Association + `_ + + .. [2] `Wikipedia entry for the Fowlkes-Mallows Index + `_ + + Examples + -------- + + Perfect labelings are both homogeneous and complete, hence have + score 1.0:: + + >>> from sklearn.metrics.cluster import fowlkes_mallows_score + >>> fowlkes_mallows_score([0, 0, 1, 1], [0, 0, 1, 1]) + 1.0 + >>> fowlkes_mallows_score([0, 0, 1, 1], [1, 1, 0, 0]) + 1.0 + + If classes members are completely split across different clusters, + the assignment is totally random, hence the FMI is null:: + + >>> fowlkes_mallows_score([0, 0, 0, 0], [0, 1, 2, 3]) + 0.0 + """ + # TODO(1.9): remove the sparse parameter + if sparse != "deprecated": + warnings.warn( + "The 'sparse' parameter was deprecated in 1.7 and will be removed in 1.9. " + "It has no effect. Leave it to its default value to silence this warning.", + FutureWarning, + ) + + labels_true, labels_pred = check_clusterings(labels_true, labels_pred) + (n_samples,) = labels_true.shape + + c = contingency_matrix(labels_true, labels_pred, sparse=True) + c = c.astype(np.int64, copy=False) + tk = np.dot(c.data, c.data) - n_samples + pk = np.sum(np.asarray(c.sum(axis=0)).ravel() ** 2) - n_samples + qk = np.sum(np.asarray(c.sum(axis=1)).ravel() ** 2) - n_samples + return float(np.sqrt(tk / pk) * np.sqrt(tk / qk)) if tk != 0.0 else 0.0 + + +@validate_params( + { + "labels": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def entropy(labels): + """Calculate the entropy for a labeling. + + Parameters + ---------- + labels : array-like of shape (n_samples,), dtype=int + The labels. + + Returns + ------- + entropy : float + The entropy for a labeling. + + Notes + ----- + The logarithm used is the natural logarithm (base-e). + """ + xp, is_array_api_compliant, device_ = get_namespace_and_device(labels) + labels_len = labels.shape[0] if is_array_api_compliant else len(labels) + if labels_len == 0: + return 1.0 + + pi = xp.astype(xp.unique_counts(labels)[1], _max_precision_float_dtype(xp, device_)) + + # single cluster => zero entropy + if pi.size == 1: + return 0.0 + + pi_sum = xp.sum(pi) + # log(a / b) should be calculated as log(a) - log(b) for + # possible loss of precision + # Always convert the result as a Python scalar (on CPU) instead of a device + # specific scalar array. + return float(-xp.sum((pi / pi_sum) * (xp.log(pi) - log(pi_sum)))) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py new file mode 100644 index 0000000000000000000000000000000000000000..38cec419e73f778ecdb7bdac89e090a26cdd794a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/_unsupervised.py @@ -0,0 +1,463 @@ +"""Unsupervised evaluation metrics.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import functools +from numbers import Integral + +import numpy as np +from scipy.sparse import issparse + +from ...preprocessing import LabelEncoder +from ...utils import _safe_indexing, check_random_state, check_X_y +from ...utils._array_api import _atol_for_type +from ...utils._param_validation import ( + Interval, + StrOptions, + validate_params, +) +from ..pairwise import _VALID_METRICS, pairwise_distances, pairwise_distances_chunked + + +def check_number_of_labels(n_labels, n_samples): + """Check that number of labels are valid. + + Parameters + ---------- + n_labels : int + Number of labels. + + n_samples : int + Number of samples. + """ + if not 1 < n_labels < n_samples: + raise ValueError( + "Number of labels is %d. Valid values are 2 to n_samples - 1 (inclusive)" + % n_labels + ) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "labels": ["array-like"], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "sample_size": [Interval(Integral, 1, None, closed="left"), None], + "random_state": ["random_state"], + }, + prefer_skip_nested_validation=True, +) +def silhouette_score( + X, labels, *, metric="euclidean", sample_size=None, random_state=None, **kwds +): + """Compute the mean Silhouette Coefficient of all samples. + + The Silhouette Coefficient is calculated using the mean intra-cluster + distance (``a``) and the mean nearest-cluster distance (``b``) for each + sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, + b)``. To clarify, ``b`` is the distance between a sample and the nearest + cluster that the sample is not a part of. + Note that Silhouette Coefficient is only defined if number of labels + is ``2 <= n_labels <= n_samples - 1``. + + This function returns the mean Silhouette Coefficient over all samples. + To obtain the values for each sample, use :func:`silhouette_samples`. + + The best value is 1 and the worst value is -1. Values near 0 indicate + overlapping clusters. Negative values generally indicate that a sample has + been assigned to the wrong cluster, as a different cluster is more similar. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_a, n_samples_a) if metric == \ + "precomputed" or (n_samples_a, n_features) otherwise + An array of pairwise distances between samples, or a feature array. + + labels : array-like of shape (n_samples,) + Predicted labels for each sample. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by :func:`~sklearn.metrics.pairwise_distances`. If ``X`` is + the distance array itself, use ``metric="precomputed"``. + + sample_size : int, default=None + The size of the sample to use when computing the Silhouette Coefficient + on a random subset of the data. + If ``sample_size is None``, no sampling is used. + + random_state : int, RandomState instance or None, default=None + Determines random number generation for selecting a subset of samples. + Used when ``sample_size is not None``. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the distance function. + If using a scipy.spatial.distance metric, the parameters are still + metric dependent. See the scipy docs for usage examples. + + Returns + ------- + silhouette : float + Mean Silhouette Coefficient for all samples. + + References + ---------- + + .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the + Interpretation and Validation of Cluster Analysis". Computational + and Applied Mathematics 20: 53-65. + `_ + + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ + + Examples + -------- + >>> from sklearn.datasets import make_blobs + >>> from sklearn.cluster import KMeans + >>> from sklearn.metrics import silhouette_score + >>> X, y = make_blobs(random_state=42) + >>> kmeans = KMeans(n_clusters=2, random_state=42) + >>> silhouette_score(X, kmeans.fit_predict(X)) + 0.49... + """ + if sample_size is not None: + X, labels = check_X_y(X, labels, accept_sparse=["csc", "csr"]) + random_state = check_random_state(random_state) + indices = random_state.permutation(X.shape[0])[:sample_size] + if metric == "precomputed": + X, labels = X[indices].T[indices].T, labels[indices] + else: + X, labels = X[indices], labels[indices] + return float(np.mean(silhouette_samples(X, labels, metric=metric, **kwds))) + + +def _silhouette_reduce(D_chunk, start, labels, label_freqs): + """Accumulate silhouette statistics for vertical chunk of X. + + Parameters + ---------- + D_chunk : {array-like, sparse matrix} of shape (n_chunk_samples, n_samples) + Precomputed distances for a chunk. If a sparse matrix is provided, + only CSR format is accepted. + start : int + First index in the chunk. + labels : array-like of shape (n_samples,) + Corresponding cluster labels, encoded as {0, ..., n_clusters-1}. + label_freqs : array-like + Distribution of cluster labels in ``labels``. + """ + n_chunk_samples = D_chunk.shape[0] + # accumulate distances from each sample to each cluster + cluster_distances = np.zeros( + (n_chunk_samples, len(label_freqs)), dtype=D_chunk.dtype + ) + + if issparse(D_chunk): + if D_chunk.format != "csr": + raise TypeError( + "Expected CSR matrix. Please pass sparse matrix in CSR format." + ) + for i in range(n_chunk_samples): + indptr = D_chunk.indptr + indices = D_chunk.indices[indptr[i] : indptr[i + 1]] + sample_weights = D_chunk.data[indptr[i] : indptr[i + 1]] + sample_labels = np.take(labels, indices) + cluster_distances[i] += np.bincount( + sample_labels, weights=sample_weights, minlength=len(label_freqs) + ) + else: + for i in range(n_chunk_samples): + sample_weights = D_chunk[i] + sample_labels = labels + cluster_distances[i] += np.bincount( + sample_labels, weights=sample_weights, minlength=len(label_freqs) + ) + + # intra_index selects intra-cluster distances within cluster_distances + end = start + n_chunk_samples + intra_index = (np.arange(n_chunk_samples), labels[start:end]) + # intra_cluster_distances are averaged over cluster size outside this function + intra_cluster_distances = cluster_distances[intra_index] + # of the remaining distances we normalise and extract the minimum + cluster_distances[intra_index] = np.inf + cluster_distances /= label_freqs + inter_cluster_distances = cluster_distances.min(axis=1) + return intra_cluster_distances, inter_cluster_distances + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "labels": ["array-like"], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + }, + prefer_skip_nested_validation=True, +) +def silhouette_samples(X, labels, *, metric="euclidean", **kwds): + """Compute the Silhouette Coefficient for each sample. + + The Silhouette Coefficient is a measure of how well samples are clustered + with samples that are similar to themselves. Clustering models with a high + Silhouette Coefficient are said to be dense, where samples in the same + cluster are similar to each other, and well separated, where samples in + different clusters are not very similar to each other. + + The Silhouette Coefficient is calculated using the mean intra-cluster + distance (``a``) and the mean nearest-cluster distance (``b``) for each + sample. The Silhouette Coefficient for a sample is ``(b - a) / max(a, + b)``. + Note that Silhouette Coefficient is only defined if number of labels + is 2 ``<= n_labels <= n_samples - 1``. + + This function returns the Silhouette Coefficient for each sample. + + The best value is 1 and the worst value is -1. Values near 0 indicate + overlapping clusters. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_a, n_samples_a) if metric == \ + "precomputed" or (n_samples_a, n_features) otherwise + An array of pairwise distances between samples, or a feature array. If + a sparse matrix is provided, CSR format should be favoured avoiding + an additional copy. + + labels : array-like of shape (n_samples,) + Label values for each sample. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by :func:`~sklearn.metrics.pairwise_distances`. + If ``X`` is the distance array itself, use "precomputed" as the metric. + Precomputed distance matrices must have 0 along the diagonal. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the distance function. + If using a ``scipy.spatial.distance`` metric, the parameters are still + metric dependent. See the scipy docs for usage examples. + + Returns + ------- + silhouette : array-like of shape (n_samples,) + Silhouette Coefficients for each sample. + + References + ---------- + + .. [1] `Peter J. Rousseeuw (1987). "Silhouettes: a Graphical Aid to the + Interpretation and Validation of Cluster Analysis". Computational + and Applied Mathematics 20: 53-65. + `_ + + .. [2] `Wikipedia entry on the Silhouette Coefficient + `_ + + Examples + -------- + >>> from sklearn.metrics import silhouette_samples + >>> from sklearn.datasets import make_blobs + >>> from sklearn.cluster import KMeans + >>> X, y = make_blobs(n_samples=50, random_state=42) + >>> kmeans = KMeans(n_clusters=3, random_state=42) + >>> labels = kmeans.fit_predict(X) + >>> silhouette_samples(X, labels) + array([...]) + """ + X, labels = check_X_y(X, labels, accept_sparse=["csr"]) + + # Check for non-zero diagonal entries in precomputed distance matrix + if metric == "precomputed": + error_msg = ValueError( + "The precomputed distance matrix contains non-zero " + "elements on the diagonal. Use np.fill_diagonal(X, 0)." + ) + if X.dtype.kind == "f": + atol = _atol_for_type(X.dtype) + + if np.any(np.abs(X.diagonal()) > atol): + raise error_msg + elif np.any(X.diagonal() != 0): # integral dtype + raise error_msg + + le = LabelEncoder() + labels = le.fit_transform(labels) + n_samples = len(labels) + label_freqs = np.bincount(labels) + check_number_of_labels(len(le.classes_), n_samples) + + kwds["metric"] = metric + reduce_func = functools.partial( + _silhouette_reduce, labels=labels, label_freqs=label_freqs + ) + results = zip(*pairwise_distances_chunked(X, reduce_func=reduce_func, **kwds)) + intra_clust_dists, inter_clust_dists = results + intra_clust_dists = np.concatenate(intra_clust_dists) + inter_clust_dists = np.concatenate(inter_clust_dists) + + denom = (label_freqs - 1).take(labels, mode="clip") + with np.errstate(divide="ignore", invalid="ignore"): + intra_clust_dists /= denom + + sil_samples = inter_clust_dists - intra_clust_dists + with np.errstate(divide="ignore", invalid="ignore"): + sil_samples /= np.maximum(intra_clust_dists, inter_clust_dists) + # nan values are for clusters of size 1, and should be 0 + return np.nan_to_num(sil_samples) + + +@validate_params( + { + "X": ["array-like"], + "labels": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def calinski_harabasz_score(X, labels): + """Compute the Calinski and Harabasz score. + + It is also known as the Variance Ratio Criterion. + + The score is defined as ratio of the sum of between-cluster dispersion and + of within-cluster dispersion. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + A list of ``n_features``-dimensional data points. Each row corresponds + to a single data point. + + labels : array-like of shape (n_samples,) + Predicted labels for each sample. + + Returns + ------- + score : float + The resulting Calinski-Harabasz score. + + References + ---------- + .. [1] `T. Calinski and J. Harabasz, 1974. "A dendrite method for cluster + analysis". Communications in Statistics + `_ + + Examples + -------- + >>> from sklearn.datasets import make_blobs + >>> from sklearn.cluster import KMeans + >>> from sklearn.metrics import calinski_harabasz_score + >>> X, _ = make_blobs(random_state=0) + >>> kmeans = KMeans(n_clusters=3, random_state=0,).fit(X) + >>> calinski_harabasz_score(X, kmeans.labels_) + 114.8... + """ + X, labels = check_X_y(X, labels) + le = LabelEncoder() + labels = le.fit_transform(labels) + + n_samples, _ = X.shape + n_labels = len(le.classes_) + + check_number_of_labels(n_labels, n_samples) + + extra_disp, intra_disp = 0.0, 0.0 + mean = np.mean(X, axis=0) + for k in range(n_labels): + cluster_k = X[labels == k] + mean_k = np.mean(cluster_k, axis=0) + extra_disp += len(cluster_k) * np.sum((mean_k - mean) ** 2) + intra_disp += np.sum((cluster_k - mean_k) ** 2) + + return float( + 1.0 + if intra_disp == 0.0 + else extra_disp * (n_samples - n_labels) / (intra_disp * (n_labels - 1.0)) + ) + + +@validate_params( + { + "X": ["array-like"], + "labels": ["array-like"], + }, + prefer_skip_nested_validation=True, +) +def davies_bouldin_score(X, labels): + """Compute the Davies-Bouldin score. + + The score is defined as the average similarity measure of each cluster with + its most similar cluster, where similarity is the ratio of within-cluster + distances to between-cluster distances. Thus, clusters which are farther + apart and less dispersed will result in a better score. + + The minimum score is zero, with lower values indicating better clustering. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.20 + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + A list of ``n_features``-dimensional data points. Each row corresponds + to a single data point. + + labels : array-like of shape (n_samples,) + Predicted labels for each sample. + + Returns + ------- + score: float + The resulting Davies-Bouldin score. + + References + ---------- + .. [1] Davies, David L.; Bouldin, Donald W. (1979). + `"A Cluster Separation Measure" + `__. + IEEE Transactions on Pattern Analysis and Machine Intelligence. + PAMI-1 (2): 224-227 + + Examples + -------- + >>> from sklearn.metrics import davies_bouldin_score + >>> X = [[0, 1], [1, 1], [3, 4]] + >>> labels = [0, 0, 1] + >>> davies_bouldin_score(X, labels) + 0.12... + """ + X, labels = check_X_y(X, labels) + le = LabelEncoder() + labels = le.fit_transform(labels) + n_samples, _ = X.shape + n_labels = len(le.classes_) + check_number_of_labels(n_labels, n_samples) + + intra_dists = np.zeros(n_labels) + centroids = np.zeros((n_labels, len(X[0])), dtype=float) + for k in range(n_labels): + cluster_k = _safe_indexing(X, labels == k) + centroid = cluster_k.mean(axis=0) + centroids[k] = centroid + intra_dists[k] = np.average(pairwise_distances(cluster_k, [centroid])) + + centroid_distances = pairwise_distances(centroids) + + if np.allclose(intra_dists, 0) or np.allclose(centroid_distances, 0): + return 0.0 + + centroid_distances[centroid_distances == 0] = np.inf + combined_intra_dists = intra_dists[:, None] + intra_dists + scores = np.max(combined_intra_dists / centroid_distances, axis=1) + return float(np.mean(scores)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..5f25296c7540f289dc74eba4a97ddac5fad9af90 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/meson.build @@ -0,0 +1,6 @@ +py.extension_module( + '_expected_mutual_info_fast', + cython_gen.process('_expected_mutual_info_fast.pyx'), + subdir: 'sklearn/metrics/cluster', + install: true +) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_bicluster.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_bicluster.py new file mode 100644 index 0000000000000000000000000000000000000000..53f7805100a1313709d1d8868d45071b3066f836 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_bicluster.py @@ -0,0 +1,56 @@ +"""Testing for bicluster metrics module""" + +import numpy as np + +from sklearn.metrics import consensus_score +from sklearn.metrics.cluster._bicluster import _jaccard +from sklearn.utils._testing import assert_almost_equal + + +def test_jaccard(): + a1 = np.array([True, True, False, False]) + a2 = np.array([True, True, True, True]) + a3 = np.array([False, True, True, False]) + a4 = np.array([False, False, True, True]) + + assert _jaccard(a1, a1, a1, a1) == 1 + assert _jaccard(a1, a1, a2, a2) == 0.25 + assert _jaccard(a1, a1, a3, a3) == 1.0 / 7 + assert _jaccard(a1, a1, a4, a4) == 0 + + +def test_consensus_score(): + a = [[True, True, False, False], [False, False, True, True]] + b = a[::-1] + + assert consensus_score((a, a), (a, a)) == 1 + assert consensus_score((a, a), (b, b)) == 1 + assert consensus_score((a, b), (a, b)) == 1 + assert consensus_score((a, b), (b, a)) == 1 + + assert consensus_score((a, a), (b, a)) == 0 + assert consensus_score((a, a), (a, b)) == 0 + assert consensus_score((b, b), (a, b)) == 0 + assert consensus_score((b, b), (b, a)) == 0 + + +def test_consensus_score_issue2445(): + """Different number of biclusters in A and B""" + a_rows = np.array( + [ + [True, True, False, False], + [False, False, True, True], + [False, False, False, True], + ] + ) + a_cols = np.array( + [ + [True, True, False, False], + [False, False, True, True], + [False, False, False, True], + ] + ) + idx = [0, 2] + s = consensus_score((a_rows, a_cols), (a_rows[idx], a_cols[idx])) + # B contains 2 of the 3 biclusters in A, so score should be 2/3 + assert_almost_equal(s, 2.0 / 3.0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a73670fbffce40eabaca55fc177648938cdccb26 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_common.py @@ -0,0 +1,234 @@ +from functools import partial +from itertools import chain + +import numpy as np +import pytest + +from sklearn.metrics.cluster import ( + adjusted_mutual_info_score, + adjusted_rand_score, + calinski_harabasz_score, + completeness_score, + davies_bouldin_score, + fowlkes_mallows_score, + homogeneity_score, + mutual_info_score, + normalized_mutual_info_score, + rand_score, + silhouette_score, + v_measure_score, +) +from sklearn.utils._testing import assert_allclose + +# Dictionaries of metrics +# ------------------------ +# The goal of having those dictionaries is to have an easy way to call a +# particular metric and associate a name to each function: +# - SUPERVISED_METRICS: all supervised cluster metrics - (when given a +# ground truth value) +# - UNSUPERVISED_METRICS: all unsupervised cluster metrics +# +# Those dictionaries will be used to test systematically some invariance +# properties, e.g. invariance toward several input layout. +# + +SUPERVISED_METRICS = { + "adjusted_mutual_info_score": adjusted_mutual_info_score, + "adjusted_rand_score": adjusted_rand_score, + "rand_score": rand_score, + "completeness_score": completeness_score, + "homogeneity_score": homogeneity_score, + "mutual_info_score": mutual_info_score, + "normalized_mutual_info_score": normalized_mutual_info_score, + "v_measure_score": v_measure_score, + "fowlkes_mallows_score": fowlkes_mallows_score, +} + +UNSUPERVISED_METRICS = { + "silhouette_score": silhouette_score, + "silhouette_manhattan": partial(silhouette_score, metric="manhattan"), + "calinski_harabasz_score": calinski_harabasz_score, + "davies_bouldin_score": davies_bouldin_score, +} + +# Lists of metrics with common properties +# --------------------------------------- +# Lists of metrics with common properties are used to test systematically some +# functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics +# that are symmetric with respect to their input argument y_true and y_pred. +# +# -------------------------------------------------------------------- +# Symmetric with respect to their input arguments y_true and y_pred. +# Symmetric metrics only apply to supervised clusters. +SYMMETRIC_METRICS = [ + "adjusted_rand_score", + "rand_score", + "v_measure_score", + "mutual_info_score", + "adjusted_mutual_info_score", + "normalized_mutual_info_score", + "fowlkes_mallows_score", +] + +NON_SYMMETRIC_METRICS = ["homogeneity_score", "completeness_score"] + +# Metrics whose upper bound is 1 +NORMALIZED_METRICS = [ + "adjusted_rand_score", + "rand_score", + "homogeneity_score", + "completeness_score", + "v_measure_score", + "adjusted_mutual_info_score", + "fowlkes_mallows_score", + "normalized_mutual_info_score", +] + + +rng = np.random.RandomState(0) +y1 = rng.randint(3, size=30) +y2 = rng.randint(3, size=30) + + +def test_symmetric_non_symmetric_union(): + assert sorted(SYMMETRIC_METRICS + NON_SYMMETRIC_METRICS) == sorted( + SUPERVISED_METRICS + ) + + +@pytest.mark.parametrize( + "metric_name, y1, y2", [(name, y1, y2) for name in SYMMETRIC_METRICS] +) +def test_symmetry(metric_name, y1, y2): + metric = SUPERVISED_METRICS[metric_name] + assert metric(y1, y2) == pytest.approx(metric(y2, y1)) + + +@pytest.mark.parametrize( + "metric_name, y1, y2", [(name, y1, y2) for name in NON_SYMMETRIC_METRICS] +) +def test_non_symmetry(metric_name, y1, y2): + metric = SUPERVISED_METRICS[metric_name] + assert metric(y1, y2) != pytest.approx(metric(y2, y1)) + + +@pytest.mark.parametrize("metric_name", NORMALIZED_METRICS) +def test_normalized_output(metric_name): + upper_bound_1 = [0, 0, 0, 1, 1, 1] + upper_bound_2 = [0, 0, 0, 1, 1, 1] + metric = SUPERVISED_METRICS[metric_name] + assert metric([0, 0, 0, 1, 1], [0, 0, 0, 1, 2]) > 0.0 + assert metric([0, 0, 1, 1, 2], [0, 0, 1, 1, 1]) > 0.0 + assert metric([0, 0, 0, 1, 2], [0, 1, 1, 1, 1]) < 1.0 + assert metric([0, 0, 0, 1, 2], [0, 1, 1, 1, 1]) < 1.0 + assert metric(upper_bound_1, upper_bound_2) == pytest.approx(1.0) + + lower_bound_1 = [0, 0, 0, 0, 0, 0] + lower_bound_2 = [0, 1, 2, 3, 4, 5] + score = np.array( + [metric(lower_bound_1, lower_bound_2), metric(lower_bound_2, lower_bound_1)] + ) + assert not (score < 0).any() + + +@pytest.mark.parametrize("metric_name", chain(SUPERVISED_METRICS, UNSUPERVISED_METRICS)) +def test_permute_labels(metric_name): + # All clustering metrics do not change score due to permutations of labels + # that is when 0 and 1 exchanged. + y_label = np.array([0, 0, 0, 1, 1, 0, 1]) + y_pred = np.array([1, 0, 1, 0, 1, 1, 0]) + if metric_name in SUPERVISED_METRICS: + metric = SUPERVISED_METRICS[metric_name] + score_1 = metric(y_pred, y_label) + assert_allclose(score_1, metric(1 - y_pred, y_label)) + assert_allclose(score_1, metric(1 - y_pred, 1 - y_label)) + assert_allclose(score_1, metric(y_pred, 1 - y_label)) + else: + metric = UNSUPERVISED_METRICS[metric_name] + X = np.random.randint(10, size=(7, 10)) + score_1 = metric(X, y_pred) + assert_allclose(score_1, metric(X, 1 - y_pred)) + + +@pytest.mark.parametrize("metric_name", chain(SUPERVISED_METRICS, UNSUPERVISED_METRICS)) +# For all clustering metrics Input parameters can be both +# in the form of arrays lists, positive, negative or string +def test_format_invariance(metric_name): + y_true = [0, 0, 0, 0, 1, 1, 1, 1] + y_pred = [0, 1, 2, 3, 4, 5, 6, 7] + + def generate_formats(y): + y = np.array(y) + yield y, "array of ints" + yield y.tolist(), "list of ints" + yield [str(x) + "-a" for x in y.tolist()], "list of strs" + yield ( + np.array([str(x) + "-a" for x in y.tolist()], dtype=object), + "array of strs", + ) + yield y - 1, "including negative ints" + yield y + 1, "strictly positive ints" + + if metric_name in SUPERVISED_METRICS: + metric = SUPERVISED_METRICS[metric_name] + score_1 = metric(y_true, y_pred) + y_true_gen = generate_formats(y_true) + y_pred_gen = generate_formats(y_pred) + for (y_true_fmt, fmt_name), (y_pred_fmt, _) in zip(y_true_gen, y_pred_gen): + assert score_1 == metric(y_true_fmt, y_pred_fmt) + else: + metric = UNSUPERVISED_METRICS[metric_name] + X = np.random.randint(10, size=(8, 10)) + score_1 = metric(X, y_true) + assert score_1 == metric(X.astype(float), y_true) + y_true_gen = generate_formats(y_true) + for y_true_fmt, fmt_name in y_true_gen: + assert score_1 == metric(X, y_true_fmt) + + +@pytest.mark.parametrize("metric", SUPERVISED_METRICS.values()) +def test_single_sample(metric): + # only the supervised metrics support single sample + for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]: + metric([i], [j]) + + +@pytest.mark.parametrize( + "metric_name, metric_func", dict(SUPERVISED_METRICS, **UNSUPERVISED_METRICS).items() +) +def test_inf_nan_input(metric_name, metric_func): + if metric_name in SUPERVISED_METRICS: + invalids = [ + ([0, 1], [np.inf, np.inf]), + ([0, 1], [np.nan, np.nan]), + ([0, 1], [np.nan, np.inf]), + ] + 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=r"contains (NaN|infinity)"): + for args in invalids: + metric_func(*args) + + +@pytest.mark.parametrize("name", chain(SUPERVISED_METRICS, UNSUPERVISED_METRICS)) +def test_returned_value_consistency(name): + """Ensure that the returned values of all metrics are consistent. + + It can only be a float. It should not be a numpy float64 or float32. + """ + + rng = np.random.RandomState(0) + X = rng.randint(10, size=(20, 10)) + labels_true = rng.randint(0, 3, size=(20,)) + labels_pred = rng.randint(0, 3, size=(20,)) + + if name in SUPERVISED_METRICS: + metric = SUPERVISED_METRICS[name] + score = metric(labels_true, labels_pred) + else: + metric = UNSUPERVISED_METRICS[name] + score = metric(X, labels_pred) + + assert isinstance(score, float) + assert not isinstance(score, (np.float64, np.float32)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_supervised.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_supervised.py new file mode 100644 index 0000000000000000000000000000000000000000..7421b726ebe677a6845167b3b268614891b38013 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_supervised.py @@ -0,0 +1,522 @@ +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_allclose, assert_array_almost_equal, assert_array_equal + +from sklearn.base import config_context +from sklearn.metrics.cluster import ( + adjusted_mutual_info_score, + adjusted_rand_score, + completeness_score, + contingency_matrix, + entropy, + expected_mutual_information, + fowlkes_mallows_score, + homogeneity_completeness_v_measure, + homogeneity_score, + mutual_info_score, + normalized_mutual_info_score, + pair_confusion_matrix, + rand_score, + v_measure_score, +) +from sklearn.metrics.cluster._supervised import _generalized_average, check_clusterings +from sklearn.utils import assert_all_finite +from sklearn.utils._array_api import ( + _get_namespace_device_dtype_ids, + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._testing import _array_api_for_tests, assert_almost_equal + +score_funcs = [ + adjusted_rand_score, + rand_score, + homogeneity_score, + completeness_score, + v_measure_score, + adjusted_mutual_info_score, + normalized_mutual_info_score, +] + + +@pytest.mark.parametrize("score_func", score_funcs) +def test_error_messages_on_wrong_input(score_func): + expected = r"Found input variables with inconsistent numbers of samples: \[2, 3\]" + with pytest.raises(ValueError, match=expected): + score_func([0, 1], [1, 1, 1]) + + expected = r"labels_true must be 1D: shape is \(2" + with pytest.raises(ValueError, match=expected): + score_func([[0, 1], [1, 0]], [1, 1, 1]) + + expected = r"labels_pred must be 1D: shape is \(2" + with pytest.raises(ValueError, match=expected): + score_func([0, 1, 0], [[1, 1], [0, 0]]) + + +def test_generalized_average(): + a, b = 1, 2 + methods = ["min", "geometric", "arithmetic", "max"] + means = [_generalized_average(a, b, method) for method in methods] + assert means[0] <= means[1] <= means[2] <= means[3] + c, d = 12, 12 + means = [_generalized_average(c, d, method) for method in methods] + assert means[0] == means[1] == means[2] == means[3] + + +@pytest.mark.parametrize("score_func", score_funcs) +def test_perfect_matches(score_func): + assert score_func([], []) == pytest.approx(1.0) + assert score_func([0], [1]) == pytest.approx(1.0) + assert score_func([0, 0, 0], [0, 0, 0]) == pytest.approx(1.0) + assert score_func([0, 1, 0], [42, 7, 42]) == pytest.approx(1.0) + assert score_func([0.0, 1.0, 0.0], [42.0, 7.0, 42.0]) == pytest.approx(1.0) + assert score_func([0.0, 1.0, 2.0], [42.0, 7.0, 2.0]) == pytest.approx(1.0) + assert score_func([0, 1, 2], [42, 7, 2]) == pytest.approx(1.0) + + +@pytest.mark.parametrize( + "score_func", + [ + normalized_mutual_info_score, + adjusted_mutual_info_score, + ], +) +@pytest.mark.parametrize("average_method", ["min", "geometric", "arithmetic", "max"]) +def test_perfect_matches_with_changing_means(score_func, average_method): + assert score_func([], [], average_method=average_method) == pytest.approx(1.0) + assert score_func([0], [1], average_method=average_method) == pytest.approx(1.0) + assert score_func( + [0, 0, 0], [0, 0, 0], average_method=average_method + ) == pytest.approx(1.0) + assert score_func( + [0, 1, 0], [42, 7, 42], average_method=average_method + ) == pytest.approx(1.0) + assert score_func( + [0.0, 1.0, 0.0], [42.0, 7.0, 42.0], average_method=average_method + ) == pytest.approx(1.0) + assert score_func( + [0.0, 1.0, 2.0], [42.0, 7.0, 2.0], average_method=average_method + ) == pytest.approx(1.0) + assert score_func( + [0, 1, 2], [42, 7, 2], average_method=average_method + ) == pytest.approx(1.0) + # Non-regression tests for: https://github.com/scikit-learn/scikit-learn/issues/30950 + assert score_func([0, 1], [0, 1], average_method=average_method) == pytest.approx( + 1.0 + ) + assert score_func( + [0, 1, 2, 3], [0, 1, 2, 3], average_method=average_method + ) == pytest.approx(1.0) + + +def test_homogeneous_but_not_complete_labeling(): + # homogeneous but not complete clustering + h, c, v = homogeneity_completeness_v_measure([0, 0, 0, 1, 1, 1], [0, 0, 0, 1, 2, 2]) + assert_almost_equal(h, 1.00, 2) + assert_almost_equal(c, 0.69, 2) + assert_almost_equal(v, 0.81, 2) + + +def test_complete_but_not_homogeneous_labeling(): + # complete but not homogeneous clustering + h, c, v = homogeneity_completeness_v_measure([0, 0, 1, 1, 2, 2], [0, 0, 1, 1, 1, 1]) + assert_almost_equal(h, 0.58, 2) + assert_almost_equal(c, 1.00, 2) + assert_almost_equal(v, 0.73, 2) + + +def test_not_complete_and_not_homogeneous_labeling(): + # neither complete nor homogeneous but not so bad either + h, c, v = homogeneity_completeness_v_measure([0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2]) + assert_almost_equal(h, 0.67, 2) + assert_almost_equal(c, 0.42, 2) + assert_almost_equal(v, 0.52, 2) + + +def test_beta_parameter(): + # test for when beta passed to + # homogeneity_completeness_v_measure + # and v_measure_score + beta_test = 0.2 + h_test = 0.67 + c_test = 0.42 + v_test = (1 + beta_test) * h_test * c_test / (beta_test * h_test + c_test) + + h, c, v = homogeneity_completeness_v_measure( + [0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2], beta=beta_test + ) + assert_almost_equal(h, h_test, 2) + assert_almost_equal(c, c_test, 2) + assert_almost_equal(v, v_test, 2) + + v = v_measure_score([0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2], beta=beta_test) + assert_almost_equal(v, v_test, 2) + + +def test_non_consecutive_labels(): + # regression tests for labels with gaps + h, c, v = homogeneity_completeness_v_measure([0, 0, 0, 2, 2, 2], [0, 1, 0, 1, 2, 2]) + assert_almost_equal(h, 0.67, 2) + assert_almost_equal(c, 0.42, 2) + assert_almost_equal(v, 0.52, 2) + + h, c, v = homogeneity_completeness_v_measure([0, 0, 0, 1, 1, 1], [0, 4, 0, 4, 2, 2]) + assert_almost_equal(h, 0.67, 2) + assert_almost_equal(c, 0.42, 2) + assert_almost_equal(v, 0.52, 2) + + ari_1 = adjusted_rand_score([0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2]) + ari_2 = adjusted_rand_score([0, 0, 0, 1, 1, 1], [0, 4, 0, 4, 2, 2]) + assert_almost_equal(ari_1, 0.24, 2) + assert_almost_equal(ari_2, 0.24, 2) + + ri_1 = rand_score([0, 0, 0, 1, 1, 1], [0, 1, 0, 1, 2, 2]) + ri_2 = rand_score([0, 0, 0, 1, 1, 1], [0, 4, 0, 4, 2, 2]) + assert_almost_equal(ri_1, 0.66, 2) + assert_almost_equal(ri_2, 0.66, 2) + + +def uniform_labelings_scores(score_func, n_samples, k_range, n_runs=10, seed=42): + # Compute score for random uniform cluster labelings + random_labels = np.random.RandomState(seed).randint + scores = np.zeros((len(k_range), n_runs)) + for i, k in enumerate(k_range): + for j in range(n_runs): + labels_a = random_labels(low=0, high=k, size=n_samples) + labels_b = random_labels(low=0, high=k, size=n_samples) + scores[i, j] = score_func(labels_a, labels_b) + return scores + + +def test_adjustment_for_chance(): + # Check that adjusted scores are almost zero on random labels + n_clusters_range = [2, 10, 50, 90] + n_samples = 100 + n_runs = 10 + + scores = uniform_labelings_scores( + adjusted_rand_score, n_samples, n_clusters_range, n_runs + ) + + max_abs_scores = np.abs(scores).max(axis=1) + assert_array_almost_equal(max_abs_scores, [0.02, 0.03, 0.03, 0.02], 2) + + +def test_adjusted_mutual_info_score(): + # Compute the Adjusted Mutual Information and test against known values + labels_a = np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]) + labels_b = np.array([1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 3, 1, 3, 3, 3, 2, 2]) + # Mutual information + mi = mutual_info_score(labels_a, labels_b) + assert_almost_equal(mi, 0.41022, 5) + # with provided sparse contingency + C = contingency_matrix(labels_a, labels_b, sparse=True) + mi = mutual_info_score(labels_a, labels_b, contingency=C) + assert_almost_equal(mi, 0.41022, 5) + # with provided dense contingency + C = contingency_matrix(labels_a, labels_b) + mi = mutual_info_score(labels_a, labels_b, contingency=C) + assert_almost_equal(mi, 0.41022, 5) + # Expected mutual information + n_samples = C.sum() + emi = expected_mutual_information(C, n_samples) + assert_almost_equal(emi, 0.15042, 5) + # Adjusted mutual information + ami = adjusted_mutual_info_score(labels_a, labels_b) + assert_almost_equal(ami, 0.27821, 5) + ami = adjusted_mutual_info_score([1, 1, 2, 2], [2, 2, 3, 3]) + assert ami == pytest.approx(1.0) + # Test with a very large array + a110 = np.array([list(labels_a) * 110]).flatten() + b110 = np.array([list(labels_b) * 110]).flatten() + ami = adjusted_mutual_info_score(a110, b110) + assert_almost_equal(ami, 0.38, 2) + + +def test_expected_mutual_info_overflow(): + # Test for regression where contingency cell exceeds 2**16 + # leading to overflow in np.outer, resulting in EMI > 1 + assert expected_mutual_information(np.array([[70000]]), 70000) <= 1 + + +def test_int_overflow_mutual_info_fowlkes_mallows_score(): + # Test overflow in mutual_info_classif and fowlkes_mallows_score + x = np.array( + [1] * (52632 + 2529) + + [2] * (14660 + 793) + + [3] * (3271 + 204) + + [4] * (814 + 39) + + [5] * (316 + 20) + ) + y = np.array( + [0] * 52632 + + [1] * 2529 + + [0] * 14660 + + [1] * 793 + + [0] * 3271 + + [1] * 204 + + [0] * 814 + + [1] * 39 + + [0] * 316 + + [1] * 20 + ) + + assert_all_finite(mutual_info_score(x, y)) + assert_all_finite(fowlkes_mallows_score(x, y)) + + +def test_entropy(): + assert_almost_equal(entropy([0, 0, 42.0]), 0.6365141, 5) + assert_almost_equal(entropy([]), 1) + assert entropy([1, 1, 1, 1]) == 0 + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", + yield_namespace_device_dtype_combinations(), + ids=_get_namespace_device_dtype_ids, +) +def test_entropy_array_api(array_namespace, device, dtype_name): + xp = _array_api_for_tests(array_namespace, device) + float_labels = xp.asarray(np.asarray([0, 0, 42.0], dtype=dtype_name), device=device) + empty_int32_labels = xp.asarray([], dtype=xp.int32, device=device) + int_labels = xp.asarray([1, 1, 1, 1], device=device) + with config_context(array_api_dispatch=True): + assert entropy(float_labels) == pytest.approx(0.6365141, abs=1e-5) + assert entropy(empty_int32_labels) == 1 + assert entropy(int_labels) == 0 + + +def test_contingency_matrix(): + labels_a = np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]) + labels_b = np.array([1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 3, 1, 3, 3, 3, 2, 2]) + C = contingency_matrix(labels_a, labels_b) + C2 = np.histogram2d(labels_a, labels_b, bins=(np.arange(1, 5), np.arange(1, 5)))[0] + assert_array_almost_equal(C, C2) + C = contingency_matrix(labels_a, labels_b, eps=0.1) + assert_array_almost_equal(C, C2 + 0.1) + + +def test_contingency_matrix_sparse(): + labels_a = np.array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]) + labels_b = np.array([1, 1, 1, 1, 2, 1, 2, 2, 2, 2, 3, 1, 3, 3, 3, 2, 2]) + C = contingency_matrix(labels_a, labels_b) + C_sparse = contingency_matrix(labels_a, labels_b, sparse=True).toarray() + assert_array_almost_equal(C, C_sparse) + with pytest.raises(ValueError, match="Cannot set 'eps' when sparse=True"): + contingency_matrix(labels_a, labels_b, eps=1e-10, sparse=True) + + +def test_exactly_zero_info_score(): + # Check numerical stability when information is exactly zero + for i in np.logspace(1, 4, 4).astype(int): + labels_a, labels_b = (np.ones(i, dtype=int), np.arange(i, dtype=int)) + assert normalized_mutual_info_score(labels_a, labels_b) == pytest.approx(0.0) + assert v_measure_score(labels_a, labels_b) == pytest.approx(0.0) + assert adjusted_mutual_info_score(labels_a, labels_b) == 0.0 + assert normalized_mutual_info_score(labels_a, labels_b) == pytest.approx(0.0) + for method in ["min", "geometric", "arithmetic", "max"]: + assert ( + adjusted_mutual_info_score(labels_a, labels_b, average_method=method) + == 0.0 + ) + assert normalized_mutual_info_score( + labels_a, labels_b, average_method=method + ) == pytest.approx(0.0) + + +def test_v_measure_and_mutual_information(seed=36): + # Check relation between v_measure, entropy and mutual information + for i in np.logspace(1, 4, 4).astype(int): + random_state = np.random.RandomState(seed) + labels_a, labels_b = ( + random_state.randint(0, 10, i), + random_state.randint(0, 10, i), + ) + assert_almost_equal( + v_measure_score(labels_a, labels_b), + 2.0 + * mutual_info_score(labels_a, labels_b) + / (entropy(labels_a) + entropy(labels_b)), + 0, + ) + avg = "arithmetic" + assert_almost_equal( + v_measure_score(labels_a, labels_b), + normalized_mutual_info_score(labels_a, labels_b, average_method=avg), + ) + + +def test_fowlkes_mallows_score(): + # General case + score = fowlkes_mallows_score([0, 0, 0, 1, 1, 1], [0, 0, 1, 1, 2, 2]) + assert_almost_equal(score, 4.0 / np.sqrt(12.0 * 6.0)) + + # Perfect match but where the label names changed + perfect_score = fowlkes_mallows_score([0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0]) + assert_almost_equal(perfect_score, 1.0) + + # Worst case + worst_score = fowlkes_mallows_score([0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5]) + assert_almost_equal(worst_score, 0.0) + + +def test_fowlkes_mallows_score_properties(): + # handcrafted example + labels_a = np.array([0, 0, 0, 1, 1, 2]) + labels_b = np.array([1, 1, 2, 2, 0, 0]) + expected = 1.0 / np.sqrt((1.0 + 3.0) * (1.0 + 2.0)) + # FMI = TP / sqrt((TP + FP) * (TP + FN)) + + score_original = fowlkes_mallows_score(labels_a, labels_b) + assert_almost_equal(score_original, expected) + + # symmetric property + score_symmetric = fowlkes_mallows_score(labels_b, labels_a) + assert_almost_equal(score_symmetric, expected) + + # permutation property + score_permuted = fowlkes_mallows_score((labels_a + 1) % 3, labels_b) + assert_almost_equal(score_permuted, expected) + + # symmetric and permutation(both together) + score_both = fowlkes_mallows_score(labels_b, (labels_a + 2) % 3) + assert_almost_equal(score_both, expected) + + +@pytest.mark.parametrize( + "labels_true, labels_pred", + [ + (["a"] * 6, [1, 1, 0, 0, 1, 1]), + ([1] * 6, [1, 1, 0, 0, 1, 1]), + ([1, 1, 0, 0, 1, 1], ["a"] * 6), + ([1, 1, 0, 0, 1, 1], [1] * 6), + (["a"] * 6, ["a"] * 6), + ], +) +def test_mutual_info_score_positive_constant_label(labels_true, labels_pred): + # Check that MI = 0 when one or both labelling are constant + # non-regression test for #16355 + assert mutual_info_score(labels_true, labels_pred) == 0 + + +def test_check_clustering_error(): + # Test warning message for continuous values + rng = np.random.RandomState(42) + noise = rng.rand(500) + wavelength = np.linspace(0.01, 1, 500) * 1e-6 + msg = ( + "Clustering metrics expects discrete values but received " + "continuous values for label, and continuous values for " + "target" + ) + + with pytest.warns(UserWarning, match=msg): + check_clusterings(wavelength, noise) + + +def test_pair_confusion_matrix_fully_dispersed(): + # edge case: every element is its own cluster + N = 100 + clustering1 = list(range(N)) + clustering2 = clustering1 + expected = np.array([[N * (N - 1), 0], [0, 0]]) + assert_array_equal(pair_confusion_matrix(clustering1, clustering2), expected) + + +def test_pair_confusion_matrix_single_cluster(): + # edge case: only one cluster + N = 100 + clustering1 = np.zeros((N,)) + clustering2 = clustering1 + expected = np.array([[0, 0], [0, N * (N - 1)]]) + assert_array_equal(pair_confusion_matrix(clustering1, clustering2), expected) + + +def test_pair_confusion_matrix(): + # regular case: different non-trivial clusterings + n = 10 + N = n**2 + clustering1 = np.hstack([[i + 1] * n for i in range(n)]) + clustering2 = np.hstack([[i + 1] * (n + 1) for i in range(n)])[:N] + # basic quadratic implementation + expected = np.zeros(shape=(2, 2), dtype=np.int64) + for i in range(len(clustering1)): + for j in range(len(clustering2)): + if i != j: + same_cluster_1 = int(clustering1[i] == clustering1[j]) + same_cluster_2 = int(clustering2[i] == clustering2[j]) + expected[same_cluster_1, same_cluster_2] += 1 + assert_array_equal(pair_confusion_matrix(clustering1, clustering2), expected) + + +@pytest.mark.parametrize( + "clustering1, clustering2", + [(list(range(100)), list(range(100))), (np.zeros((100,)), np.zeros((100,)))], +) +def test_rand_score_edge_cases(clustering1, clustering2): + # edge case 1: every element is its own cluster + # edge case 2: only one cluster + assert_allclose(rand_score(clustering1, clustering2), 1.0) + + +def test_rand_score(): + # regular case: different non-trivial clusterings + clustering1 = [0, 0, 0, 1, 1, 1] + clustering2 = [0, 1, 0, 1, 2, 2] + # pair confusion matrix + D11 = 2 * 2 # ordered pairs (1, 3), (5, 6) + D10 = 2 * 4 # ordered pairs (1, 2), (2, 3), (4, 5), (4, 6) + D01 = 2 * 1 # ordered pair (2, 4) + D00 = 5 * 6 - D11 - D01 - D10 # the remaining pairs + # rand score + expected_numerator = D00 + D11 + expected_denominator = D00 + D01 + D10 + D11 + expected = expected_numerator / expected_denominator + assert_allclose(rand_score(clustering1, clustering2), expected) + + +def test_adjusted_rand_score_overflow(): + """Check that large amount of data will not lead to overflow in + `adjusted_rand_score`. + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/20305 + """ + rng = np.random.RandomState(0) + y_true = rng.randint(0, 2, 100_000, dtype=np.int8) + y_pred = rng.randint(0, 2, 100_000, dtype=np.int8) + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + adjusted_rand_score(y_true, y_pred) + + +@pytest.mark.parametrize("average_method", ["min", "arithmetic", "geometric", "max"]) +def test_normalized_mutual_info_score_bounded(average_method): + """Check that nmi returns a score between 0 (included) and 1 (excluded + for non-perfect match) + + Non-regression test for issue #13836 + """ + labels1 = [0] * 469 + labels2 = [1] + labels1[1:] + labels3 = [0, 1] + labels1[2:] + + # labels1 is constant. The mutual info between labels1 and any other labelling is 0. + nmi = normalized_mutual_info_score(labels1, labels2, average_method=average_method) + assert nmi == 0 + + # non constant, non perfect matching labels + nmi = normalized_mutual_info_score(labels2, labels3, average_method=average_method) + assert 0 <= nmi < 1 + + +# TODO(1.9): remove +@pytest.mark.parametrize("sparse", [True, False]) +def test_fowlkes_mallows_sparse_deprecated(sparse): + """Check deprecation warning for 'sparse' parameter of fowlkes_mallows_score.""" + with pytest.warns( + FutureWarning, match="The 'sparse' parameter was deprecated in 1.7" + ): + fowlkes_mallows_score([0, 1], [1, 1], sparse=sparse) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_unsupervised.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_unsupervised.py new file mode 100644 index 0000000000000000000000000000000000000000..a0420bbd406ec873022ee3a6e511c51fafd82f11 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/cluster/tests/test_unsupervised.py @@ -0,0 +1,413 @@ +import warnings + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy.sparse import issparse + +from sklearn import datasets +from sklearn.metrics import pairwise_distances +from sklearn.metrics.cluster import ( + calinski_harabasz_score, + davies_bouldin_score, + silhouette_samples, + silhouette_score, +) +from sklearn.metrics.cluster._unsupervised import _silhouette_reduce +from sklearn.utils._testing import assert_array_equal +from sklearn.utils.fixes import ( + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, + LIL_CONTAINERS, +) + + +@pytest.mark.parametrize( + "sparse_container", + [None] + CSR_CONTAINERS + CSC_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +@pytest.mark.parametrize("sample_size", [None, "half"]) +def test_silhouette(sparse_container, sample_size): + # Tests the Silhouette Coefficient. + dataset = datasets.load_iris() + X, y = dataset.data, dataset.target + if sparse_container is not None: + X = sparse_container(X) + sample_size = int(X.shape[0] / 2) if sample_size == "half" else sample_size + + D = pairwise_distances(X, metric="euclidean") + # Given that the actual labels are used, we can assume that S would be positive. + score_precomputed = silhouette_score( + D, y, metric="precomputed", sample_size=sample_size, random_state=0 + ) + score_euclidean = silhouette_score( + X, y, metric="euclidean", sample_size=sample_size, random_state=0 + ) + assert score_precomputed > 0 + assert score_euclidean > 0 + assert score_precomputed == pytest.approx(score_euclidean) + + +def test_cluster_size_1(): + # Assert Silhouette Coefficient == 0 when there is 1 sample in a cluster + # (cluster 0). We also test the case where there are identical samples + # as the only members of a cluster (cluster 2). To our knowledge, this case + # is not discussed in reference material, and we choose for it a sample + # score of 1. + X = [[0.0], [1.0], [1.0], [2.0], [3.0], [3.0]] + labels = np.array([0, 1, 1, 1, 2, 2]) + + # Cluster 0: 1 sample -> score of 0 by Rousseeuw's convention + # Cluster 1: intra-cluster = [.5, .5, 1] + # inter-cluster = [1, 1, 1] + # silhouette = [.5, .5, 0] + # Cluster 2: intra-cluster = [0, 0] + # inter-cluster = [arbitrary, arbitrary] + # silhouette = [1., 1.] + + silhouette = silhouette_score(X, labels) + assert not np.isnan(silhouette) + ss = silhouette_samples(X, labels) + assert_array_equal(ss, [0, 0.5, 0.5, 0, 1, 1]) + + +def test_silhouette_paper_example(): + # Explicitly check per-sample results against Rousseeuw (1987) + # Data from Table 1 + lower = [ + 5.58, + 7.00, + 6.50, + 7.08, + 7.00, + 3.83, + 4.83, + 5.08, + 8.17, + 5.83, + 2.17, + 5.75, + 6.67, + 6.92, + 4.92, + 6.42, + 5.00, + 5.58, + 6.00, + 4.67, + 6.42, + 3.42, + 5.50, + 6.42, + 6.42, + 5.00, + 3.92, + 6.17, + 2.50, + 4.92, + 6.25, + 7.33, + 4.50, + 2.25, + 6.33, + 2.75, + 6.08, + 6.67, + 4.25, + 2.67, + 6.00, + 6.17, + 6.17, + 6.92, + 6.17, + 5.25, + 6.83, + 4.50, + 3.75, + 5.75, + 5.42, + 6.08, + 5.83, + 6.67, + 3.67, + 4.75, + 3.00, + 6.08, + 6.67, + 5.00, + 5.58, + 4.83, + 6.17, + 5.67, + 6.50, + 6.92, + ] + D = np.zeros((12, 12)) + D[np.tril_indices(12, -1)] = lower + D += D.T + + names = [ + "BEL", + "BRA", + "CHI", + "CUB", + "EGY", + "FRA", + "IND", + "ISR", + "USA", + "USS", + "YUG", + "ZAI", + ] + + # Data from Figure 2 + labels1 = [1, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1] + expected1 = { + "USA": 0.43, + "BEL": 0.39, + "FRA": 0.35, + "ISR": 0.30, + "BRA": 0.22, + "EGY": 0.20, + "ZAI": 0.19, + "CUB": 0.40, + "USS": 0.34, + "CHI": 0.33, + "YUG": 0.26, + "IND": -0.04, + } + score1 = 0.28 + + # Data from Figure 3 + labels2 = [1, 2, 3, 3, 1, 1, 2, 1, 1, 3, 3, 2] + expected2 = { + "USA": 0.47, + "FRA": 0.44, + "BEL": 0.42, + "ISR": 0.37, + "EGY": 0.02, + "ZAI": 0.28, + "BRA": 0.25, + "IND": 0.17, + "CUB": 0.48, + "USS": 0.44, + "YUG": 0.31, + "CHI": 0.31, + } + score2 = 0.33 + + for labels, expected, score in [ + (labels1, expected1, score1), + (labels2, expected2, score2), + ]: + expected = [expected[name] for name in names] + # we check to 2dp because that's what's in the paper + pytest.approx( + expected, + silhouette_samples(D, np.array(labels), metric="precomputed"), + abs=1e-2, + ) + pytest.approx( + score, silhouette_score(D, np.array(labels), metric="precomputed"), abs=1e-2 + ) + + +def test_correct_labelsize(): + # Assert 1 < n_labels < n_samples + dataset = datasets.load_iris() + X = dataset.data + + # n_labels = n_samples + y = np.arange(X.shape[0]) + err_msg = ( + r"Number of labels is %d\. Valid values are 2 " + r"to n_samples - 1 \(inclusive\)" % len(np.unique(y)) + ) + with pytest.raises(ValueError, match=err_msg): + silhouette_score(X, y) + + # n_labels = 1 + y = np.zeros(X.shape[0]) + err_msg = ( + r"Number of labels is %d\. Valid values are 2 " + r"to n_samples - 1 \(inclusive\)" % len(np.unique(y)) + ) + with pytest.raises(ValueError, match=err_msg): + silhouette_score(X, y) + + +def test_non_encoded_labels(): + dataset = datasets.load_iris() + X = dataset.data + labels = dataset.target + assert silhouette_score(X, labels * 2 + 10) == silhouette_score(X, labels) + assert_array_equal( + silhouette_samples(X, labels * 2 + 10), silhouette_samples(X, labels) + ) + + +def test_non_numpy_labels(): + dataset = datasets.load_iris() + X = dataset.data + y = dataset.target + assert silhouette_score(list(X), list(y)) == silhouette_score(X, y) + + +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +def test_silhouette_nonzero_diag(dtype): + # Make sure silhouette_samples requires diagonal to be zero. + # Non-regression test for #12178 + + # Construct a zero-diagonal matrix + dists = pairwise_distances( + np.array([[0.2, 0.1, 0.12, 1.34, 1.11, 1.6]], dtype=dtype).T + ) + labels = [0, 0, 0, 1, 1, 1] + + # small values on the diagonal are OK + dists[2][2] = np.finfo(dists.dtype).eps * 10 + silhouette_samples(dists, labels, metric="precomputed") + + # values bigger than eps * 100 are not + dists[2][2] = np.finfo(dists.dtype).eps * 1000 + with pytest.raises(ValueError, match="contains non-zero"): + silhouette_samples(dists, labels, metric="precomputed") + + +@pytest.mark.parametrize( + "sparse_container", + CSC_CONTAINERS + CSR_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +def test_silhouette_samples_precomputed_sparse(sparse_container): + """Check that silhouette_samples works for sparse matrices correctly.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + y = [0, 0, 0, 0, 1, 1, 1, 1] + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + assert issparse(pdist_sparse) + output_with_sparse_input = silhouette_samples(pdist_sparse, y, metric="precomputed") + output_with_dense_input = silhouette_samples(pdist_dense, y, metric="precomputed") + assert_allclose(output_with_sparse_input, output_with_dense_input) + + +@pytest.mark.parametrize( + "sparse_container", + CSC_CONTAINERS + CSR_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS, +) +def test_silhouette_samples_euclidean_sparse(sparse_container): + """Check that silhouette_samples works for sparse matrices correctly.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + y = [0, 0, 0, 0, 1, 1, 1, 1] + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + assert issparse(pdist_sparse) + output_with_sparse_input = silhouette_samples(pdist_sparse, y) + output_with_dense_input = silhouette_samples(pdist_dense, y) + assert_allclose(output_with_sparse_input, output_with_dense_input) + + +@pytest.mark.parametrize( + "sparse_container", CSC_CONTAINERS + DOK_CONTAINERS + LIL_CONTAINERS +) +def test_silhouette_reduce(sparse_container): + """Check for non-CSR input to private method `_silhouette_reduce`.""" + X = np.array([[0.2, 0.1, 0.1, 0.2, 0.1, 1.6, 0.2, 0.1]], dtype=np.float32).T + pdist_dense = pairwise_distances(X) + pdist_sparse = sparse_container(pdist_dense) + y = [0, 0, 0, 0, 1, 1, 1, 1] + label_freqs = np.bincount(y) + with pytest.raises( + TypeError, + match="Expected CSR matrix. Please pass sparse matrix in CSR format.", + ): + _silhouette_reduce(pdist_sparse, start=0, labels=y, label_freqs=label_freqs) + + +def assert_raises_on_only_one_label(func): + """Assert message when there is only one label""" + rng = np.random.RandomState(seed=0) + with pytest.raises(ValueError, match="Number of labels is"): + func(rng.rand(10, 2), np.zeros(10)) + + +def assert_raises_on_all_points_same_cluster(func): + """Assert message when all point are in different clusters""" + rng = np.random.RandomState(seed=0) + with pytest.raises(ValueError, match="Number of labels is"): + func(rng.rand(10, 2), np.arange(10)) + + +def test_calinski_harabasz_score(): + assert_raises_on_only_one_label(calinski_harabasz_score) + + assert_raises_on_all_points_same_cluster(calinski_harabasz_score) + + # Assert the value is 1. when all samples are equals + assert 1.0 == calinski_harabasz_score(np.ones((10, 2)), [0] * 5 + [1] * 5) + + # Assert the value is 0. when all the mean cluster are equal + assert 0.0 == calinski_harabasz_score([[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10) + + # General case (with non numpy arrays) + X = ( + [[0, 0], [1, 1]] * 5 + + [[3, 3], [4, 4]] * 5 + + [[0, 4], [1, 3]] * 5 + + [[3, 1], [4, 0]] * 5 + ) + labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 + pytest.approx(calinski_harabasz_score(X, labels), 45 * (40 - 4) / (5 * (4 - 1))) + + +def test_davies_bouldin_score(): + assert_raises_on_only_one_label(davies_bouldin_score) + assert_raises_on_all_points_same_cluster(davies_bouldin_score) + + # Assert the value is 0. when all samples are equals + assert davies_bouldin_score(np.ones((10, 2)), [0] * 5 + [1] * 5) == pytest.approx( + 0.0 + ) + + # Assert the value is 0. when all the mean cluster are equal + assert davies_bouldin_score( + [[-1, -1], [1, 1]] * 10, [0] * 10 + [1] * 10 + ) == pytest.approx(0.0) + + # General case (with non numpy arrays) + X = ( + [[0, 0], [1, 1]] * 5 + + [[3, 3], [4, 4]] * 5 + + [[0, 4], [1, 3]] * 5 + + [[3, 1], [4, 0]] * 5 + ) + labels = [0] * 10 + [1] * 10 + [2] * 10 + [3] * 10 + pytest.approx(davies_bouldin_score(X, labels), 2 * np.sqrt(0.5) / 3) + + # Ensure divide by zero warning is not raised in general case + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + davies_bouldin_score(X, labels) + + # General case - cluster have one sample + X = [[0, 0], [2, 2], [3, 3], [5, 5]] + labels = [0, 0, 1, 2] + pytest.approx(davies_bouldin_score(X, labels), (5.0 / 4) / 3) + + +def test_silhouette_score_integer_precomputed(): + """Check that silhouette_score works for precomputed metrics that are integers. + + Non-regression test for #22107. + """ + result = silhouette_score( + [[0, 1, 2], [1, 0, 1], [2, 1, 0]], [0, 0, 1], metric="precomputed" + ) + assert result == pytest.approx(1 / 6) + + # non-zero on diagonal for ints raises an error + with pytest.raises(ValueError, match="contains non-zero"): + silhouette_score( + [[1, 1, 2], [1, 0, 1], [2, 1, 0]], [0, 0, 1], metric="precomputed" + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/meson.build b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/meson.build new file mode 100644 index 0000000000000000000000000000000000000000..f0f9894cc6f59a9500a1598c9c9a94d5d6f58429 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/meson.build @@ -0,0 +1,49 @@ +# Metrics is cimported from other subpackages so this is needed for the cimport +# to work +metrics_cython_tree = [ + fs.copyfile('__init__.py') +] +# Some metrics code cimports code from utils, we may as well copy all the necessary files +metrics_cython_tree += utils_cython_tree + +_dist_metrics_pxd = custom_target( + '_dist_metrics_pxd', + output: '_dist_metrics.pxd', + input: '_dist_metrics.pxd.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # Need to install the generated pxd because it is needed in other subpackages + # Cython code, e.g. sklearn.cluster + install_dir: sklearn_dir / 'metrics', + install: true, +) +metrics_cython_tree += [_dist_metrics_pxd] + +_dist_metrics_pyx = custom_target( + '_dist_metrics_pyx', + output: '_dist_metrics.pyx', + input: '_dist_metrics.pyx.tp', + command: [tempita, '@INPUT@', '-o', '@OUTDIR@'], + # TODO in principle this should go in py.exension_module below. This is + # temporary work-around for dependency issue with .pyx.tp files. For more + # details, see https://github.com/mesonbuild/meson/issues/13212 + depends: metrics_cython_tree, +) + +_dist_metrics = py.extension_module( + '_dist_metrics', + cython_gen.process(_dist_metrics_pyx), + dependencies: [np_dep], + subdir: 'sklearn/metrics', + install: true +) + +py.extension_module( + '_pairwise_fast', + [cython_gen.process('_pairwise_fast.pyx'), metrics_cython_tree], + dependencies: [openmp_dep], + subdir: 'sklearn/metrics', + install: true +) + +subdir('_pairwise_distances_reduction') +subdir('cluster') diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/pairwise.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/pairwise.py new file mode 100644 index 0000000000000000000000000000000000000000..050b58866c8ef589fba008c8444948b30e3416ed --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/pairwise.py @@ -0,0 +1,2675 @@ +"""Metrics for pairwise distances and affinity of sets of samples.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +import math +import warnings +from functools import partial +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs +from scipy.sparse import csr_matrix, issparse +from scipy.spatial import distance + +from .. import config_context +from ..exceptions import DataConversionWarning +from ..preprocessing import normalize +from ..utils import check_array, gen_batches, gen_even_slices +from ..utils._array_api import ( + _fill_or_add_to_diagonal, + _find_matching_floating_dtype, + _is_numpy_namespace, + _max_precision_float_dtype, + _modify_in_place_if_numpy, + get_namespace, + get_namespace_and_device, +) +from ..utils._chunking import get_chunk_n_rows +from ..utils._mask import _get_mask +from ..utils._missing import is_scalar_nan +from ..utils._param_validation import ( + Hidden, + Interval, + MissingValues, + Options, + StrOptions, + validate_params, +) +from ..utils.deprecation import _deprecate_force_all_finite +from ..utils.extmath import row_norms, safe_sparse_dot +from ..utils.fixes import parse_version, sp_base_version +from ..utils.parallel import Parallel, delayed +from ..utils.validation import _num_samples, check_non_negative +from ._pairwise_distances_reduction import ArgKmin +from ._pairwise_fast import _chi2_kernel_fast, _sparse_manhattan + + +# Utility Functions +def _return_float_dtype(X, Y): + """ + 1. If dtype of X and Y is float32, then dtype float32 is returned. + 2. Else dtype float is returned. + """ + if not issparse(X) and not isinstance(X, np.ndarray): + X = np.asarray(X) + + if Y is None: + Y_dtype = X.dtype + elif not issparse(Y) and not isinstance(Y, np.ndarray): + Y = np.asarray(Y) + Y_dtype = Y.dtype + else: + Y_dtype = Y.dtype + + if X.dtype == Y_dtype == np.float32: + dtype = np.float32 + else: + dtype = float + + return X, Y, dtype + + +def check_pairwise_arrays( + X, + Y, + *, + precomputed=False, + dtype="infer_float", + accept_sparse="csr", + force_all_finite="deprecated", + ensure_all_finite=None, + ensure_2d=True, + copy=False, +): + """Set X and Y appropriately and checks inputs. + + If Y is None, it is set as a pointer to X (i.e. not a copy). + If Y is given, this does not happen. + All distance metrics should use this function first to assert that the + given parameters are correct and safe to use. + + Specifically, this function first ensures that both X and Y are arrays, + then checks that they are at least two dimensional while ensuring that + their elements are floats (or dtype if provided). Finally, the function + checks that the size of the second dimension of the two arrays is equal, or + the equivalent check for a precomputed distance matrix. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + + precomputed : bool, default=False + True if X is to be treated as precomputed distances to the samples in + Y. + + dtype : str, type, list of type or None default="infer_float" + Data type required for X and Y. If "infer_float", the dtype will be an + appropriate float type selected by _return_float_dtype. If None, the + dtype of the input is preserved. + + .. versionadded:: 0.18 + + accept_sparse : str, bool or list/tuple of str, default='csr' + String[s] representing allowed sparse matrix formats, such as 'csc', + 'csr', etc. If the input is sparse but not in the allowed format, + it will be converted to the first listed format. True allows the input + to be any format. False means that a sparse matrix input will + raise an error. + + force_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 0.22 + ``force_all_finite`` accepts the string ``'allow-nan'``. + + .. versionchanged:: 0.23 + Accepts `pd.NA` and converts it into `np.nan`. + + .. deprecated:: 1.6 + `force_all_finite` was renamed to `ensure_all_finite` and will be removed + in 1.8. + + ensure_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 1.6 + `force_all_finite` was renamed to `ensure_all_finite`. + + ensure_2d : bool, default=True + Whether to raise an error when the input arrays are not 2-dimensional. Setting + this to `False` is necessary when using a custom metric with certain + non-numerical inputs (e.g. a list of strings). + + .. versionadded:: 1.5 + + copy : bool, default=False + Whether a forced copy will be triggered. If copy=False, a copy might + be triggered by a conversion. + + .. versionadded:: 0.22 + + Returns + ------- + safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array equal to X, guaranteed to be a numpy array. + + safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. + If Y was None, safe_Y will be a pointer to X. + """ + ensure_all_finite = _deprecate_force_all_finite(force_all_finite, ensure_all_finite) + + xp, _ = get_namespace(X, Y) + if any([issparse(X), issparse(Y)]) or _is_numpy_namespace(xp): + X, Y, dtype_float = _return_float_dtype(X, Y) + else: + dtype_float = _find_matching_floating_dtype(X, Y, xp=xp) + + estimator = "check_pairwise_arrays" + if dtype == "infer_float": + dtype = dtype_float + + if Y is X or Y is None: + X = Y = check_array( + X, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + ensure_all_finite=ensure_all_finite, + estimator=estimator, + ensure_2d=ensure_2d, + ) + else: + X = check_array( + X, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + ensure_all_finite=ensure_all_finite, + estimator=estimator, + ensure_2d=ensure_2d, + ) + Y = check_array( + Y, + accept_sparse=accept_sparse, + dtype=dtype, + copy=copy, + ensure_all_finite=ensure_all_finite, + estimator=estimator, + ensure_2d=ensure_2d, + ) + + if precomputed: + if X.shape[1] != Y.shape[0]: + raise ValueError( + "Precomputed metric requires shape " + "(n_queries, n_indexed). Got (%d, %d) " + "for %d indexed." % (X.shape[0], X.shape[1], Y.shape[0]) + ) + elif ensure_2d and X.shape[1] != Y.shape[1]: + # Only check the number of features if 2d arrays are enforced. Otherwise, + # validation is left to the user for custom metrics. + raise ValueError( + "Incompatible dimension for X and Y matrices: " + "X.shape[1] == %d while Y.shape[1] == %d" % (X.shape[1], Y.shape[1]) + ) + + return X, Y + + +def check_paired_arrays(X, Y): + """Set X and Y appropriately and checks inputs for paired distances. + + All paired distance metrics should use this function first to assert that + the given parameters are correct and safe to use. + + Specifically, this function first ensures that both X and Y are arrays, + then checks that they are at least two dimensional while ensuring that + their elements are floats. Finally, the function checks that the size + of the dimensions of the two arrays are equal. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + + Returns + ------- + safe_X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array equal to X, guaranteed to be a numpy array. + + safe_Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + An array equal to Y if Y was not None, guaranteed to be a numpy array. + If Y was None, safe_Y will be a pointer to X. + """ + X, Y = check_pairwise_arrays(X, Y) + if X.shape != Y.shape: + raise ValueError( + "X and Y should be of same shape. They were respectively %r and %r long." + % (X.shape, Y.shape) + ) + return X, Y + + +# Pairwise distances +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "Y_norm_squared": ["array-like", None], + "squared": ["boolean"], + "X_norm_squared": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def euclidean_distances( + X, Y=None, *, Y_norm_squared=None, squared=False, X_norm_squared=None +): + """ + Compute the distance matrix between each pair from a feature array X and Y. + + For efficiency reasons, the euclidean distance between a pair of row + vector x and y is computed as:: + + dist(x, y) = sqrt(dot(x, x) - 2 * dot(x, y) + dot(y, y)) + + This formulation has two advantages over other ways of computing distances. + First, it is computationally efficient when dealing with sparse data. + Second, if one argument varies but the other remains unchanged, then + `dot(x, x)` and/or `dot(y, y)` can be pre-computed. + + However, this is not the most precise way of doing this computation, + because this equation potentially suffers from "catastrophic cancellation". + Also, the distance matrix returned by this function may not be exactly + symmetric as required by, e.g., :mod:`scipy.spatial.distance` functions. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + Y_norm_squared : array-like of shape (n_samples_Y,) or (n_samples_Y, 1) \ + or (1, n_samples_Y), default=None + Pre-computed dot-products of vectors in Y (e.g., + ``(Y**2).sum(axis=1)``) + May be ignored in some cases, see the note below. + + squared : bool, default=False + Return squared Euclidean distances. + + X_norm_squared : array-like of shape (n_samples_X,) or (n_samples_X, 1) \ + or (1, n_samples_X), default=None + Pre-computed dot-products of vectors in X (e.g., + ``(X**2).sum(axis=1)``) + May be ignored in some cases, see the note below. + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + paired_distances : Distances between pairs of elements of X and Y. + + Notes + ----- + To achieve a better accuracy, `X_norm_squared` and `Y_norm_squared` may be + unused if they are passed as `np.float32`. + + Examples + -------- + >>> from sklearn.metrics.pairwise import euclidean_distances + >>> X = [[0, 1], [1, 1]] + >>> # distance between rows of X + >>> euclidean_distances(X, X) + array([[0., 1.], + [1., 0.]]) + >>> # get distance to origin + >>> euclidean_distances(X, [[0, 0]]) + array([[1. ], + [1.41421356]]) + """ + xp, _ = get_namespace(X, Y) + X, Y = check_pairwise_arrays(X, Y) + + if X_norm_squared is not None: + X_norm_squared = check_array(X_norm_squared, ensure_2d=False) + original_shape = X_norm_squared.shape + if X_norm_squared.shape == (X.shape[0],): + X_norm_squared = xp.reshape(X_norm_squared, (-1, 1)) + if X_norm_squared.shape == (1, X.shape[0]): + X_norm_squared = X_norm_squared.T + if X_norm_squared.shape != (X.shape[0], 1): + raise ValueError( + f"Incompatible dimensions for X of shape {X.shape} and " + f"X_norm_squared of shape {original_shape}." + ) + + if Y_norm_squared is not None: + Y_norm_squared = check_array(Y_norm_squared, ensure_2d=False) + original_shape = Y_norm_squared.shape + if Y_norm_squared.shape == (Y.shape[0],): + Y_norm_squared = xp.reshape(Y_norm_squared, (1, -1)) + if Y_norm_squared.shape == (Y.shape[0], 1): + Y_norm_squared = Y_norm_squared.T + if Y_norm_squared.shape != (1, Y.shape[0]): + raise ValueError( + f"Incompatible dimensions for Y of shape {Y.shape} and " + f"Y_norm_squared of shape {original_shape}." + ) + + return _euclidean_distances(X, Y, X_norm_squared, Y_norm_squared, squared) + + +def _euclidean_distances(X, Y, X_norm_squared=None, Y_norm_squared=None, squared=False): + """Computational part of euclidean_distances + + Assumes inputs are already checked. + + If norms are passed as float32, they are unused. If arrays are passed as + float32, norms needs to be recomputed on upcast chunks. + TODO: use a float64 accumulator in row_norms to avoid the latter. + """ + xp, _, device_ = get_namespace_and_device(X, Y) + if X_norm_squared is not None and X_norm_squared.dtype != xp.float32: + XX = xp.reshape(X_norm_squared, (-1, 1)) + elif X.dtype != xp.float32: + XX = row_norms(X, squared=True)[:, None] + else: + XX = None + + if Y is X: + YY = None if XX is None else XX.T + else: + if Y_norm_squared is not None and Y_norm_squared.dtype != xp.float32: + YY = xp.reshape(Y_norm_squared, (1, -1)) + elif Y.dtype != xp.float32: + YY = row_norms(Y, squared=True)[None, :] + else: + YY = None + + if X.dtype == xp.float32 or Y.dtype == xp.float32: + # To minimize precision issues with float32, we compute the distance + # matrix on chunks of X and Y upcast to float64 + distances = _euclidean_distances_upcast(X, XX, Y, YY) + else: + # if dtype is already float64, no need to chunk and upcast + distances = -2 * safe_sparse_dot(X, Y.T, dense_output=True) + distances += XX + distances += YY + + xp_zero = xp.asarray(0, device=device_, dtype=distances.dtype) + distances = _modify_in_place_if_numpy( + xp, xp.maximum, distances, xp_zero, out=distances + ) + + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + if X is Y: + _fill_or_add_to_diagonal(distances, 0, xp=xp, add_value=False) + + if squared: + return distances + + distances = _modify_in_place_if_numpy(xp, xp.sqrt, distances, out=distances) + return distances + + +@validate_params( + { + "X": ["array-like"], + "Y": ["array-like", None], + "squared": ["boolean"], + "missing_values": [MissingValues(numeric_only=True)], + "copy": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def nan_euclidean_distances( + X, Y=None, *, squared=False, missing_values=np.nan, copy=True +): + """Calculate the euclidean distances in the presence of missing values. + + Compute the euclidean distance between each pair of samples in X and Y, + where Y=X is assumed if Y=None. When calculating the distance between a + pair of samples, this formulation ignores feature coordinates with a + missing value in either sample and scales up the weight of the remaining + coordinates: + + .. code-block:: text + + dist(x,y) = sqrt(weight * sq. distance from present coordinates) + + where: + + .. code-block:: text + + weight = Total # of coordinates / # of present coordinates + + For example, the distance between ``[3, na, na, 6]`` and ``[1, na, 4, 5]`` is: + + .. math:: + \\sqrt{\\frac{4}{2}((3-1)^2 + (6-5)^2)} + + If all the coordinates are missing or if there are no common present + coordinates then NaN is returned for that pair. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.22 + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : array-like of shape (n_samples_Y, n_features), default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + squared : bool, default=False + Return squared Euclidean distances. + + missing_values : np.nan, float or int, default=np.nan + Representation of missing value. + + copy : bool, default=True + Make and use a deep copy of X and Y (if Y exists). + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + paired_distances : Distances between pairs of elements of X and Y. + + References + ---------- + * John K. Dixon, "Pattern Recognition with Partly Missing Data", + IEEE Transactions on Systems, Man, and Cybernetics, Volume: 9, Issue: + 10, pp. 617 - 621, Oct. 1979. + http://ieeexplore.ieee.org/abstract/document/4310090/ + + Examples + -------- + >>> from sklearn.metrics.pairwise import nan_euclidean_distances + >>> nan = float("NaN") + >>> X = [[0, 1], [1, nan]] + >>> nan_euclidean_distances(X, X) # distance between rows of X + array([[0. , 1.41421356], + [1.41421356, 0. ]]) + + >>> # get distance to origin + >>> nan_euclidean_distances(X, [[0, 0]]) + array([[1. ], + [1.41421356]]) + """ + + ensure_all_finite = "allow-nan" if is_scalar_nan(missing_values) else True + X, Y = check_pairwise_arrays( + X, Y, accept_sparse=False, ensure_all_finite=ensure_all_finite, copy=copy + ) + # Get missing mask for X + missing_X = _get_mask(X, missing_values) + + # Get missing mask for Y + missing_Y = missing_X if Y is X else _get_mask(Y, missing_values) + + # set missing values to zero + X[missing_X] = 0 + Y[missing_Y] = 0 + + distances = euclidean_distances(X, Y, squared=True) + + # Adjust distances for missing values + XX = X * X + YY = Y * Y + distances -= np.dot(XX, missing_Y.T) + distances -= np.dot(missing_X, YY.T) + + np.clip(distances, 0, None, out=distances) + + if X is Y: + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + np.fill_diagonal(distances, 0.0) + + present_X = 1 - missing_X + present_Y = present_X if Y is X else ~missing_Y + present_count = np.dot(present_X, present_Y.T) + distances[present_count == 0] = np.nan + # avoid divide by zero + np.maximum(1, present_count, out=present_count) + distances /= present_count + distances *= X.shape[1] + + if not squared: + np.sqrt(distances, out=distances) + + return distances + + +def _euclidean_distances_upcast(X, XX=None, Y=None, YY=None, batch_size=None): + """Euclidean distances between X and Y. + + Assumes X and Y have float32 dtype. + Assumes XX and YY have float64 dtype or are None. + + X and Y are upcast to float64 by chunks, which size is chosen to limit + memory increase by approximately 10% (at least 10MiB). + """ + xp, _, device_ = get_namespace_and_device(X, Y) + n_samples_X = X.shape[0] + n_samples_Y = Y.shape[0] + n_features = X.shape[1] + + distances = xp.empty((n_samples_X, n_samples_Y), dtype=xp.float32, device=device_) + + if batch_size is None: + x_density = X.nnz / np.prod(X.shape) if issparse(X) else 1 + y_density = Y.nnz / np.prod(Y.shape) if issparse(Y) else 1 + + # Allow 10% more memory than X, Y and the distance matrix take (at + # least 10MiB) + maxmem = max( + ( + (x_density * n_samples_X + y_density * n_samples_Y) * n_features + + (x_density * n_samples_X * y_density * n_samples_Y) + ) + / 10, + 10 * 2**17, + ) + + # The increase amount of memory in 8-byte blocks is: + # - x_density * batch_size * n_features (copy of chunk of X) + # - y_density * batch_size * n_features (copy of chunk of Y) + # - batch_size * batch_size (chunk of distance matrix) + # Hence x² + (xd+yd)kx = M, where x=batch_size, k=n_features, M=maxmem + # xd=x_density and yd=y_density + tmp = (x_density + y_density) * n_features + batch_size = (-tmp + math.sqrt(tmp**2 + 4 * maxmem)) / 2 + batch_size = max(int(batch_size), 1) + + x_batches = gen_batches(n_samples_X, batch_size) + xp_max_float = _max_precision_float_dtype(xp=xp, device=device_) + for i, x_slice in enumerate(x_batches): + X_chunk = xp.astype(X[x_slice, :], xp_max_float) + if XX is None: + XX_chunk = row_norms(X_chunk, squared=True)[:, None] + else: + XX_chunk = XX[x_slice] + + y_batches = gen_batches(n_samples_Y, batch_size) + + for j, y_slice in enumerate(y_batches): + if X is Y and j < i: + # when X is Y the distance matrix is symmetric so we only need + # to compute half of it. + d = distances[y_slice, x_slice].T + + else: + Y_chunk = xp.astype(Y[y_slice, :], xp_max_float) + if YY is None: + YY_chunk = row_norms(Y_chunk, squared=True)[None, :] + else: + YY_chunk = YY[:, y_slice] + + d = -2 * safe_sparse_dot(X_chunk, Y_chunk.T, dense_output=True) + d += XX_chunk + d += YY_chunk + + distances[x_slice, y_slice] = xp.astype(d, xp.float32, copy=False) + + return distances + + +def _argmin_min_reduce(dist, start): + # `start` is specified in the signature but not used. This is because the higher + # order `pairwise_distances_chunked` function needs reduction functions that are + # passed as argument to have a two arguments signature. + indices = dist.argmin(axis=1) + values = dist[np.arange(dist.shape[0]), indices] + return indices, values + + +def _argmin_reduce(dist, start): + # `start` is specified in the signature but not used. This is because the higher + # order `pairwise_distances_chunked` function needs reduction functions that are + # passed as argument to have a two arguments signature. + return dist.argmin(axis=1) + + +_VALID_METRICS = [ + "euclidean", + "l2", + "l1", + "manhattan", + "cityblock", + "braycurtis", + "canberra", + "chebyshev", + "correlation", + "cosine", + "dice", + "hamming", + "jaccard", + "mahalanobis", + "matching", + "minkowski", + "rogerstanimoto", + "russellrao", + "seuclidean", + "sokalsneath", + "sqeuclidean", + "yule", + "wminkowski", + "nan_euclidean", + "haversine", +] +if sp_base_version < parse_version("1.17"): # pragma: no cover + # Deprecated in SciPy 1.15 and removed in SciPy 1.17 + _VALID_METRICS += ["sokalmichener"] +if sp_base_version < parse_version("1.11"): # pragma: no cover + # Deprecated in SciPy 1.9 and removed in SciPy 1.11 + _VALID_METRICS += ["kulsinski"] +if sp_base_version < parse_version("1.9"): + # Deprecated in SciPy 1.0 and removed in SciPy 1.9 + _VALID_METRICS += ["matching"] + +_NAN_METRICS = ["nan_euclidean"] + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix"], + "axis": [Options(Integral, {0, 1})], + "metric": [ + StrOptions(set(_VALID_METRICS).union(ArgKmin.valid_metrics())), + callable, + ], + "metric_kwargs": [dict, None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def pairwise_distances_argmin_min( + X, Y, *, axis=1, metric="euclidean", metric_kwargs=None +): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). The minimal distances are + also returned. + + This is mostly equivalent to calling:: + + (pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis), + pairwise_distances(X, Y=Y, metric=metric).min(axis=axis)) + + but uses much less memory, and is faster for large arrays. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Array containing points. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + Array containing points. + + axis : int, default=1 + Axis along which the argmin and distances are to be computed. + + metric : str or callable, default='euclidean' + Metric to use for distance computation. Any metric from scikit-learn + or :mod:`scipy.spatial.distance` can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan', 'nan_euclidean'] + + - from :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for :mod:`scipy.spatial.distance` for details on these + metrics. + + .. note:: + `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. + + .. note:: + `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + Returns + ------- + argmin : ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + distances : ndarray + The array of minimum distances. `distances[i]` is the distance between + the i-th row in X and the argmin[i]-th row in Y. + + See Also + -------- + pairwise_distances : Distances between every pair of samples of X and Y. + pairwise_distances_argmin : Same as `pairwise_distances_argmin_min` but only + returns the argmins. + + Examples + -------- + >>> from sklearn.metrics.pairwise import pairwise_distances_argmin_min + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> argmin, distances = pairwise_distances_argmin_min(X, Y) + >>> argmin + array([0, 1]) + >>> distances + array([1., 1.]) + """ + ensure_all_finite = "allow-nan" if metric == "nan_euclidean" else True + X, Y = check_pairwise_arrays(X, Y, ensure_all_finite=ensure_all_finite) + + if axis == 0: + X, Y = Y, X + + if metric_kwargs is None: + metric_kwargs = {} + + if ArgKmin.is_usable_for(X, Y, metric): + # This is an adaptor for one "sqeuclidean" specification. + # For this backend, we can directly use "sqeuclidean". + if metric_kwargs.get("squared", False) and metric == "euclidean": + metric = "sqeuclidean" + metric_kwargs = {} + + values, indices = ArgKmin.compute( + X=X, + Y=Y, + k=1, + metric=metric, + metric_kwargs=metric_kwargs, + strategy="auto", + return_distance=True, + ) + values = values.flatten() + indices = indices.flatten() + else: + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + + # Turn off check for finiteness because this is costly and because arrays + # have already been validated. + with config_context(assume_finite=True): + indices, values = zip( + *pairwise_distances_chunked( + X, Y, reduce_func=_argmin_min_reduce, metric=metric, **metric_kwargs + ) + ) + indices = np.concatenate(indices) + values = np.concatenate(values) + + return indices, values + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix"], + "axis": [Options(Integral, {0, 1})], + "metric": [ + StrOptions(set(_VALID_METRICS).union(ArgKmin.valid_metrics())), + callable, + ], + "metric_kwargs": [dict, None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def pairwise_distances_argmin(X, Y, *, axis=1, metric="euclidean", metric_kwargs=None): + """Compute minimum distances between one point and a set of points. + + This function computes for each row in X, the index of the row of Y which + is closest (according to the specified distance). + + This is mostly equivalent to calling:: + + pairwise_distances(X, Y=Y, metric=metric).argmin(axis=axis) + + but uses much less memory, and is faster for large arrays. + + This function works with dense 2D arrays only. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Array containing points. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features) + Arrays containing points. + + axis : int, default=1 + Axis along which the argmin and distances are to be computed. + + metric : str or callable, default="euclidean" + Metric to use for distance computation. Any metric from scikit-learn + or :mod:`scipy.spatial.distance` can be used. + + If metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays as input and return one value indicating the + distance between them. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + Valid values for metric are: + + - from scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan', 'nan_euclidean'] + + - from :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', + 'mahalanobis', 'minkowski', 'rogerstanimoto', 'russellrao', + 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', + 'yule'] + + See the documentation for :mod:`scipy.spatial.distance` for details on these + metrics. + + .. note:: + `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. + + .. note:: + `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). + + metric_kwargs : dict, default=None + Keyword arguments to pass to specified metric function. + + Returns + ------- + argmin : numpy.ndarray + Y[argmin[i], :] is the row in Y that is closest to X[i, :]. + + See Also + -------- + pairwise_distances : Distances between every pair of samples of X and Y. + pairwise_distances_argmin_min : Same as `pairwise_distances_argmin` but also + returns the distances. + + Examples + -------- + >>> from sklearn.metrics.pairwise import pairwise_distances_argmin + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> pairwise_distances_argmin(X, Y) + array([0, 1]) + """ + ensure_all_finite = "allow-nan" if metric == "nan_euclidean" else True + X, Y = check_pairwise_arrays(X, Y, ensure_all_finite=ensure_all_finite) + + if axis == 0: + X, Y = Y, X + + if metric_kwargs is None: + metric_kwargs = {} + + if ArgKmin.is_usable_for(X, Y, metric): + # This is an adaptor for one "sqeuclidean" specification. + # For this backend, we can directly use "sqeuclidean". + if metric_kwargs.get("squared", False) and metric == "euclidean": + metric = "sqeuclidean" + metric_kwargs = {} + + indices = ArgKmin.compute( + X=X, + Y=Y, + k=1, + metric=metric, + metric_kwargs=metric_kwargs, + strategy="auto", + return_distance=False, + ) + indices = indices.flatten() + else: + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + + # Turn off check for finiteness because this is costly and because arrays + # have already been validated. + with config_context(assume_finite=True): + indices = np.concatenate( + list( + # This returns a np.ndarray generator whose arrays we need + # to flatten into one. + pairwise_distances_chunked( + X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs + ) + ) + ) + + return indices + + +@validate_params( + {"X": ["array-like", "sparse matrix"], "Y": ["array-like", "sparse matrix", None]}, + prefer_skip_nested_validation=True, +) +def haversine_distances(X, Y=None): + """Compute the Haversine distance between samples in X and Y. + + The Haversine (or great circle) distance is the angular distance between + two points on the surface of a sphere. The first coordinate of each point + is assumed to be the latitude, the second is the longitude, given + in radians. The dimension of the data must be 2. + + .. math:: + D(x, y) = 2\\arcsin[\\sqrt{\\sin^2((x_{lat} - y_{lat}) / 2) + + \\cos(x_{lat})\\cos(y_{lat})\\ + sin^2((x_{lon} - y_{lon}) / 2)}] + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, 2) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, 2), default=None + An optional second feature array. If `None`, uses `Y=X`. + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + The distance matrix. + + Notes + ----- + As the Earth is nearly spherical, the haversine formula provides a good + approximation of the distance between two points of the Earth surface, with + a less than 1% error on average. + + Examples + -------- + We want to calculate the distance between the Ezeiza Airport + (Buenos Aires, Argentina) and the Charles de Gaulle Airport (Paris, + France). + + >>> from sklearn.metrics.pairwise import haversine_distances + >>> from math import radians + >>> bsas = [-34.83333, -58.5166646] + >>> paris = [49.0083899664, 2.53844117956] + >>> bsas_in_radians = [radians(_) for _ in bsas] + >>> paris_in_radians = [radians(_) for _ in paris] + >>> result = haversine_distances([bsas_in_radians, paris_in_radians]) + >>> result * 6371000/1000 # multiply by Earth radius to get kilometers + array([[ 0. , 11099.54035582], + [11099.54035582, 0. ]]) + """ + from ..metrics import DistanceMetric + + return DistanceMetric.get_metric("haversine").pairwise(X, Y) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + }, + prefer_skip_nested_validation=True, +) +def manhattan_distances(X, Y=None): + """Compute the L1 distances between the vectors in X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + An array where each row is a sample and each column is a feature. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An array where each row is a sample and each column is a feature. + If `None`, method uses `Y=X`. + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Pairwise L1 distances. + + Notes + ----- + When X and/or Y are CSR sparse matrices and they are not already + in canonical format, this function modifies them in-place to + make them canonical. + + Examples + -------- + >>> from sklearn.metrics.pairwise import manhattan_distances + >>> manhattan_distances([[3]], [[3]]) + array([[0.]]) + >>> manhattan_distances([[3]], [[2]]) + array([[1.]]) + >>> manhattan_distances([[2]], [[3]]) + array([[1.]]) + >>> manhattan_distances([[1, 2], [3, 4]],\ + [[1, 2], [0, 3]]) + array([[0., 2.], + [4., 4.]]) + """ + X, Y = check_pairwise_arrays(X, Y) + + if issparse(X) or issparse(Y): + X = csr_matrix(X, copy=False) + Y = csr_matrix(Y, copy=False) + X.sum_duplicates() # this also sorts indices in-place + Y.sum_duplicates() + D = np.zeros((X.shape[0], Y.shape[0])) + _sparse_manhattan(X.data, X.indices, X.indptr, Y.data, Y.indices, Y.indptr, D) + return D + + return distance.cdist(X, Y, "cityblock") + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + }, + prefer_skip_nested_validation=True, +) +def cosine_distances(X, Y=None): + """Compute cosine distance between samples in X and Y. + + Cosine distance is defined as 1.0 minus the cosine similarity. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Matrix `X`. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + Matrix `Y`. + + Returns + ------- + distances : ndarray of shape (n_samples_X, n_samples_Y) + Returns the cosine distance between samples in X and Y. + + See Also + -------- + cosine_similarity : Compute cosine similarity between samples in X and Y. + scipy.spatial.distance.cosine : Dense matrices only. + + Examples + -------- + >>> from sklearn.metrics.pairwise import cosine_distances + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> cosine_distances(X, Y) + array([[1. , 1. ], + [0.422, 0.183]]) + """ + xp, _ = get_namespace(X, Y) + + # 1.0 - cosine_similarity(X, Y) without copy + S = cosine_similarity(X, Y) + S *= -1 + S += 1 + S = xp.clip(S, 0.0, 2.0) + if X is Y or Y is None: + # Ensure that distances between vectors and themselves are set to 0.0. + # This may not be the case due to floating point rounding errors. + _fill_or_add_to_diagonal(S, 0.0, xp, add_value=False) + return S + + +# Paired distances +@validate_params( + {"X": ["array-like", "sparse matrix"], "Y": ["array-like", "sparse matrix"]}, + prefer_skip_nested_validation=True, +) +def paired_euclidean_distances(X, Y): + """Compute the paired euclidean distances between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input array/matrix X. + + Y : {array-like, sparse matrix} of shape (n_samples, n_features) + Input array/matrix Y. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Output array/matrix containing the calculated paired euclidean + distances. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_euclidean_distances + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> paired_euclidean_distances(X, Y) + array([1., 1.]) + """ + X, Y = check_paired_arrays(X, Y) + return row_norms(X - Y) + + +@validate_params( + {"X": ["array-like", "sparse matrix"], "Y": ["array-like", "sparse matrix"]}, + prefer_skip_nested_validation=True, +) +def paired_manhattan_distances(X, Y): + """Compute the paired L1 distances between X and Y. + + Distances are calculated between (X[0], Y[0]), (X[1], Y[1]), ..., + (X[n_samples], Y[n_samples]). + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + An array-like where each row is a sample and each column is a feature. + + Y : {array-like, sparse matrix} of shape (n_samples, n_features) + An array-like where each row is a sample and each column is a feature. + + Returns + ------- + distances : ndarray of shape (n_samples,) + L1 paired distances between the row vectors of `X` + and the row vectors of `Y`. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_manhattan_distances + >>> import numpy as np + >>> X = np.array([[1, 1, 0], [0, 1, 0], [0, 0, 1]]) + >>> Y = np.array([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) + >>> paired_manhattan_distances(X, Y) + array([1., 2., 1.]) + """ + X, Y = check_paired_arrays(X, Y) + diff = X - Y + if issparse(diff): + diff.data = np.abs(diff.data) + return np.squeeze(np.array(diff.sum(axis=1))) + else: + return np.abs(diff).sum(axis=-1) + + +@validate_params( + {"X": ["array-like", "sparse matrix"], "Y": ["array-like", "sparse matrix"]}, + prefer_skip_nested_validation=True, +) +def paired_cosine_distances(X, Y): + """ + Compute the paired cosine distances between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + An array where each row is a sample and each column is a feature. + + Y : {array-like, sparse matrix} of shape (n_samples, n_features) + An array where each row is a sample and each column is a feature. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`, where `distances[i]` is the + distance between `X[i]` and `Y[i]`. + + Notes + ----- + The cosine distance is equivalent to the half the squared + euclidean distance if each sample is normalized to unit norm. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_cosine_distances + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> paired_cosine_distances(X, Y) + array([0.5 , 0.184]) + """ + X, Y = check_paired_arrays(X, Y) + return 0.5 * row_norms(normalize(X) - normalize(Y), squared=True) + + +PAIRED_DISTANCES = { + "cosine": paired_cosine_distances, + "euclidean": paired_euclidean_distances, + "l2": paired_euclidean_distances, + "l1": paired_manhattan_distances, + "manhattan": paired_manhattan_distances, + "cityblock": paired_manhattan_distances, +} + + +@validate_params( + { + "X": ["array-like"], + "Y": ["array-like"], + "metric": [StrOptions(set(PAIRED_DISTANCES)), callable], + }, + prefer_skip_nested_validation=True, +) +def paired_distances(X, Y, *, metric="euclidean", **kwds): + """ + Compute the paired distances between X and Y. + + Compute the distances between (X[0], Y[0]), (X[1], Y[1]), etc... + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + Array 1 for distance computation. + + Y : ndarray of shape (n_samples, n_features) + Array 2 for distance computation. + + metric : str or callable, default="euclidean" + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + specified in PAIRED_DISTANCES, including "euclidean", + "manhattan", or "cosine". + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from `X` as input and return a value indicating + the distance between them. + + **kwds : dict + Unused parameters. + + Returns + ------- + distances : ndarray of shape (n_samples,) + Returns the distances between the row vectors of `X` + and the row vectors of `Y`. + + See Also + -------- + sklearn.metrics.pairwise_distances : Computes the distance between every pair of + samples. + + Examples + -------- + >>> from sklearn.metrics.pairwise import paired_distances + >>> X = [[0, 1], [1, 1]] + >>> Y = [[0, 1], [2, 1]] + >>> paired_distances(X, Y) + array([0., 1.]) + """ + + if metric in PAIRED_DISTANCES: + func = PAIRED_DISTANCES[metric] + return func(X, Y) + elif callable(metric): + # Check the matrix first (it is usually done by the metric) + X, Y = check_paired_arrays(X, Y) + distances = np.zeros(len(X)) + for i in range(len(X)): + distances[i] = metric(X[i], Y[i]) + return distances + + +# Kernels +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "dense_output": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def linear_kernel(X, Y=None, dense_output=True): + """ + Compute the linear kernel between X and Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + dense_output : bool, default=True + Whether to return dense output even when the input is sparse. If + ``False``, the output is sparse if both input arrays are sparse. + + .. versionadded:: 0.20 + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + The Gram matrix of the linear kernel, i.e. `X @ Y.T`. + + Examples + -------- + >>> from sklearn.metrics.pairwise import linear_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> linear_kernel(X, Y) + array([[0., 0.], + [1., 2.]]) + """ + X, Y = check_pairwise_arrays(X, Y) + return safe_sparse_dot(X, Y.T, dense_output=dense_output) + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "degree": [Interval(Real, 1, None, closed="left")], + "gamma": [ + Interval(Real, 0, None, closed="left"), + None, + Hidden(np.ndarray), + ], + "coef0": [Interval(Real, None, None, closed="neither")], + }, + prefer_skip_nested_validation=True, +) +def polynomial_kernel(X, Y=None, degree=3, gamma=None, coef0=1): + """ + Compute the polynomial kernel between X and Y. + + .. code-block:: text + + K(X, Y) = (gamma + coef0) ^ degree + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + degree : float, default=3 + Kernel degree. + + gamma : float, default=None + Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. + + coef0 : float, default=1 + Constant offset added to scaled inner product. + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + The polynomial kernel. + + Examples + -------- + >>> from sklearn.metrics.pairwise import polynomial_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> polynomial_kernel(X, Y, degree=2) + array([[1. , 1. ], + [1.77, 2.77]]) + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = safe_sparse_dot(X, Y.T, dense_output=True) + K *= gamma + K += coef0 + K **= degree + return K + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "gamma": [ + Interval(Real, 0, None, closed="left"), + None, + Hidden(np.ndarray), + ], + "coef0": [Interval(Real, None, None, closed="neither")], + }, + prefer_skip_nested_validation=True, +) +def sigmoid_kernel(X, Y=None, gamma=None, coef0=1): + """Compute the sigmoid kernel between X and Y. + + .. code-block:: text + + K(X, Y) = tanh(gamma + coef0) + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + Coefficient of the vector inner product. If None, defaults to 1.0 / n_features. + + coef0 : float, default=1 + Constant offset added to scaled inner product. + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + Sigmoid kernel between two arrays. + + Examples + -------- + >>> from sklearn.metrics.pairwise import sigmoid_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> sigmoid_kernel(X, Y) + array([[0.76, 0.76], + [0.87, 0.93]]) + """ + xp, _ = get_namespace(X, Y) + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = safe_sparse_dot(X, Y.T, dense_output=True) + K *= gamma + K += coef0 + # compute tanh in-place for numpy + K = _modify_in_place_if_numpy(xp, xp.tanh, K, out=K) + return K + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "gamma": [ + Interval(Real, 0, None, closed="left"), + None, + Hidden(np.ndarray), + ], + }, + prefer_skip_nested_validation=True, +) +def rbf_kernel(X, Y=None, gamma=None): + """Compute the rbf (gaussian) kernel between X and Y. + + .. code-block:: text + + K(x, y) = exp(-gamma ||x-y||^2) + + for each pair of rows x in X and y in Y. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + If None, defaults to 1.0 / n_features. + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + The RBF kernel. + + Examples + -------- + >>> from sklearn.metrics.pairwise import rbf_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> rbf_kernel(X, Y) + array([[0.71, 0.51], + [0.51, 0.71]]) + """ + xp, _ = get_namespace(X, Y) + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = euclidean_distances(X, Y, squared=True) + K *= -gamma + # exponentiate K in-place when using numpy + K = _modify_in_place_if_numpy(xp, xp.exp, K, out=K) + return K + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "gamma": [ + Interval(Real, 0, None, closed="neither"), + Hidden(np.ndarray), + None, + ], + }, + prefer_skip_nested_validation=True, +) +def laplacian_kernel(X, Y=None, gamma=None): + """Compute the laplacian kernel between X and Y. + + The laplacian kernel is defined as: + + .. code-block:: text + + K(x, y) = exp(-gamma ||x-y||_1) + + for each pair of rows x in X and y in Y. + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.17 + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + A feature array. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=None + If None, defaults to 1.0 / n_features. Otherwise it should be strictly positive. + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + The kernel matrix. + + Examples + -------- + >>> from sklearn.metrics.pairwise import laplacian_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> laplacian_kernel(X, Y) + array([[0.71, 0.51], + [0.51, 0.71]]) + """ + X, Y = check_pairwise_arrays(X, Y) + if gamma is None: + gamma = 1.0 / X.shape[1] + + K = -gamma * manhattan_distances(X, Y) + np.exp(K, K) # exponentiate K in-place + return K + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "dense_output": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def cosine_similarity(X, Y=None, dense_output=True): + """Compute cosine similarity between samples in X and Y. + + Cosine similarity, or the cosine kernel, computes similarity as the + normalized dot product of X and Y: + + .. code-block:: text + + K(X, Y) = / (||X||*||Y||) + + On L2-normalized data, this function is equivalent to linear_kernel. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_features) + Input data. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), \ + default=None + Input data. If ``None``, the output will be the pairwise + similarities between all samples in ``X``. + + dense_output : bool, default=True + Whether to return dense output even when the input is sparse. If + ``False``, the output is sparse if both input arrays are sparse. + + .. versionadded:: 0.17 + parameter ``dense_output`` for dense output. + + Returns + ------- + similarities : ndarray or sparse matrix of shape (n_samples_X, n_samples_Y) + Returns the cosine similarity between samples in X and Y. + + Examples + -------- + >>> from sklearn.metrics.pairwise import cosine_similarity + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> cosine_similarity(X, Y) + array([[0. , 0. ], + [0.577, 0.816]]) + """ + X, Y = check_pairwise_arrays(X, Y) + + X_normalized = normalize(X, copy=True) + if X is Y: + Y_normalized = X_normalized + else: + Y_normalized = normalize(Y, copy=True) + + K = safe_sparse_dot(X_normalized, Y_normalized.T, dense_output=dense_output) + + return K + + +@validate_params( + {"X": ["array-like"], "Y": ["array-like", None]}, + prefer_skip_nested_validation=True, +) +def additive_chi2_kernel(X, Y=None): + """Compute the additive chi-squared kernel between observations in X and Y. + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by: + + .. code-block:: text + + k(x, y) = -Sum [(x - y)^2 / (x + y)] + + It can be interpreted as a weighted difference per entry. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + A feature array. + + Y : array-like of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + Returns + ------- + kernel : array-like of shape (n_samples_X, n_samples_Y) + The kernel matrix. + + See Also + -------- + chi2_kernel : The exponentiated version of the kernel, which is usually + preferable. + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to this kernel. + + Notes + ----- + As the negative of a distance, this kernel is only conditionally positive + definite. + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + https://hal.archives-ouvertes.fr/hal-00171412/document + + Examples + -------- + >>> from sklearn.metrics.pairwise import additive_chi2_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> additive_chi2_kernel(X, Y) + array([[-1., -2.], + [-2., -1.]]) + """ + xp, _, device_ = get_namespace_and_device(X, Y) + X, Y = check_pairwise_arrays(X, Y, accept_sparse=False) + if xp.any(X < 0): + raise ValueError("X contains negative values.") + if Y is not X and xp.any(Y < 0): + raise ValueError("Y contains negative values.") + + if _is_numpy_namespace(xp): + result = np.zeros((X.shape[0], Y.shape[0]), dtype=X.dtype) + _chi2_kernel_fast(X, Y, result) + return result + else: + dtype = _find_matching_floating_dtype(X, Y, xp=xp) + xb = X[:, None, :] + yb = Y[None, :, :] + nom = -((xb - yb) ** 2) + denom = xb + yb + nom = xp.where(denom == 0, xp.asarray(0, dtype=dtype, device=device_), nom) + denom = xp.where(denom == 0, xp.asarray(1, dtype=dtype, device=device_), denom) + return xp.sum(nom / denom, axis=2) + + +@validate_params( + { + "X": ["array-like"], + "Y": ["array-like", None], + "gamma": [Interval(Real, 0, None, closed="neither"), Hidden(np.ndarray)], + }, + prefer_skip_nested_validation=True, +) +def chi2_kernel(X, Y=None, gamma=1.0): + """Compute the exponential chi-squared kernel between X and Y. + + The chi-squared kernel is computed between each pair of rows in X and Y. X + and Y have to be non-negative. This kernel is most commonly applied to + histograms. + + The chi-squared kernel is given by: + + .. code-block:: text + + k(x, y) = exp(-gamma Sum [(x - y)^2 / (x + y)]) + + It can be interpreted as a weighted difference per entry. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : array-like of shape (n_samples_X, n_features) + A feature array. + + Y : array-like of shape (n_samples_Y, n_features), default=None + An optional second feature array. If `None`, uses `Y=X`. + + gamma : float, default=1 + Scaling parameter of the chi2 kernel. + + Returns + ------- + kernel : ndarray of shape (n_samples_X, n_samples_Y) + The kernel matrix. + + See Also + -------- + additive_chi2_kernel : The additive version of this kernel. + sklearn.kernel_approximation.AdditiveChi2Sampler : A Fourier approximation + to the additive version of this kernel. + + References + ---------- + * Zhang, J. and Marszalek, M. and Lazebnik, S. and Schmid, C. + Local features and kernels for classification of texture and object + categories: A comprehensive study + International Journal of Computer Vision 2007 + https://hal.archives-ouvertes.fr/hal-00171412/document + + Examples + -------- + >>> from sklearn.metrics.pairwise import chi2_kernel + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> chi2_kernel(X, Y) + array([[0.368, 0.135], + [0.135, 0.368]]) + """ + xp, _ = get_namespace(X, Y) + K = additive_chi2_kernel(X, Y) + K *= gamma + if _is_numpy_namespace(xp): + return np.exp(K, out=K) + return xp.exp(K) + + +# Helper functions - distance +PAIRWISE_DISTANCE_FUNCTIONS = { + # If updating this dictionary, update the doc in both distance_metrics() + # and also in pairwise_distances()! + "cityblock": manhattan_distances, + "cosine": cosine_distances, + "euclidean": euclidean_distances, + "haversine": haversine_distances, + "l2": euclidean_distances, + "l1": manhattan_distances, + "manhattan": manhattan_distances, + "precomputed": None, # HACK: precomputed is always allowed, never called + "nan_euclidean": nan_euclidean_distances, +} + + +def distance_metrics(): + """Valid metrics for pairwise_distances. + + This function simply returns the valid pairwise distance metrics. + It exists to allow for a description of the mapping for + each of the valid strings. + + The valid distance metrics, and the function they map to, are: + + =============== ======================================== + metric Function + =============== ======================================== + 'cityblock' metrics.pairwise.manhattan_distances + 'cosine' metrics.pairwise.cosine_distances + 'euclidean' metrics.pairwise.euclidean_distances + 'haversine' metrics.pairwise.haversine_distances + 'l1' metrics.pairwise.manhattan_distances + 'l2' metrics.pairwise.euclidean_distances + 'manhattan' metrics.pairwise.manhattan_distances + 'nan_euclidean' metrics.pairwise.nan_euclidean_distances + =============== ======================================== + + Read more in the :ref:`User Guide `. + + Returns + ------- + distance_metrics : dict + Returns valid metrics for pairwise_distances. + """ + return PAIRWISE_DISTANCE_FUNCTIONS + + +def _dist_wrapper(dist_func, dist_matrix, slice_, *args, **kwargs): + """Write in-place to a slice of a distance matrix.""" + dist_matrix[:, slice_] = dist_func(*args, **kwargs) + + +def _parallel_pairwise(X, Y, func, n_jobs, **kwds): + """Break the pairwise matrix in n_jobs even slices + and compute them using multithreading.""" + + if Y is None: + Y = X + X, Y, dtype = _return_float_dtype(X, Y) + + if effective_n_jobs(n_jobs) == 1: + return func(X, Y, **kwds) + + # enforce a threading backend to prevent data communication overhead + fd = delayed(_dist_wrapper) + ret = np.empty((X.shape[0], Y.shape[0]), dtype=dtype, order="F") + Parallel(backend="threading", n_jobs=n_jobs)( + fd(func, ret, s, X, Y[s], **kwds) + for s in gen_even_slices(_num_samples(Y), effective_n_jobs(n_jobs)) + ) + + if (X is Y or Y is None) and func is euclidean_distances: + # zeroing diagonal for euclidean norm. + # TODO: do it also for other norms. + np.fill_diagonal(ret, 0) + + return ret + + +def _pairwise_callable(X, Y, metric, ensure_all_finite=True, **kwds): + """Handle the callable case for pairwise_{distances,kernels}.""" + X, Y = check_pairwise_arrays( + X, + Y, + dtype=None, + ensure_all_finite=ensure_all_finite, + # No input dimension checking done for custom metrics (left to user) + ensure_2d=False, + ) + + if X is Y: + # Only calculate metric for upper triangle + out = np.zeros((X.shape[0], Y.shape[0]), dtype="float") + iterator = itertools.combinations(range(X.shape[0]), 2) + for i, j in iterator: + # scipy has not yet implemented 1D sparse slices; once implemented this can + # be removed and `arr[ind]` can be simply used. + x = X[[i], :] if issparse(X) else X[i] + y = Y[[j], :] if issparse(Y) else Y[j] + out[i, j] = metric(x, y, **kwds) + + # Make symmetric + # NB: out += out.T will produce incorrect results + out = out + out.T + + # Calculate diagonal + # NB: nonzero diagonals are allowed for both metrics and kernels + for i in range(X.shape[0]): + # scipy has not yet implemented 1D sparse slices; once implemented this can + # be removed and `arr[ind]` can be simply used. + x = X[[i], :] if issparse(X) else X[i] + out[i, i] = metric(x, x, **kwds) + + else: + # Calculate all cells + out = np.empty((X.shape[0], Y.shape[0]), dtype="float") + iterator = itertools.product(range(X.shape[0]), range(Y.shape[0])) + for i, j in iterator: + # scipy has not yet implemented 1D sparse slices; once implemented this can + # be removed and `arr[ind]` can be simply used. + x = X[[i], :] if issparse(X) else X[i] + y = Y[[j], :] if issparse(Y) else Y[j] + out[i, j] = metric(x, y, **kwds) + + return out + + +def _check_chunk_size(reduced, chunk_size): + """Checks chunk is a sequence of expected size or a tuple of same.""" + if reduced is None: + return + is_tuple = isinstance(reduced, tuple) + if not is_tuple: + reduced = (reduced,) + if any(isinstance(r, tuple) or not hasattr(r, "__iter__") for r in reduced): + raise TypeError( + "reduce_func returned %r. Expected sequence(s) of length %d." + % (reduced if is_tuple else reduced[0], chunk_size) + ) + if any(_num_samples(r) != chunk_size for r in reduced): + actual_size = tuple(_num_samples(r) for r in reduced) + raise ValueError( + "reduce_func returned object of length %s. " + "Expected same length as input: %d." + % (actual_size if is_tuple else actual_size[0], chunk_size) + ) + + +def _precompute_metric_params(X, Y, metric=None, **kwds): + """Precompute data-derived metric parameters if not provided.""" + if metric == "seuclidean" and "V" not in kwds: + if X is Y: + V = np.var(X, axis=0, ddof=1) + else: + raise ValueError( + "The 'V' parameter is required for the seuclidean metric " + "when Y is passed." + ) + return {"V": V} + if metric == "mahalanobis" and "VI" not in kwds: + if X is Y: + VI = np.linalg.inv(np.cov(X.T)).T + else: + raise ValueError( + "The 'VI' parameter is required for the mahalanobis metric " + "when Y is passed." + ) + return {"VI": VI} + return {} + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "reduce_func": [callable, None], + "metric": [StrOptions({"precomputed"}.union(_VALID_METRICS)), callable], + "n_jobs": [Integral, None], + "working_memory": [Interval(Real, 0, None, closed="left"), None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def pairwise_distances_chunked( + X, + Y=None, + *, + reduce_func=None, + metric="euclidean", + n_jobs=None, + working_memory=None, + **kwds, +): + """Generate a distance matrix chunk by chunk with optional reduction. + + In cases where not all of a pairwise distance matrix needs to be + stored at once, this is used to calculate pairwise distances in + ``working_memory``-sized chunks. If ``reduce_func`` is given, it is + run on each chunk and its return values are concatenated into lists, + arrays or sparse matrices. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_features) + Array of pairwise distances between samples, or a feature array. + The shape the array should be (n_samples_X, n_samples_X) if + metric='precomputed' and (n_samples_X, n_features) otherwise. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. Only allowed if + metric != "precomputed". + + reduce_func : callable, default=None + The function which is applied on each chunk of the distance matrix, + reducing it to needed values. ``reduce_func(D_chunk, start)`` + is called repeatedly, where ``D_chunk`` is a contiguous vertical + slice of the pairwise distance matrix, starting at row ``start``. + It should return one of: None; an array, a list, or a sparse matrix + of length ``D_chunk.shape[0]``; or a tuple of such objects. + Returning None is useful for in-place operations, rather than + reductions. + + If None, pairwise_distances_chunked returns a generator of vertical + chunks of the distance matrix. + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by :func:`scipy.spatial.distance.pdist` for its metric parameter, + or a metric listed in pairwise.PAIRWISE_DISTANCE_FUNCTIONS. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on + each pair of instances (rows) and the resulting value recorded. + The callable should take two arrays from X as input and return a + value indicating the distance between them. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by + breaking down the pairwise matrix into n_jobs even slices and + computing them in parallel. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + working_memory : float, default=None + The sought maximum memory for temporary distance matrix chunks. + When None (default), the value of + ``sklearn.get_config()['working_memory']`` is used. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the distance function. + If using a :mod:`scipy.spatial.distance` metric, the parameters are still + metric dependent. See the scipy docs for usage examples. + + Yields + ------ + D_chunk : {ndarray, sparse matrix} + A contiguous slice of distance matrix, optionally processed by + ``reduce_func``. + + Examples + -------- + Without reduce_func: + + >>> import numpy as np + >>> from sklearn.metrics import pairwise_distances_chunked + >>> X = np.random.RandomState(0).rand(5, 3) + >>> D_chunk = next(pairwise_distances_chunked(X)) + >>> D_chunk + array([[0. , 0.295, 0.417, 0.197, 0.572], + [0.295, 0. , 0.576, 0.419, 0.764], + [0.417, 0.576, 0. , 0.449, 0.903], + [0.197, 0.419, 0.449, 0. , 0.512], + [0.572, 0.764, 0.903, 0.512, 0. ]]) + + Retrieve all neighbors and average distance within radius r: + + >>> r = .2 + >>> def reduce_func(D_chunk, start): + ... neigh = [np.flatnonzero(d < r) for d in D_chunk] + ... avg_dist = (D_chunk * (D_chunk < r)).mean(axis=1) + ... return neigh, avg_dist + >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func) + >>> neigh, avg_dist = next(gen) + >>> neigh + [array([0, 3]), array([1]), array([2]), array([0, 3]), array([4])] + >>> avg_dist + array([0.039, 0. , 0. , 0.039, 0. ]) + + Where r is defined per sample, we need to make use of ``start``: + + >>> r = [.2, .4, .4, .3, .1] + >>> def reduce_func(D_chunk, start): + ... neigh = [np.flatnonzero(d < r[i]) + ... for i, d in enumerate(D_chunk, start)] + ... return neigh + >>> neigh = next(pairwise_distances_chunked(X, reduce_func=reduce_func)) + >>> neigh + [array([0, 3]), array([0, 1]), array([2]), array([0, 3]), array([4])] + + Force row-by-row generation by reducing ``working_memory``: + + >>> gen = pairwise_distances_chunked(X, reduce_func=reduce_func, + ... working_memory=0) + >>> next(gen) + [array([0, 3])] + >>> next(gen) + [array([0, 1])] + """ + n_samples_X = _num_samples(X) + if metric == "precomputed": + slices = (slice(0, n_samples_X),) + else: + if Y is None: + Y = X + # We get as many rows as possible within our working_memory budget to + # store len(Y) distances in each row of output. + # + # Note: + # - this will get at least 1 row, even if 1 row of distances will + # exceed working_memory. + # - this does not account for any temporary memory usage while + # calculating distances (e.g. difference of vectors in manhattan + # distance. + chunk_n_rows = get_chunk_n_rows( + row_bytes=8 * _num_samples(Y), + max_n_rows=n_samples_X, + working_memory=working_memory, + ) + slices = gen_batches(n_samples_X, chunk_n_rows) + + # precompute data-derived metric params + params = _precompute_metric_params(X, Y, metric=metric, **kwds) + kwds.update(**params) + + for sl in slices: + if sl.start == 0 and sl.stop == n_samples_X: + X_chunk = X # enable optimised paths for X is Y + else: + X_chunk = X[sl] + D_chunk = pairwise_distances(X_chunk, Y, metric=metric, n_jobs=n_jobs, **kwds) + if (X is Y or Y is None) and PAIRWISE_DISTANCE_FUNCTIONS.get( + metric, None + ) is euclidean_distances: + # zeroing diagonal, taking care of aliases of "euclidean", + # i.e. "l2" + D_chunk.flat[sl.start :: _num_samples(X) + 1] = 0 + if reduce_func is not None: + chunk_size = D_chunk.shape[0] + D_chunk = reduce_func(D_chunk, sl.start) + _check_chunk_size(D_chunk, chunk_size) + yield D_chunk + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "metric": [StrOptions(set(_VALID_METRICS) | {"precomputed"}), callable], + "n_jobs": [Integral, None], + "force_all_finite": [ + "boolean", + StrOptions({"allow-nan"}), + Hidden(StrOptions({"deprecated"})), + ], + "ensure_all_finite": ["boolean", StrOptions({"allow-nan"}), Hidden(None)], + }, + prefer_skip_nested_validation=True, +) +def pairwise_distances( + X, + Y=None, + metric="euclidean", + *, + n_jobs=None, + force_all_finite="deprecated", + ensure_all_finite=None, + **kwds, +): + """Compute the distance matrix from a feature array X and optional Y. + + This function takes one or two feature arrays or a distance matrix, and returns + a distance matrix. + + - If `X` is a feature array, of shape (n_samples_X, n_features), and: + + - `Y` is `None` and `metric` is not 'precomputed', the pairwise distances + between `X` and itself are returned. + - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise + distances between `X` and `Y` is returned. + + - If `X` is a distance matrix, of shape (n_samples_X, n_samples_X), `metric` + should be 'precomputed'. `Y` is thus ignored and `X` is returned as is. + + If the input is a collection of non-numeric data (e.g. a list of strings or a + boolean array), a custom metric must be passed. + + This method provides a safe way to take a distance matrix as input, while + preserving compatibility with many other algorithms that take a vector + array. + + Valid values for metric are: + + - From scikit-learn: ['cityblock', 'cosine', 'euclidean', 'l1', 'l2', + 'manhattan', 'nan_euclidean']. All metrics support sparse matrix + inputs except 'nan_euclidean'. + + - From :mod:`scipy.spatial.distance`: ['braycurtis', 'canberra', 'chebyshev', + 'correlation', 'dice', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', + 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', + 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule']. + These metrics do not support sparse matrix inputs. + + .. note:: + `'kulsinski'` is deprecated from SciPy 1.9 and will be removed in SciPy 1.11. + + .. note:: + `'matching'` has been removed in SciPy 1.9 (use `'hamming'` instead). + + Note that in the case of 'cityblock', 'cosine' and 'euclidean' (which are + valid :mod:`scipy.spatial.distance` metrics), the scikit-learn implementation + will be used, which is faster and has support for sparse matrices (except + for 'cityblock'). For a verbose description of the metrics from + scikit-learn, see :func:`sklearn.metrics.pairwise.distance_metrics` + function. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_features) + Array of pairwise distances between samples, or a feature array. + The shape of the array should be (n_samples_X, n_samples_X) if + metric == "precomputed" and (n_samples_X, n_features) otherwise. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + An optional second feature array. Only allowed if + metric != "precomputed". + + metric : str or callable, default='euclidean' + The metric to use when calculating distance between instances in a + feature array. If metric is a string, it must be one of the options + allowed by :func:`scipy.spatial.distance.pdist` for its metric parameter, or + a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. + If metric is "precomputed", X is assumed to be a distance matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two arrays from X as input and return a value indicating + the distance between them. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them + using multithreading. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + The "euclidean" and "cosine" metrics rely heavily on BLAS which is already + multithreaded. So, increasing `n_jobs` would likely cause oversubscription + and quickly degrade performance. + + force_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored + for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 0.22 + ``force_all_finite`` accepts the string ``'allow-nan'``. + + .. versionchanged:: 0.23 + Accepts `pd.NA` and converts it into `np.nan`. + + .. deprecated:: 1.6 + `force_all_finite` was renamed to `ensure_all_finite` and will be removed + in 1.8. + + ensure_all_finite : bool or 'allow-nan', default=True + Whether to raise an error on np.inf, np.nan, pd.NA in array. Ignored + for a metric listed in ``pairwise.PAIRWISE_DISTANCE_FUNCTIONS``. The + possibilities are: + + - True: Force all values of array to be finite. + - False: accepts np.inf, np.nan, pd.NA in array. + - 'allow-nan': accepts only np.nan and pd.NA values in array. Values + cannot be infinite. + + .. versionadded:: 1.6 + `force_all_finite` was renamed to `ensure_all_finite`. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the distance function. + If using a scipy.spatial.distance metric, the parameters are still + metric dependent. See the scipy docs for usage examples. + + Returns + ------- + D : ndarray of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_samples_Y) + A distance matrix D such that D_{i, j} is the distance between the + ith and jth vectors of the given matrix X, if Y is None. + If Y is not None, then D_{i, j} is the distance between the ith array + from X and the jth array from Y. + + See Also + -------- + pairwise_distances_chunked : Performs the same calculation as this + function, but returns a generator of chunks of the distance matrix, in + order to limit memory usage. + sklearn.metrics.pairwise.paired_distances : Computes the distances between + corresponding elements of two arrays. + + Notes + ----- + If metric is a callable, no restrictions are placed on `X` and `Y` dimensions. + + Examples + -------- + >>> from sklearn.metrics.pairwise import pairwise_distances + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> pairwise_distances(X, Y, metric='sqeuclidean') + array([[1., 2.], + [2., 1.]]) + """ + ensure_all_finite = _deprecate_force_all_finite(force_all_finite, ensure_all_finite) + + if metric == "precomputed": + X, _ = check_pairwise_arrays( + X, Y, precomputed=True, ensure_all_finite=ensure_all_finite + ) + + whom = ( + "`pairwise_distances`. Precomputed distance " + " need to have non-negative values." + ) + check_non_negative(X, whom=whom) + return X + elif metric in PAIRWISE_DISTANCE_FUNCTIONS: + func = PAIRWISE_DISTANCE_FUNCTIONS[metric] + elif callable(metric): + func = partial( + _pairwise_callable, + metric=metric, + ensure_all_finite=ensure_all_finite, + **kwds, + ) + else: + if issparse(X) or issparse(Y): + raise TypeError("scipy distance metrics do not support sparse matrices.") + + dtype = bool if metric in PAIRWISE_BOOLEAN_FUNCTIONS else "infer_float" + + if dtype is bool and (X.dtype != bool or (Y is not None and Y.dtype != bool)): + msg = "Data was converted to boolean for metric %s" % metric + warnings.warn(msg, DataConversionWarning) + + X, Y = check_pairwise_arrays( + X, Y, dtype=dtype, ensure_all_finite=ensure_all_finite + ) + + # precompute data-derived metric params + params = _precompute_metric_params(X, Y, metric=metric, **kwds) + kwds.update(**params) + + if effective_n_jobs(n_jobs) == 1 and X is Y: + return distance.squareform(distance.pdist(X, metric=metric, **kwds)) + func = partial(distance.cdist, metric=metric, **kwds) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) + + +# These distances require boolean arrays, when using scipy.spatial.distance +PAIRWISE_BOOLEAN_FUNCTIONS = [ + "dice", + "jaccard", + "rogerstanimoto", + "russellrao", + "sokalsneath", + "yule", +] +if sp_base_version < parse_version("1.17"): + # Deprecated in SciPy 1.15 and removed in SciPy 1.17 + PAIRWISE_BOOLEAN_FUNCTIONS += ["sokalmichener"] +if sp_base_version < parse_version("1.11"): + # Deprecated in SciPy 1.9 and removed in SciPy 1.11 + PAIRWISE_BOOLEAN_FUNCTIONS += ["kulsinski"] +if sp_base_version < parse_version("1.9"): + # Deprecated in SciPy 1.0 and removed in SciPy 1.9 + PAIRWISE_BOOLEAN_FUNCTIONS += ["matching"] + +# Helper functions - distance +PAIRWISE_KERNEL_FUNCTIONS = { + # If updating this dictionary, update the doc in both distance_metrics() + # and also in pairwise_distances()! + "additive_chi2": additive_chi2_kernel, + "chi2": chi2_kernel, + "linear": linear_kernel, + "polynomial": polynomial_kernel, + "poly": polynomial_kernel, + "rbf": rbf_kernel, + "laplacian": laplacian_kernel, + "sigmoid": sigmoid_kernel, + "cosine": cosine_similarity, +} + + +def kernel_metrics(): + """Valid metrics for pairwise_kernels. + + This function simply returns the valid pairwise distance metrics. + It exists, however, to allow for a verbose description of the mapping for + each of the valid strings. + + The valid distance metrics, and the function they map to, are: + =============== ======================================== + metric Function + =============== ======================================== + 'additive_chi2' sklearn.pairwise.additive_chi2_kernel + 'chi2' sklearn.pairwise.chi2_kernel + 'linear' sklearn.pairwise.linear_kernel + 'poly' sklearn.pairwise.polynomial_kernel + 'polynomial' sklearn.pairwise.polynomial_kernel + 'rbf' sklearn.pairwise.rbf_kernel + 'laplacian' sklearn.pairwise.laplacian_kernel + 'sigmoid' sklearn.pairwise.sigmoid_kernel + 'cosine' sklearn.pairwise.cosine_similarity + =============== ======================================== + + Read more in the :ref:`User Guide `. + + Returns + ------- + kernel_metrics : dict + Returns valid metrics for pairwise_kernels. + """ + return PAIRWISE_KERNEL_FUNCTIONS + + +KERNEL_PARAMS = { + "additive_chi2": (), + "chi2": frozenset(["gamma"]), + "cosine": (), + "linear": (), + "poly": frozenset(["gamma", "degree", "coef0"]), + "polynomial": frozenset(["gamma", "degree", "coef0"]), + "rbf": frozenset(["gamma"]), + "laplacian": frozenset(["gamma"]), + "sigmoid": frozenset(["gamma", "coef0"]), +} + + +@validate_params( + { + "X": ["array-like", "sparse matrix"], + "Y": ["array-like", "sparse matrix", None], + "metric": [ + StrOptions(set(PAIRWISE_KERNEL_FUNCTIONS) | {"precomputed"}), + callable, + ], + "filter_params": ["boolean"], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=True, +) +def pairwise_kernels( + X, Y=None, metric="linear", *, filter_params=False, n_jobs=None, **kwds +): + """Compute the kernel between arrays X and optional array Y. + + This function takes one or two feature arrays or a kernel matrix, and returns + a kernel matrix. + + - If `X` is a feature array, of shape (n_samples_X, n_features), and: + + - `Y` is `None` and `metric` is not 'precomputed', the pairwise kernels + between `X` and itself are returned. + - `Y` is a feature array of shape (n_samples_Y, n_features), the pairwise + kernels between `X` and `Y` is returned. + + - If `X` is a kernel matrix, of shape (n_samples_X, n_samples_X), `metric` + should be 'precomputed'. `Y` is thus ignored and `X` is returned as is. + + This method provides a safe way to take a kernel matrix as input, while + preserving compatibility with many other algorithms that take a vector + array. + + Valid values for metric are: + ['additive_chi2', 'chi2', 'linear', 'poly', 'polynomial', 'rbf', + 'laplacian', 'sigmoid', 'cosine'] + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples_X, n_samples_X) or \ + (n_samples_X, n_features) + Array of pairwise kernels between samples, or a feature array. + The shape of the array should be (n_samples_X, n_samples_X) if + metric == "precomputed" and (n_samples_X, n_features) otherwise. + + Y : {array-like, sparse matrix} of shape (n_samples_Y, n_features), default=None + A second feature array only if X has shape (n_samples_X, n_features). + + metric : str or callable, default="linear" + The metric to use when calculating kernel between instances in a + feature array. If metric is a string, it must be one of the metrics + in ``pairwise.PAIRWISE_KERNEL_FUNCTIONS``. + If metric is "precomputed", X is assumed to be a kernel matrix. + Alternatively, if metric is a callable function, it is called on each + pair of instances (rows) and the resulting value recorded. The callable + should take two rows from X as input and return the corresponding + kernel value as a single number. This means that callables from + :mod:`sklearn.metrics.pairwise` are not allowed, as they operate on + matrices, not single samples. Use the string identifying the kernel + instead. + + filter_params : bool, default=False + Whether to filter invalid parameters or not. + + n_jobs : int, default=None + The number of jobs to use for the computation. This works by breaking + down the pairwise matrix into n_jobs even slices and computing them + using multithreading. + + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + **kwds : optional keyword parameters + Any further parameters are passed directly to the kernel function. + + Returns + ------- + K : ndarray of shape (n_samples_X, n_samples_X) or (n_samples_X, n_samples_Y) + A kernel matrix K such that K_{i, j} is the kernel between the + ith and jth vectors of the given matrix X, if Y is None. + If Y is not None, then K_{i, j} is the kernel between the ith array + from X and the jth array from Y. + + Notes + ----- + If metric is a callable, no restrictions are placed on `X` and `Y` dimensions. + + Examples + -------- + >>> from sklearn.metrics.pairwise import pairwise_kernels + >>> X = [[0, 0, 0], [1, 1, 1]] + >>> Y = [[1, 0, 0], [1, 1, 0]] + >>> pairwise_kernels(X, Y, metric='linear') + array([[0., 0.], + [1., 2.]]) + """ + # import GPKernel locally to prevent circular imports + from ..gaussian_process.kernels import Kernel as GPKernel + + if metric == "precomputed": + X, _ = check_pairwise_arrays(X, Y, precomputed=True) + return X + elif isinstance(metric, GPKernel): + func = metric.__call__ + elif metric in PAIRWISE_KERNEL_FUNCTIONS: + if filter_params: + kwds = {k: kwds[k] for k in kwds if k in KERNEL_PARAMS[metric]} + func = PAIRWISE_KERNEL_FUNCTIONS[metric] + elif callable(metric): + func = partial(_pairwise_callable, metric=metric, **kwds) + + return _parallel_pairwise(X, Y, func, n_jobs, **kwds) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..b66353e5ecfab4973aca5456473dbb947b86b0a9 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_classification.py @@ -0,0 +1,3397 @@ +import re +import warnings +from functools import partial +from itertools import chain, permutations, product + +import numpy as np +import pytest +from scipy import linalg +from scipy.spatial.distance import hamming as sp_hamming +from scipy.stats import bernoulli + +from sklearn import datasets, svm +from sklearn.datasets import make_multilabel_classification +from sklearn.exceptions import UndefinedMetricWarning +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + class_likelihood_ratios, + classification_report, + cohen_kappa_score, + confusion_matrix, + f1_score, + fbeta_score, + hamming_loss, + hinge_loss, + jaccard_score, + log_loss, + make_scorer, + matthews_corrcoef, + multilabel_confusion_matrix, + precision_recall_fscore_support, + precision_score, + recall_score, + zero_one_loss, +) +from sklearn.metrics._classification import _check_targets, d2_log_loss_score +from sklearn.model_selection import cross_val_score +from sklearn.preprocessing import LabelBinarizer, label_binarize +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._mocking import MockDataFrame +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + ignore_warnings, +) +from sklearn.utils.extmath import _nanaverage +from sklearn.utils.fixes import CSC_CONTAINERS, CSR_CONTAINERS +from sklearn.utils.validation import check_random_state + +############################################################################### +# Utilities for testing + + +def make_prediction(dataset=None, binary=False): + """Make some classification predictions on a toy dataset using a SVC + + If binary is True restrict to a binary classification problem instead of a + multiclass classification problem + """ + + if dataset is None: + # import some data to play with + dataset = datasets.load_iris() + + X = dataset.data + y = dataset.target + + if binary: + # restrict to a binary classification task + X, y = X[y < 2], y[y < 2] + + n_samples, n_features = X.shape + p = np.arange(n_samples) + + rng = check_random_state(37) + rng.shuffle(p) + X, y = X[p], y[p] + half = int(n_samples / 2) + + # add noisy features to make the problem harder and avoid perfect results + rng = np.random.RandomState(0) + X = np.c_[X, rng.randn(n_samples, 200 * n_features)] + + # run classifier, get class probabilities and label predictions + clf = svm.SVC(kernel="linear", probability=True, random_state=0) + y_pred_proba = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) + + if binary: + # only interested in probabilities of the positive case + # XXX: do we really want a special API for the binary case? + y_pred_proba = y_pred_proba[:, 1] + + y_pred = clf.predict(X[half:]) + y_true = y[half:] + return y_true, y_pred, y_pred_proba + + +############################################################################### +# Tests + + +def test_classification_report_dictionary_output(): + # Test performance report with dictionary output + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with class names + expected_report = { + "setosa": { + "precision": 0.82608695652173914, + "recall": 0.79166666666666663, + "f1-score": 0.8085106382978724, + "support": 24, + }, + "versicolor": { + "precision": 0.33333333333333331, + "recall": 0.096774193548387094, + "f1-score": 0.15000000000000002, + "support": 31, + }, + "virginica": { + "precision": 0.41860465116279072, + "recall": 0.90000000000000002, + "f1-score": 0.57142857142857151, + "support": 20, + }, + "macro avg": { + "f1-score": 0.5099797365754813, + "precision": 0.5260083136726211, + "recall": 0.596146953405018, + "support": 75, + }, + "accuracy": 0.5333333333333333, + "weighted avg": { + "f1-score": 0.47310435663627154, + "precision": 0.5137535108414785, + "recall": 0.5333333333333333, + "support": 75, + }, + } + + report = classification_report( + y_true, + y_pred, + labels=np.arange(len(iris.target_names)), + target_names=iris.target_names, + output_dict=True, + ) + + # assert the 2 dicts are equal. + assert report.keys() == expected_report.keys() + for key in expected_report: + if key == "accuracy": + assert isinstance(report[key], float) + assert report[key] == expected_report[key] + else: + assert report[key].keys() == expected_report[key].keys() + for metric in expected_report[key]: + assert_almost_equal(expected_report[key][metric], report[key][metric]) + + assert isinstance(expected_report["setosa"]["precision"], float) + assert isinstance(expected_report["macro avg"]["precision"], float) + assert isinstance(expected_report["setosa"]["support"], int) + assert isinstance(expected_report["macro avg"]["support"], int) + + +def test_classification_report_output_dict_empty_input(): + report = classification_report(y_true=[], y_pred=[], output_dict=True) + expected_report = { + "accuracy": 0.0, + "macro avg": { + "f1-score": np.nan, + "precision": np.nan, + "recall": np.nan, + "support": 0, + }, + "weighted avg": { + "f1-score": np.nan, + "precision": np.nan, + "recall": np.nan, + "support": 0, + }, + } + assert isinstance(report, dict) + # assert the 2 dicts are equal. + assert report.keys() == expected_report.keys() + for key in expected_report: + if key == "accuracy": + assert isinstance(report[key], float) + assert report[key] == expected_report[key] + else: + assert report[key].keys() == expected_report[key].keys() + for metric in expected_report[key]: + assert_almost_equal(expected_report[key][metric], report[key][metric]) + + +@pytest.mark.parametrize("zero_division", ["warn", 0, 1, np.nan]) +def test_classification_report_zero_division_warning(zero_division): + y_true, y_pred = ["a", "b", "c"], ["a", "b", "d"] + with warnings.catch_warnings(record=True) as record: + classification_report( + y_true, y_pred, zero_division=zero_division, output_dict=True + ) + if zero_division == "warn": + assert len(record) > 1 + for item in record: + msg = "Use `zero_division` parameter to control this behavior." + assert msg in str(item.message) + else: + assert not record + + +@pytest.mark.parametrize( + "labels, show_micro_avg", [([0], True), ([0, 1], False), ([0, 1, 2], False)] +) +def test_classification_report_labels_subset_superset(labels, show_micro_avg): + """Check the behaviour of passing `labels` as a superset or subset of the labels. + WHen a superset, we expect to show the "accuracy" in the report while it should be + the micro-averaging if this is a subset. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27927 + """ + + y_true, y_pred = [0, 1], [0, 1] + + report = classification_report(y_true, y_pred, labels=labels, output_dict=True) + if show_micro_avg: + assert "micro avg" in report + assert "accuracy" not in report + else: # accuracy should be shown + assert "accuracy" in report + assert "micro avg" not in report + + +def test_multilabel_accuracy_score_subset_accuracy(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + assert accuracy_score(y1, y2) == 0.5 + assert accuracy_score(y1, y1) == 1 + assert accuracy_score(y2, y2) == 1 + assert accuracy_score(y2, np.logical_not(y2)) == 0 + assert accuracy_score(y1, np.logical_not(y1)) == 0 + assert accuracy_score(y1, np.zeros(y1.shape)) == 0 + assert accuracy_score(y2, np.zeros(y1.shape)) == 0 + + +def test_precision_recall_f1_score_binary(): + # Test Precision Recall and F1 Score for binary classification task + y_true, y_pred, _ = make_prediction(binary=True) + + # detailed measures for each class + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + assert_array_almost_equal(p, [0.73, 0.85], 2) + assert_array_almost_equal(r, [0.88, 0.68], 2) + assert_array_almost_equal(f, [0.80, 0.76], 2) + assert_array_equal(s, [25, 25]) + + # individual scoring function that can be used for grid search: in the + # binary class case the score is the value of the measure for the positive + # class (e.g. label == 1). This is deprecated for average != 'binary'. + for kwargs in [{}, {"average": "binary"}]: + with warnings.catch_warnings(): + warnings.simplefilter("error") + + ps = precision_score(y_true, y_pred, **kwargs) + assert_array_almost_equal(ps, 0.85, 2) + + rs = recall_score(y_true, y_pred, **kwargs) + assert_array_almost_equal(rs, 0.68, 2) + + fs = f1_score(y_true, y_pred, **kwargs) + assert_array_almost_equal(fs, 0.76, 2) + + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, **kwargs), + (1 + 2**2) * ps * rs / (2**2 * ps + rs), + 2, + ) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_precision_recall_f_binary_single_class(): + # Test precision, recall and F-scores behave with a single positive or + # negative class + # Such a case may occur with non-stratified cross-validation + assert 1.0 == precision_score([1, 1], [1, 1]) + assert 1.0 == recall_score([1, 1], [1, 1]) + assert 1.0 == f1_score([1, 1], [1, 1]) + assert 1.0 == fbeta_score([1, 1], [1, 1], beta=0) + + assert 0.0 == precision_score([-1, -1], [-1, -1]) + assert 0.0 == recall_score([-1, -1], [-1, -1]) + assert 0.0 == f1_score([-1, -1], [-1, -1]) + assert 0.0 == fbeta_score([-1, -1], [-1, -1], beta=float("inf")) + assert fbeta_score([-1, -1], [-1, -1], beta=float("inf")) == pytest.approx( + fbeta_score([-1, -1], [-1, -1], beta=1e5) + ) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_precision_recall_f_extra_labels(): + # Test handling of explicit additional (not in input) labels to PRF + y_true = [1, 3, 3, 2] + y_pred = [1, 1, 3, 2] + y_true_bin = label_binarize(y_true, classes=np.arange(5)) + y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) + data = [(y_true, y_pred), (y_true_bin, y_pred_bin)] + + for i, (y_true, y_pred) in enumerate(data): + # No average: zeros in array + actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=None) + assert_array_almost_equal([0.0, 1.0, 1.0, 0.5, 0.0], actual) + + # Macro average is changed + actual = recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average="macro") + assert_array_almost_equal(np.mean([0.0, 1.0, 1.0, 0.5, 0.0]), actual) + + # No effect otherwise + for average in ["micro", "weighted", "samples"]: + if average == "samples" and i == 0: + continue + assert_almost_equal( + recall_score(y_true, y_pred, labels=[0, 1, 2, 3, 4], average=average), + recall_score(y_true, y_pred, labels=None, average=average), + ) + + # Error when introducing invalid label in multilabel case + # (although it would only affect performance if average='macro'/None) + for average in [None, "macro", "micro", "samples"]: + with pytest.raises(ValueError): + recall_score(y_true_bin, y_pred_bin, labels=np.arange(6), average=average) + with pytest.raises(ValueError): + recall_score( + y_true_bin, y_pred_bin, labels=np.arange(-1, 4), average=average + ) + + # tests non-regression on issue #10307 + y_true = np.array([[0, 1, 1], [1, 0, 0]]) + y_pred = np.array([[1, 1, 1], [1, 0, 1]]) + p, r, f, _ = precision_recall_fscore_support( + y_true, y_pred, average="samples", labels=[0, 1] + ) + assert_almost_equal(np.array([p, r, f]), np.array([3 / 4, 1, 5 / 6])) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_precision_recall_f_ignored_labels(): + # Test a subset of labels may be requested for PRF + y_true = [1, 1, 2, 3] + y_pred = [1, 3, 3, 3] + y_true_bin = label_binarize(y_true, classes=np.arange(5)) + y_pred_bin = label_binarize(y_pred, classes=np.arange(5)) + data = [(y_true, y_pred), (y_true_bin, y_pred_bin)] + + for i, (y_true, y_pred) in enumerate(data): + recall_13 = partial(recall_score, y_true, y_pred, labels=[1, 3]) + recall_all = partial(recall_score, y_true, y_pred, labels=None) + + assert_array_almost_equal([0.5, 1.0], recall_13(average=None)) + assert_almost_equal((0.5 + 1.0) / 2, recall_13(average="macro")) + assert_almost_equal((0.5 * 2 + 1.0 * 1) / 3, recall_13(average="weighted")) + assert_almost_equal(2.0 / 3, recall_13(average="micro")) + + # ensure the above were meaningful tests: + for average in ["macro", "weighted", "micro"]: + assert recall_13(average=average) != recall_all(average=average) + + +def test_average_precision_score_non_binary_class(): + """Test multiclass-multiouptut for `average_precision_score`.""" + y_true = np.array( + [ + [2, 2, 1], + [1, 2, 0], + [0, 1, 2], + [1, 2, 1], + [2, 0, 1], + [1, 2, 1], + ] + ) + y_score = np.array( + [ + [0.7, 0.2, 0.1], + [0.4, 0.3, 0.3], + [0.1, 0.8, 0.1], + [0.2, 0.3, 0.5], + [0.4, 0.4, 0.2], + [0.1, 0.2, 0.7], + ] + ) + err_msg = "multiclass-multioutput format is not supported" + with pytest.raises(ValueError, match=err_msg): + average_precision_score(y_true, y_score, pos_label=2) + + +@pytest.mark.parametrize( + "y_true, y_score", + [ + ( + [0, 0, 1, 2], + np.array( + [ + [0.7, 0.2, 0.1], + [0.4, 0.3, 0.3], + [0.1, 0.8, 0.1], + [0.2, 0.3, 0.5], + ] + ), + ), + ( + [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], + [0, 0.1, 0.1, 0.4, 0.5, 0.6, 0.6, 0.9, 0.9, 1, 1], + ), + ], +) +def test_average_precision_score_duplicate_values(y_true, y_score): + """ + Duplicate values with precision-recall require a different + processing than when computing the AUC of a ROC, because the + precision-recall curve is a decreasing curve + The following situation corresponds to a perfect + test statistic, the average_precision_score should be 1. + """ + assert average_precision_score(y_true, y_score) == 1 + + +@pytest.mark.parametrize( + "y_true, y_score", + [ + ( + [2, 2, 1, 1, 0], + np.array( + [ + [0.2, 0.3, 0.5], + [0.2, 0.3, 0.5], + [0.4, 0.5, 0.3], + [0.4, 0.5, 0.3], + [0.8, 0.5, 0.3], + ] + ), + ), + ( + [0, 1, 1], + [0.5, 0.5, 0.6], + ), + ], +) +def test_average_precision_score_tied_values(y_true, y_score): + # Here if we go from left to right in y_true, the 0 values are + # separated from the 1 values, so it appears that we've + # correctly sorted our classifications. But in fact the first two + # values have the same score (0.5) and so the first two values + # could be swapped around, creating an imperfect sorting. This + # imperfection should come through in the end score, making it less + # than one. + assert average_precision_score(y_true, y_score) != 1.0 + + +def test_precision_recall_f_unused_pos_label(): + # Check warning that pos_label unused when set to non-default value + # but average != 'binary'; even if data is binary. + + msg = ( + r"Note that pos_label \(set to 2\) is " + r"ignored when average != 'binary' \(got 'macro'\). You " + r"may use labels=\[pos_label\] to specify a single " + "positive class." + ) + with pytest.warns(UserWarning, match=msg): + precision_recall_fscore_support( + [1, 2, 1], [1, 2, 2], pos_label=2, average="macro" + ) + + +def test_confusion_matrix_binary(): + # Test confusion matrix - binary classification case + y_true, y_pred, _ = make_prediction(binary=True) + + def test(y_true, y_pred): + cm = confusion_matrix(y_true, y_pred) + assert_array_equal(cm, [[22, 3], [8, 17]]) + + tp, fp, fn, tn = cm.flatten() + num = tp * tn - fp * fn + den = np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) + + true_mcc = 0 if den == 0 else num / den + mcc = matthews_corrcoef(y_true, y_pred) + assert_array_almost_equal(mcc, true_mcc, decimal=2) + assert_array_almost_equal(mcc, 0.57, decimal=2) + + test(y_true, y_pred) + test([str(y) for y in y_true], [str(y) for y in y_pred]) + + +def test_multilabel_confusion_matrix_binary(): + # Test multilabel confusion matrix - binary classification case + y_true, y_pred, _ = make_prediction(binary=True) + + def test(y_true, y_pred): + cm = multilabel_confusion_matrix(y_true, y_pred) + assert_array_equal(cm, [[[17, 8], [3, 22]], [[22, 3], [8, 17]]]) + + test(y_true, y_pred) + test([str(y) for y in y_true], [str(y) for y in y_pred]) + + +def test_multilabel_confusion_matrix_multiclass(): + # Test multilabel confusion matrix - multi-class case + y_true, y_pred, _ = make_prediction(binary=False) + + def test(y_true, y_pred, string_type=False): + # compute confusion matrix with default labels introspection + cm = multilabel_confusion_matrix(y_true, y_pred) + assert_array_equal( + cm, [[[47, 4], [5, 19]], [[38, 6], [28, 3]], [[30, 25], [2, 18]]] + ) + + # compute confusion matrix with explicit label ordering + labels = ["0", "2", "1"] if string_type else [0, 2, 1] + cm = multilabel_confusion_matrix(y_true, y_pred, labels=labels) + assert_array_equal( + cm, [[[47, 4], [5, 19]], [[30, 25], [2, 18]], [[38, 6], [28, 3]]] + ) + + # compute confusion matrix with super set of present labels + labels = ["0", "2", "1", "3"] if string_type else [0, 2, 1, 3] + cm = multilabel_confusion_matrix(y_true, y_pred, labels=labels) + assert_array_equal( + cm, + [ + [[47, 4], [5, 19]], + [[30, 25], [2, 18]], + [[38, 6], [28, 3]], + [[75, 0], [0, 0]], + ], + ) + + test(y_true, y_pred) + test([str(y) for y in y_true], [str(y) for y in y_pred], string_type=True) + + +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_multilabel_confusion_matrix_multilabel(csc_container, csr_container): + # Test multilabel confusion matrix - multilabel-indicator case + + y_true = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]]) + y_pred = np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]]) + y_true_csr = csr_container(y_true) + y_pred_csr = csr_container(y_pred) + y_true_csc = csc_container(y_true) + y_pred_csc = csc_container(y_pred) + + # cross test different types + sample_weight = np.array([2, 1, 3]) + real_cm = [[[1, 0], [1, 1]], [[1, 0], [1, 1]], [[0, 2], [1, 0]]] + trues = [y_true, y_true_csr, y_true_csc] + preds = [y_pred, y_pred_csr, y_pred_csc] + + for y_true_tmp in trues: + for y_pred_tmp in preds: + cm = multilabel_confusion_matrix(y_true_tmp, y_pred_tmp) + assert_array_equal(cm, real_cm) + + # test support for samplewise + cm = multilabel_confusion_matrix(y_true, y_pred, samplewise=True) + assert_array_equal(cm, [[[1, 0], [1, 1]], [[1, 1], [0, 1]], [[0, 1], [2, 0]]]) + + # test support for labels + cm = multilabel_confusion_matrix(y_true, y_pred, labels=[2, 0]) + assert_array_equal(cm, [[[0, 2], [1, 0]], [[1, 0], [1, 1]]]) + + # test support for labels with samplewise + cm = multilabel_confusion_matrix(y_true, y_pred, labels=[2, 0], samplewise=True) + assert_array_equal(cm, [[[0, 0], [1, 1]], [[1, 1], [0, 0]], [[0, 1], [1, 0]]]) + + # test support for sample_weight with sample_wise + cm = multilabel_confusion_matrix( + y_true, y_pred, sample_weight=sample_weight, samplewise=True + ) + assert_array_equal(cm, [[[2, 0], [2, 2]], [[1, 1], [0, 1]], [[0, 3], [6, 0]]]) + + +def test_multilabel_confusion_matrix_errors(): + y_true = np.array([[1, 0, 1], [0, 1, 0], [1, 1, 0]]) + y_pred = np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]]) + + # Bad sample_weight + with pytest.raises(ValueError, match="inconsistent numbers of samples"): + multilabel_confusion_matrix(y_true, y_pred, sample_weight=[1, 2]) + with pytest.raises(ValueError, match="should be a 1d array"): + multilabel_confusion_matrix( + y_true, y_pred, sample_weight=[[1, 2, 3], [2, 3, 4], [3, 4, 5]] + ) + + # Bad labels + err_msg = r"All labels must be in \[0, n labels\)" + with pytest.raises(ValueError, match=err_msg): + multilabel_confusion_matrix(y_true, y_pred, labels=[-1]) + err_msg = r"All labels must be in \[0, n labels\)" + with pytest.raises(ValueError, match=err_msg): + multilabel_confusion_matrix(y_true, y_pred, labels=[3]) + + # Using samplewise outside multilabel + with pytest.raises(ValueError, match="Samplewise metrics"): + multilabel_confusion_matrix([0, 1, 2], [1, 2, 0], samplewise=True) + + # Bad y_type + err_msg = "multiclass-multioutput is not supported" + with pytest.raises(ValueError, match=err_msg): + multilabel_confusion_matrix([[0, 1, 2], [2, 1, 0]], [[1, 2, 0], [1, 0, 2]]) + + +@pytest.mark.parametrize( + "normalize, cm_dtype, expected_results", + [ + ("true", "f", 0.333333333), + ("pred", "f", 0.333333333), + ("all", "f", 0.1111111111), + (None, "i", 2), + ], +) +def test_confusion_matrix_normalize(normalize, cm_dtype, expected_results): + y_test = [0, 1, 2] * 6 + y_pred = list(chain(*permutations([0, 1, 2]))) + cm = confusion_matrix(y_test, y_pred, normalize=normalize) + assert_allclose(cm, expected_results) + assert cm.dtype.kind == cm_dtype + + +def test_confusion_matrix_normalize_single_class(): + y_test = [0, 0, 0, 0, 1, 1, 1, 1] + y_pred = [0, 0, 0, 0, 0, 0, 0, 0] + + cm_true = confusion_matrix(y_test, y_pred, normalize="true") + assert cm_true.sum() == pytest.approx(2.0) + + # additionally check that no warnings are raised due to a division by zero + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + cm_pred = confusion_matrix(y_test, y_pred, normalize="pred") + + assert cm_pred.sum() == pytest.approx(1.0) + + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + confusion_matrix(y_pred, y_test, normalize="true") + + +def test_confusion_matrix_single_label(): + """Test `confusion_matrix` warns when only one label found.""" + y_test = [0, 0, 0, 0] + y_pred = [0, 0, 0, 0] + + with pytest.warns(UserWarning, match="A single label was found in"): + confusion_matrix(y_pred, y_test) + + +@pytest.mark.parametrize( + "params, warn_msg", + [ + # When `fp == 0` and `tp != 0`, LR+ is undefined + ( + { + "y_true": np.array([1, 1, 1, 0, 0, 0]), + "y_pred": np.array([1, 1, 1, 0, 0, 0]), + }, + "`positive_likelihood_ratio` is ill-defined and set to `np.nan`.", + ), + # When `fp == 0` and `tp == 0`, LR+ is undefined + ( + { + "y_true": np.array([1, 1, 1, 0, 0, 0]), + "y_pred": np.array([0, 0, 0, 0, 0, 0]), + }, + ( + "No samples were predicted for the positive class and " + "`positive_likelihood_ratio` is set to `np.nan`." + ), + ), + # When `tn == 0`, LR- is undefined + ( + { + "y_true": np.array([1, 1, 1, 0, 0, 0]), + "y_pred": np.array([0, 0, 0, 1, 1, 1]), + }, + "`negative_likelihood_ratio` is ill-defined and set to `np.nan`.", + ), + # When `tp + fn == 0` both ratios are undefined + ( + { + "y_true": np.array([0, 0, 0, 0, 0, 0]), + "y_pred": np.array([1, 1, 1, 0, 0, 0]), + }, + "No samples of the positive class are present in `y_true`.", + ), + ], +) +def test_likelihood_ratios_warnings(params, warn_msg): + # likelihood_ratios must raise warnings when at + # least one of the ratios is ill-defined. + + with pytest.warns(UserWarning, match=warn_msg): + class_likelihood_ratios(**params) + + +@pytest.mark.parametrize( + "params, err_msg", + [ + ( + { + "y_true": np.array([0, 1, 0, 1, 0]), + "y_pred": np.array([1, 1, 0, 0, 2]), + }, + ( + "class_likelihood_ratios only supports binary classification " + "problems, got targets of type: multiclass" + ), + ), + ], +) +def test_likelihood_ratios_errors(params, err_msg): + # likelihood_ratios must raise error when attempting + # non-binary classes to avoid Simpson's paradox + with pytest.raises(ValueError, match=err_msg): + class_likelihood_ratios(**params) + + +def test_likelihood_ratios(): + # Build confusion matrix with tn=9, fp=8, fn=1, tp=2, + # sensitivity=2/3, specificity=9/17, prevalence=3/20, + # LR+=34/24, LR-=17/27 + y_true = np.array([1] * 3 + [0] * 17) + y_pred = np.array([1] * 2 + [0] * 10 + [1] * 8) + + pos, neg = class_likelihood_ratios(y_true, y_pred) + assert_allclose(pos, 34 / 24) + assert_allclose(neg, 17 / 27) + + # Build limit case with y_pred = y_true + pos, neg = class_likelihood_ratios(y_true, y_true) + assert_array_equal(pos, np.nan * 2) + assert_allclose(neg, np.zeros(2), rtol=1e-12) + + # Ignore last 5 samples to get tn=9, fp=3, fn=1, tp=2, + # sensitivity=2/3, specificity=9/12, prevalence=3/20, + # LR+=24/9, LR-=12/27 + sample_weight = np.array([1.0] * 15 + [0.0] * 5) + pos, neg = class_likelihood_ratios(y_true, y_pred, sample_weight=sample_weight) + assert_allclose(pos, 24 / 9) + assert_allclose(neg, 12 / 27) + + +# TODO(1.9): remove test +@pytest.mark.parametrize("raise_warning", [True, False]) +def test_likelihood_ratios_raise_warning_deprecation(raise_warning): + """Test that class_likelihood_ratios raises a `FutureWarning` when `raise_warning` + param is set.""" + y_true = np.array([1, 0]) + y_pred = np.array([1, 0]) + + msg = "`raise_warning` was deprecated in version 1.7 and will be removed in 1.9." + with pytest.warns(FutureWarning, match=msg): + class_likelihood_ratios(y_true, y_pred, raise_warning=raise_warning) + + +def test_likelihood_ratios_replace_undefined_by_worst(): + """Test that class_likelihood_ratios returns the worst scores `1.0` for both LR+ and + LR- when `replace_undefined_by=1` is set.""" + # This data causes fp=0 (0 false positives) in the confusion_matrix and a division + # by zero that affects the positive_likelihood_ratio: + y_true = np.array([1, 1, 0]) + y_pred = np.array([1, 0, 0]) + + positive_likelihood_ratio, _ = class_likelihood_ratios( + y_true, y_pred, replace_undefined_by=1 + ) + assert positive_likelihood_ratio == pytest.approx(1.0) + + # This data causes tn=0 (0 true negatives) in the confusion_matrix and a division + # by zero that affects the negative_likelihood_ratio: + y_true = np.array([1, 0, 0]) + y_pred = np.array([1, 1, 1]) + + _, negative_likelihood_ratio = class_likelihood_ratios( + y_true, y_pred, replace_undefined_by=1 + ) + assert negative_likelihood_ratio == pytest.approx(1.0) + + +@pytest.mark.parametrize( + "replace_undefined_by", + [ + {"LR+": 0.0}, + {"LR-": 0.0}, + {"LR+": -5.0, "LR-": 0.0}, + {"LR+": 1.0, "LR-": "nan"}, + {"LR+": 0.0, "LR-": 0.0}, + {"LR+": 1.0, "LR-": 2.0}, + ], +) +def test_likelihood_ratios_wrong_dict_replace_undefined_by(replace_undefined_by): + """Test that class_likelihood_ratios raises a `ValueError` if the input dict for + `replace_undefined_by` is in the wrong format or contains impossible values.""" + y_true = np.array([1, 0]) + y_pred = np.array([1, 0]) + + msg = "The dictionary passed as `replace_undefined_by` needs to be in the form" + with pytest.raises(ValueError, match=msg): + class_likelihood_ratios( + y_true, y_pred, replace_undefined_by=replace_undefined_by + ) + + +@pytest.mark.parametrize( + "replace_undefined_by, expected", + [ + ({"LR+": 1.0, "LR-": 1.0}, 1.0), + ({"LR+": np.inf, "LR-": 0.0}, np.inf), + ({"LR+": 2.0, "LR-": 0.0}, 2.0), + ({"LR+": np.nan, "LR-": np.nan}, np.nan), + (np.nan, np.nan), + ], +) +def test_likelihood_ratios_replace_undefined_by_0_fp(replace_undefined_by, expected): + """Test that the `replace_undefined_by` param returns the right value for the + positive_likelihood_ratio as defined by the user.""" + # This data causes fp=0 (0 false positives) in the confusion_matrix and a division + # by zero that affects the positive_likelihood_ratio: + y_true = np.array([1, 1, 0]) + y_pred = np.array([1, 0, 0]) + + positive_likelihood_ratio, _ = class_likelihood_ratios( + y_true, y_pred, replace_undefined_by=replace_undefined_by + ) + + if np.isnan(expected): + assert np.isnan(positive_likelihood_ratio) + else: + assert positive_likelihood_ratio == pytest.approx(expected) + + +@pytest.mark.parametrize( + "replace_undefined_by, expected", + [ + ({"LR+": 1.0, "LR-": 1.0}, 1.0), + ({"LR+": np.inf, "LR-": 0.0}, 0.0), + ({"LR+": np.inf, "LR-": 0.5}, 0.5), + ({"LR+": np.nan, "LR-": np.nan}, np.nan), + (np.nan, np.nan), + ], +) +def test_likelihood_ratios_replace_undefined_by_0_tn(replace_undefined_by, expected): + """Test that the `replace_undefined_by` param returns the right value for the + negative_likelihood_ratio as defined by the user.""" + # This data causes tn=0 (0 true negatives) in the confusion_matrix and a division + # by zero that affects the negative_likelihood_ratio: + y_true = np.array([1, 0, 0]) + y_pred = np.array([1, 1, 1]) + + _, negative_likelihood_ratio = class_likelihood_ratios( + y_true, y_pred, replace_undefined_by=replace_undefined_by + ) + + if np.isnan(expected): + assert np.isnan(negative_likelihood_ratio) + else: + assert negative_likelihood_ratio == pytest.approx(expected) + + +def test_cohen_kappa(): + # These label vectors reproduce the contingency matrix from Artstein and + # Poesio (2008), Table 1: np.array([[20, 20], [10, 50]]). + y1 = np.array([0] * 40 + [1] * 60) + y2 = np.array([0] * 20 + [1] * 20 + [0] * 10 + [1] * 50) + kappa = cohen_kappa_score(y1, y2) + assert_almost_equal(kappa, 0.348, decimal=3) + assert kappa == cohen_kappa_score(y2, y1) + + # Add spurious labels and ignore them. + y1 = np.append(y1, [2] * 4) + y2 = np.append(y2, [2] * 4) + assert cohen_kappa_score(y1, y2, labels=[0, 1]) == kappa + + assert_almost_equal(cohen_kappa_score(y1, y1), 1.0) + + # Multiclass example: Artstein and Poesio, Table 4. + y1 = np.array([0] * 46 + [1] * 44 + [2] * 10) + y2 = np.array([0] * 52 + [1] * 32 + [2] * 16) + assert_almost_equal(cohen_kappa_score(y1, y2), 0.8013, decimal=4) + + # Weighting example: none, linear, quadratic. + y1 = np.array([0] * 46 + [1] * 44 + [2] * 10) + y2 = np.array([0] * 50 + [1] * 40 + [2] * 10) + assert_almost_equal(cohen_kappa_score(y1, y2), 0.9315, decimal=4) + assert_almost_equal(cohen_kappa_score(y1, y2, weights="linear"), 0.9412, decimal=4) + assert_almost_equal( + cohen_kappa_score(y1, y2, weights="quadratic"), 0.9541, decimal=4 + ) + + +def test_cohen_kappa_score_error_wrong_label(): + """Test that correct error is raised when users pass labels that are not in y1.""" + labels = [1, 2] + y1 = np.array(["a"] * 5 + ["b"] * 5) + y2 = np.array(["b"] * 10) + with pytest.raises( + ValueError, match="At least one label in `labels` must be present in `y1`" + ): + cohen_kappa_score(y1, y2, labels=labels) + + +@pytest.mark.parametrize("zero_division", [0, 1, np.nan]) +@pytest.mark.parametrize("y_true, y_pred", [([0], [0])]) +@pytest.mark.parametrize( + "metric", + [ + f1_score, + partial(fbeta_score, beta=1), + precision_score, + recall_score, + ], +) +def test_zero_division_nan_no_warning(metric, y_true, y_pred, zero_division): + """Check the behaviour of `zero_division` when setting to 0, 1 or np.nan. + No warnings should be raised. + """ + with warnings.catch_warnings(): + warnings.simplefilter("error") + result = metric(y_true, y_pred, zero_division=zero_division) + + if np.isnan(zero_division): + assert np.isnan(result) + else: + assert result == zero_division + + +@pytest.mark.parametrize("y_true, y_pred", [([0], [0])]) +@pytest.mark.parametrize( + "metric", + [ + f1_score, + partial(fbeta_score, beta=1), + precision_score, + recall_score, + ], +) +def test_zero_division_nan_warning(metric, y_true, y_pred): + """Check the behaviour of `zero_division` when setting to "warn". + A `UndefinedMetricWarning` should be raised. + """ + with pytest.warns(UndefinedMetricWarning): + result = metric(y_true, y_pred, zero_division="warn") + assert result == 0.0 + + +def test_matthews_corrcoef_against_numpy_corrcoef(global_random_seed): + rng = np.random.RandomState(global_random_seed) + y_true = rng.randint(0, 2, size=20) + y_pred = rng.randint(0, 2, size=20) + + assert_almost_equal( + matthews_corrcoef(y_true, y_pred), np.corrcoef(y_true, y_pred)[0, 1], 10 + ) + + +def test_matthews_corrcoef_against_jurman(global_random_seed): + # Check that the multiclass matthews_corrcoef agrees with the definition + # presented in Jurman, Riccadonna, Furlanello, (2012). A Comparison of MCC + # and CEN Error Measures in MultiClass Prediction + rng = np.random.RandomState(global_random_seed) + y_true = rng.randint(0, 2, size=20) + y_pred = rng.randint(0, 2, size=20) + sample_weight = rng.rand(20) + + C = confusion_matrix(y_true, y_pred, sample_weight=sample_weight) + N = len(C) + cov_ytyp = sum( + [ + C[k, k] * C[m, l] - C[l, k] * C[k, m] + for k in range(N) + for m in range(N) + for l in range(N) + ] + ) + cov_ytyt = sum( + [ + C[:, k].sum() + * np.sum([C[g, f] for f in range(N) for g in range(N) if f != k]) + for k in range(N) + ] + ) + cov_ypyp = np.sum( + [ + C[k, :].sum() + * np.sum([C[f, g] for f in range(N) for g in range(N) if f != k]) + for k in range(N) + ] + ) + mcc_jurman = cov_ytyp / np.sqrt(cov_ytyt * cov_ypyp) + mcc_ours = matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight) + + assert_almost_equal(mcc_ours, mcc_jurman, 10) + + +def test_matthews_corrcoef(global_random_seed): + rng = np.random.RandomState(global_random_seed) + y_true = ["a" if i == 0 else "b" for i in rng.randint(0, 2, size=20)] + + # corrcoef of same vectors must be 1 + assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0) + + # corrcoef, when the two vectors are opposites of each other, should be -1 + y_true_inv = ["b" if i == "a" else "a" for i in y_true] + assert_almost_equal(matthews_corrcoef(y_true, y_true_inv), -1) + + y_true_inv2 = label_binarize(y_true, classes=["a", "b"]) + y_true_inv2 = np.where(y_true_inv2, "a", "b") + assert_almost_equal(matthews_corrcoef(y_true, y_true_inv2), -1) + + # For the zero vector case, the corrcoef cannot be calculated and should + # output 0 + assert_almost_equal(matthews_corrcoef([0, 0, 0, 0], [0, 0, 0, 0]), 0.0) + + # And also for any other vector with 0 variance + assert_almost_equal(matthews_corrcoef(y_true, ["a"] * len(y_true)), 0.0) + + # These two vectors have 0 correlation and hence mcc should be 0 + y_1 = [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1] + y_2 = [1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1] + assert_almost_equal(matthews_corrcoef(y_1, y_2), 0.0) + + # Check that sample weight is able to selectively exclude + mask = [1] * 10 + [0] * 10 + # Now the first half of the vector elements are alone given a weight of 1 + # and hence the mcc will not be a perfect 0 as in the previous case + with pytest.raises(AssertionError): + assert_almost_equal(matthews_corrcoef(y_1, y_2, sample_weight=mask), 0.0) + + +def test_matthews_corrcoef_multiclass(global_random_seed): + rng = np.random.RandomState(global_random_seed) + ord_a = ord("a") + n_classes = 4 + y_true = [chr(ord_a + i) for i in rng.randint(0, n_classes, size=20)] + + # corrcoef of same vectors must be 1 + assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0) + + # with multiclass > 2 it is not possible to achieve -1 + y_true = [0, 0, 1, 1, 2, 2] + y_pred_bad = [2, 2, 0, 0, 1, 1] + assert_almost_equal(matthews_corrcoef(y_true, y_pred_bad), -0.5) + + # Maximizing false positives and negatives minimizes the MCC + # The minimum will be different for depending on the input + y_true = [0, 0, 1, 1, 2, 2] + y_pred_min = [1, 1, 0, 0, 0, 0] + assert_almost_equal(matthews_corrcoef(y_true, y_pred_min), -12 / np.sqrt(24 * 16)) + + # Zero variance will result in an mcc of zero + y_true = [0, 1, 2] + y_pred = [3, 3, 3] + assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0) + + # Also for ground truth with zero variance + y_true = [3, 3, 3] + y_pred = [0, 1, 2] + assert_almost_equal(matthews_corrcoef(y_true, y_pred), 0.0) + + # These two vectors have 0 correlation and hence mcc should be 0 + y_1 = [0, 1, 2, 0, 1, 2, 0, 1, 2] + y_2 = [1, 1, 1, 2, 2, 2, 0, 0, 0] + assert_almost_equal(matthews_corrcoef(y_1, y_2), 0.0) + + # We can test that binary assumptions hold using the multiclass computation + # by masking the weight of samples not in the first two classes + + # Masking the last label should let us get an MCC of -1 + y_true = [0, 0, 1, 1, 2] + y_pred = [1, 1, 0, 0, 2] + sample_weight = [1, 1, 1, 1, 0] + assert_almost_equal( + matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight), -1 + ) + + # For the zero vector case, the corrcoef cannot be calculated and should + # output 0 + y_true = [0, 0, 1, 2] + y_pred = [0, 0, 1, 2] + sample_weight = [1, 1, 0, 0] + assert_almost_equal( + matthews_corrcoef(y_true, y_pred, sample_weight=sample_weight), 0.0 + ) + + +@pytest.mark.parametrize("n_points", [100, 10000]) +def test_matthews_corrcoef_overflow(n_points, global_random_seed): + # https://github.com/scikit-learn/scikit-learn/issues/9622 + rng = np.random.RandomState(global_random_seed) + + def mcc_safe(y_true, y_pred): + conf_matrix = confusion_matrix(y_true, y_pred) + true_pos = conf_matrix[1, 1] + false_pos = conf_matrix[1, 0] + false_neg = conf_matrix[0, 1] + n_points = len(y_true) + pos_rate = (true_pos + false_neg) / n_points + activity = (true_pos + false_pos) / n_points + mcc_numerator = true_pos / n_points - pos_rate * activity + mcc_denominator = activity * pos_rate * (1 - activity) * (1 - pos_rate) + return mcc_numerator / np.sqrt(mcc_denominator) + + def random_ys(n_points): # binary + x_true = rng.random_sample(n_points) + x_pred = x_true + 0.2 * (rng.random_sample(n_points) - 0.5) + y_true = x_true > 0.5 + y_pred = x_pred > 0.5 + return y_true, y_pred + + arr = np.repeat([0.0, 1.0], n_points) # binary + assert_almost_equal(matthews_corrcoef(arr, arr), 1.0) + arr = np.repeat([0.0, 1.0, 2.0], n_points) # multiclass + assert_almost_equal(matthews_corrcoef(arr, arr), 1.0) + + y_true, y_pred = random_ys(n_points) + assert_almost_equal(matthews_corrcoef(y_true, y_true), 1.0) + assert_almost_equal(matthews_corrcoef(y_true, y_pred), mcc_safe(y_true, y_pred)) + + +def test_precision_recall_f1_score_multiclass(): + # Test Precision Recall and F1 Score for multiclass classification task + y_true, y_pred, _ = make_prediction(binary=False) + + # compute scores with default labels introspection + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + assert_array_almost_equal(p, [0.83, 0.33, 0.42], 2) + assert_array_almost_equal(r, [0.79, 0.09, 0.90], 2) + assert_array_almost_equal(f, [0.81, 0.15, 0.57], 2) + assert_array_equal(s, [24, 31, 20]) + + # averaging tests + ps = precision_score(y_true, y_pred, pos_label=1, average="micro") + assert_array_almost_equal(ps, 0.53, 2) + + rs = recall_score(y_true, y_pred, average="micro") + assert_array_almost_equal(rs, 0.53, 2) + + fs = f1_score(y_true, y_pred, average="micro") + assert_array_almost_equal(fs, 0.53, 2) + + ps = precision_score(y_true, y_pred, average="macro") + assert_array_almost_equal(ps, 0.53, 2) + + rs = recall_score(y_true, y_pred, average="macro") + assert_array_almost_equal(rs, 0.60, 2) + + fs = f1_score(y_true, y_pred, average="macro") + assert_array_almost_equal(fs, 0.51, 2) + + ps = precision_score(y_true, y_pred, average="weighted") + assert_array_almost_equal(ps, 0.51, 2) + + rs = recall_score(y_true, y_pred, average="weighted") + assert_array_almost_equal(rs, 0.53, 2) + + fs = f1_score(y_true, y_pred, average="weighted") + assert_array_almost_equal(fs, 0.47, 2) + + with pytest.raises(ValueError): + precision_score(y_true, y_pred, average="samples") + with pytest.raises(ValueError): + recall_score(y_true, y_pred, average="samples") + with pytest.raises(ValueError): + f1_score(y_true, y_pred, average="samples") + with pytest.raises(ValueError): + fbeta_score(y_true, y_pred, average="samples", beta=0.5) + + # same prediction but with and explicit label ordering + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, labels=[0, 2, 1], average=None + ) + assert_array_almost_equal(p, [0.83, 0.41, 0.33], 2) + assert_array_almost_equal(r, [0.79, 0.90, 0.10], 2) + assert_array_almost_equal(f, [0.81, 0.57, 0.15], 2) + assert_array_equal(s, [24, 20, 31]) + + +@pytest.mark.parametrize("average", ["samples", "micro", "macro", "weighted", None]) +def test_precision_refcall_f1_score_multilabel_unordered_labels(average): + # test that labels need not be sorted in the multilabel case + y_true = np.array([[1, 1, 0, 0]]) + y_pred = np.array([[0, 0, 1, 1]]) + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, labels=[3, 0, 1, 2], warn_for=[], average=average + ) + assert_array_equal(p, 0) + assert_array_equal(r, 0) + assert_array_equal(f, 0) + if average is None: + assert_array_equal(s, [0, 1, 1, 0]) + + +def test_precision_recall_f1_score_binary_averaged(): + y_true = np.array([0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1]) + y_pred = np.array([1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1]) + + # compute scores with default labels introspection + ps, rs, fs, _ = precision_recall_fscore_support(y_true, y_pred, average=None) + p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average="macro") + assert p == np.mean(ps) + assert r == np.mean(rs) + assert f == np.mean(fs) + p, r, f, _ = precision_recall_fscore_support(y_true, y_pred, average="weighted") + support = np.bincount(y_true) + assert p == np.average(ps, weights=support) + assert r == np.average(rs, weights=support) + assert f == np.average(fs, weights=support) + + +def test_zero_precision_recall(): + # Check that pathological cases do not bring NaNs + + old_error_settings = np.seterr(all="raise") + + try: + y_true = np.array([0, 1, 2, 0, 1, 2]) + y_pred = np.array([2, 0, 1, 1, 2, 0]) + + assert_almost_equal(precision_score(y_true, y_pred, average="macro"), 0.0, 2) + assert_almost_equal(recall_score(y_true, y_pred, average="macro"), 0.0, 2) + assert_almost_equal(f1_score(y_true, y_pred, average="macro"), 0.0, 2) + + finally: + np.seterr(**old_error_settings) + + +def test_confusion_matrix_multiclass_subset_labels(): + # Test confusion matrix - multi-class case with subset of labels + y_true, y_pred, _ = make_prediction(binary=False) + + # compute confusion matrix with only first two labels considered + cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) + assert_array_equal(cm, [[19, 4], [4, 3]]) + + # compute confusion matrix with explicit label ordering for only subset + # of labels + cm = confusion_matrix(y_true, y_pred, labels=[2, 1]) + assert_array_equal(cm, [[18, 2], [24, 3]]) + + # a label not in y_true should result in zeros for that row/column + extra_label = np.max(y_true) + 1 + cm = confusion_matrix(y_true, y_pred, labels=[2, extra_label]) + assert_array_equal(cm, [[18, 0], [0, 0]]) + + +@pytest.mark.parametrize( + "labels, err_msg", + [ + ([], "'labels' should contains at least one label."), + ([3, 4], "At least one label specified must be in y_true"), + ], + ids=["empty list", "unknown labels"], +) +def test_confusion_matrix_error(labels, err_msg): + y_true, y_pred, _ = make_prediction(binary=False) + with pytest.raises(ValueError, match=err_msg): + confusion_matrix(y_true, y_pred, labels=labels) + + +@pytest.mark.parametrize( + "labels", (None, [0, 1], [0, 1, 2]), ids=["None", "binary", "multiclass"] +) +def test_confusion_matrix_on_zero_length_input(labels): + expected_n_classes = len(labels) if labels else 0 + expected = np.zeros((expected_n_classes, expected_n_classes), dtype=int) + cm = confusion_matrix([], [], labels=labels) + assert_array_equal(cm, expected) + + +def test_confusion_matrix_dtype(): + y = [0, 1, 1] + weight = np.ones(len(y)) + # confusion_matrix returns int64 by default + cm = confusion_matrix(y, y) + assert cm.dtype == np.int64 + # The dtype of confusion_matrix is always 64 bit + for dtype in [np.bool_, np.int32, np.uint64]: + cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False)) + assert cm.dtype == np.int64 + for dtype in [np.float32, np.float64, None, object]: + cm = confusion_matrix(y, y, sample_weight=weight.astype(dtype, copy=False)) + assert cm.dtype == np.float64 + + # np.iinfo(np.uint32).max should be accumulated correctly + weight = np.full(len(y), 4294967295, dtype=np.uint32) + cm = confusion_matrix(y, y, sample_weight=weight) + assert cm[0, 0] == 4294967295 + assert cm[1, 1] == 8589934590 + + # np.iinfo(np.int64).max should cause an overflow + weight = np.full(len(y), 9223372036854775807, dtype=np.int64) + cm = confusion_matrix(y, y, sample_weight=weight) + assert cm[0, 0] == 9223372036854775807 + assert cm[1, 1] == -2 + + +@pytest.mark.parametrize("dtype", ["Int64", "Float64", "boolean"]) +def test_confusion_matrix_pandas_nullable(dtype): + """Checks that confusion_matrix works with pandas nullable dtypes. + + Non-regression test for gh-25635. + """ + pd = pytest.importorskip("pandas") + + y_ndarray = np.array([1, 0, 0, 1, 0, 1, 1, 0, 1]) + y_true = pd.Series(y_ndarray, dtype=dtype) + y_predicted = pd.Series([0, 0, 1, 1, 0, 1, 1, 1, 1], dtype="int64") + + output = confusion_matrix(y_true, y_predicted) + expected_output = confusion_matrix(y_ndarray, y_predicted) + + assert_array_equal(output, expected_output) + + +def test_classification_report_multiclass(): + # Test performance report + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with class names + expected_report = """\ + precision recall f1-score support + + setosa 0.83 0.79 0.81 24 + versicolor 0.33 0.10 0.15 31 + virginica 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 +weighted avg 0.51 0.53 0.47 75 +""" + report = classification_report( + y_true, + y_pred, + labels=np.arange(len(iris.target_names)), + target_names=iris.target_names, + ) + assert report == expected_report + + +def test_classification_report_multiclass_balanced(): + y_true, y_pred = [0, 0, 0, 1, 1, 1, 2, 2, 2], [0, 1, 2, 0, 1, 2, 0, 1, 2] + + expected_report = """\ + precision recall f1-score support + + 0 0.33 0.33 0.33 3 + 1 0.33 0.33 0.33 3 + 2 0.33 0.33 0.33 3 + + accuracy 0.33 9 + macro avg 0.33 0.33 0.33 9 +weighted avg 0.33 0.33 0.33 9 +""" + report = classification_report(y_true, y_pred) + assert report == expected_report + + +def test_classification_report_multiclass_with_label_detection(): + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with label detection + expected_report = """\ + precision recall f1-score support + + 0 0.83 0.79 0.81 24 + 1 0.33 0.10 0.15 31 + 2 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 +weighted avg 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert report == expected_report + + +def test_classification_report_multiclass_with_digits(): + # Test performance report with added digits in floating point values + iris = datasets.load_iris() + y_true, y_pred, _ = make_prediction(dataset=iris, binary=False) + + # print classification report with class names + expected_report = """\ + precision recall f1-score support + + setosa 0.82609 0.79167 0.80851 24 + versicolor 0.33333 0.09677 0.15000 31 + virginica 0.41860 0.90000 0.57143 20 + + accuracy 0.53333 75 + macro avg 0.52601 0.59615 0.50998 75 +weighted avg 0.51375 0.53333 0.47310 75 +""" + report = classification_report( + y_true, + y_pred, + labels=np.arange(len(iris.target_names)), + target_names=iris.target_names, + digits=5, + ) + assert report == expected_report + + +def test_classification_report_multiclass_with_string_label(): + y_true, y_pred, _ = make_prediction(binary=False) + + y_true = np.array(["blue", "green", "red"])[y_true] + y_pred = np.array(["blue", "green", "red"])[y_pred] + + expected_report = """\ + precision recall f1-score support + + blue 0.83 0.79 0.81 24 + green 0.33 0.10 0.15 31 + red 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 +weighted avg 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert report == expected_report + + expected_report = """\ + precision recall f1-score support + + a 0.83 0.79 0.81 24 + b 0.33 0.10 0.15 31 + c 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 +weighted avg 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred, target_names=["a", "b", "c"]) + assert report == expected_report + + +def test_classification_report_multiclass_with_unicode_label(): + y_true, y_pred, _ = make_prediction(binary=False) + + labels = np.array(["blue\xa2", "green\xa2", "red\xa2"]) + y_true = labels[y_true] + y_pred = labels[y_pred] + + expected_report = """\ + precision recall f1-score support + + blue\xa2 0.83 0.79 0.81 24 + green\xa2 0.33 0.10 0.15 31 + red\xa2 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 +weighted avg 0.51 0.53 0.47 75 +""" + report = classification_report(y_true, y_pred) + assert report == expected_report + + +def test_classification_report_multiclass_with_long_string_label(): + y_true, y_pred, _ = make_prediction(binary=False) + + labels = np.array(["blue", "green" * 5, "red"]) + y_true = labels[y_true] + y_pred = labels[y_pred] + + expected_report = """\ + precision recall f1-score support + + blue 0.83 0.79 0.81 24 +greengreengreengreengreen 0.33 0.10 0.15 31 + red 0.42 0.90 0.57 20 + + accuracy 0.53 75 + macro avg 0.53 0.60 0.51 75 + weighted avg 0.51 0.53 0.47 75 +""" + + report = classification_report(y_true, y_pred) + assert report == expected_report + + +def test_classification_report_labels_target_names_unequal_length(): + y_true = [0, 0, 2, 0, 0] + y_pred = [0, 2, 2, 0, 0] + target_names = ["class 0", "class 1", "class 2"] + + msg = "labels size, 2, does not match size of target_names, 3" + with pytest.warns(UserWarning, match=msg): + classification_report(y_true, y_pred, labels=[0, 2], target_names=target_names) + + +def test_classification_report_no_labels_target_names_unequal_length(): + y_true = [0, 0, 2, 0, 0] + y_pred = [0, 2, 2, 0, 0] + target_names = ["class 0", "class 1", "class 2"] + + err_msg = ( + "Number of classes, 2, does not " + "match size of target_names, 3. " + "Try specifying the labels parameter" + ) + with pytest.raises(ValueError, match=err_msg): + classification_report(y_true, y_pred, target_names=target_names) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_multilabel_classification_report(): + n_classes = 4 + n_samples = 50 + + _, y_true = make_multilabel_classification( + n_features=1, n_samples=n_samples, n_classes=n_classes, random_state=0 + ) + + _, y_pred = make_multilabel_classification( + n_features=1, n_samples=n_samples, n_classes=n_classes, random_state=1 + ) + + expected_report = """\ + precision recall f1-score support + + 0 0.50 0.67 0.57 24 + 1 0.51 0.74 0.61 27 + 2 0.29 0.08 0.12 26 + 3 0.52 0.56 0.54 27 + + micro avg 0.50 0.51 0.50 104 + macro avg 0.45 0.51 0.46 104 +weighted avg 0.45 0.51 0.46 104 + samples avg 0.46 0.42 0.40 104 +""" + + report = classification_report(y_true, y_pred) + assert report == expected_report + + +def test_multilabel_zero_one_loss_subset(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + assert zero_one_loss(y1, y2) == 0.5 + assert zero_one_loss(y1, y1) == 0 + assert zero_one_loss(y2, y2) == 0 + assert zero_one_loss(y2, np.logical_not(y2)) == 1 + assert zero_one_loss(y1, np.logical_not(y1)) == 1 + assert zero_one_loss(y1, np.zeros(y1.shape)) == 1 + assert zero_one_loss(y2, np.zeros(y1.shape)) == 1 + + +def test_multilabel_hamming_loss(): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + w = np.array([1, 3]) + + assert hamming_loss(y1, y2) == 1 / 6 + assert hamming_loss(y1, y1) == 0 + assert hamming_loss(y2, y2) == 0 + assert hamming_loss(y2, 1 - y2) == 1 + assert hamming_loss(y1, 1 - y1) == 1 + assert hamming_loss(y1, np.zeros(y1.shape)) == 4 / 6 + assert hamming_loss(y2, np.zeros(y1.shape)) == 0.5 + assert hamming_loss(y1, y2, sample_weight=w) == 1.0 / 12 + assert hamming_loss(y1, 1 - y2, sample_weight=w) == 11.0 / 12 + assert hamming_loss(y1, np.zeros_like(y1), sample_weight=w) == 2.0 / 3 + # sp_hamming only works with 1-D arrays + assert hamming_loss(y1[0], y2[0]) == sp_hamming(y1[0], y2[0]) + + +def test_jaccard_score_validation(): + y_true = np.array([0, 1, 0, 1, 1]) + y_pred = np.array([0, 1, 0, 1, 1]) + err_msg = r"pos_label=2 is not a valid label. It should be one of \[0, 1\]" + with pytest.raises(ValueError, match=err_msg): + jaccard_score(y_true, y_pred, average="binary", pos_label=2) + + y_true = np.array([[0, 1, 1], [1, 0, 0]]) + y_pred = np.array([[1, 1, 1], [1, 0, 1]]) + msg1 = ( + r"Target is multilabel-indicator but average='binary'. " + r"Please choose another average setting, one of \[None, " + r"'micro', 'macro', 'weighted', 'samples'\]." + ) + with pytest.raises(ValueError, match=msg1): + jaccard_score(y_true, y_pred, average="binary", pos_label=-1) + + y_true = np.array([0, 1, 1, 0, 2]) + y_pred = np.array([1, 1, 1, 1, 0]) + msg2 = ( + r"Target is multiclass but average='binary'. Please choose " + r"another average setting, one of \[None, 'micro', 'macro', " + r"'weighted'\]." + ) + with pytest.raises(ValueError, match=msg2): + jaccard_score(y_true, y_pred, average="binary") + msg3 = "Samplewise metrics are not available outside of multilabel classification." + with pytest.raises(ValueError, match=msg3): + jaccard_score(y_true, y_pred, average="samples") + + msg = ( + r"Note that pos_label \(set to 3\) is ignored when " + r"average != 'binary' \(got 'micro'\). You may use " + r"labels=\[pos_label\] to specify a single positive " + "class." + ) + with pytest.warns(UserWarning, match=msg): + jaccard_score(y_true, y_pred, average="micro", pos_label=3) + + +def test_multilabel_jaccard_score(recwarn): + # Dense label indicator matrix format + y1 = np.array([[0, 1, 1], [1, 0, 1]]) + y2 = np.array([[0, 0, 1], [1, 0, 1]]) + + # size(y1 \inter y2) = [1, 2] + # size(y1 \union y2) = [2, 2] + + assert jaccard_score(y1, y2, average="samples") == 0.75 + assert jaccard_score(y1, y1, average="samples") == 1 + assert jaccard_score(y2, y2, average="samples") == 1 + assert jaccard_score(y2, np.logical_not(y2), average="samples") == 0 + assert jaccard_score(y1, np.logical_not(y1), average="samples") == 0 + assert jaccard_score(y1, np.zeros(y1.shape), average="samples") == 0 + assert jaccard_score(y2, np.zeros(y1.shape), average="samples") == 0 + + y_true = np.array([[0, 1, 1], [1, 0, 0]]) + y_pred = np.array([[1, 1, 1], [1, 0, 1]]) + # average='macro' + assert_almost_equal(jaccard_score(y_true, y_pred, average="macro"), 2.0 / 3) + # average='micro' + assert_almost_equal(jaccard_score(y_true, y_pred, average="micro"), 3.0 / 5) + # average='samples' + assert_almost_equal(jaccard_score(y_true, y_pred, average="samples"), 7.0 / 12) + assert_almost_equal( + jaccard_score(y_true, y_pred, average="samples", labels=[0, 2]), 1.0 / 2 + ) + assert_almost_equal( + jaccard_score(y_true, y_pred, average="samples", labels=[1, 2]), 1.0 / 2 + ) + # average=None + assert_array_equal( + jaccard_score(y_true, y_pred, average=None), np.array([1.0 / 2, 1.0, 1.0 / 2]) + ) + + y_true = np.array([[0, 1, 1], [1, 0, 1]]) + y_pred = np.array([[1, 1, 1], [1, 0, 1]]) + assert_almost_equal(jaccard_score(y_true, y_pred, average="macro"), 5.0 / 6) + # average='weighted' + assert_almost_equal(jaccard_score(y_true, y_pred, average="weighted"), 7.0 / 8) + + msg2 = "Got 4 > 2" + with pytest.raises(ValueError, match=msg2): + jaccard_score(y_true, y_pred, labels=[4], average="macro") + msg3 = "Got -1 < 0" + with pytest.raises(ValueError, match=msg3): + jaccard_score(y_true, y_pred, labels=[-1], average="macro") + + msg = ( + "Jaccard is ill-defined and being set to 0.0 in labels " + "with no true or predicted samples." + ) + + with pytest.warns(UndefinedMetricWarning, match=msg): + assert ( + jaccard_score(np.array([[0, 1]]), np.array([[0, 1]]), average="macro") + == 0.5 + ) + + msg = ( + "Jaccard is ill-defined and being set to 0.0 in samples " + "with no true or predicted labels." + ) + + with pytest.warns(UndefinedMetricWarning, match=msg): + assert ( + jaccard_score( + np.array([[0, 0], [1, 1]]), + np.array([[0, 0], [1, 1]]), + average="samples", + ) + == 0.5 + ) + + assert not list(recwarn) + + +def test_multiclass_jaccard_score(recwarn): + y_true = ["ant", "ant", "cat", "cat", "ant", "cat", "bird", "bird"] + y_pred = ["cat", "ant", "cat", "cat", "ant", "bird", "bird", "cat"] + labels = ["ant", "bird", "cat"] + lb = LabelBinarizer() + lb.fit(labels) + y_true_bin = lb.transform(y_true) + y_pred_bin = lb.transform(y_pred) + multi_jaccard_score = partial(jaccard_score, y_true, y_pred) + bin_jaccard_score = partial(jaccard_score, y_true_bin, y_pred_bin) + multi_labels_list = [ + ["ant", "bird"], + ["ant", "cat"], + ["cat", "bird"], + ["ant"], + ["bird"], + ["cat"], + None, + ] + bin_labels_list = [[0, 1], [0, 2], [2, 1], [0], [1], [2], None] + + # other than average='samples'/'none-samples', test everything else here + for average in ("macro", "weighted", "micro", None): + for m_label, b_label in zip(multi_labels_list, bin_labels_list): + assert_almost_equal( + multi_jaccard_score(average=average, labels=m_label), + bin_jaccard_score(average=average, labels=b_label), + ) + + y_true = np.array([[0, 0], [0, 0], [0, 0]]) + y_pred = np.array([[0, 0], [0, 0], [0, 0]]) + with ignore_warnings(): + assert jaccard_score(y_true, y_pred, average="weighted") == 0 + + assert not list(recwarn) + + +def test_average_binary_jaccard_score(recwarn): + # tp=0, fp=0, fn=1, tn=0 + assert jaccard_score([1], [0], average="binary") == 0.0 + # tp=0, fp=0, fn=0, tn=1 + msg = ( + "Jaccard is ill-defined and being set to 0.0 due to " + "no true or predicted samples" + ) + with pytest.warns(UndefinedMetricWarning, match=msg): + assert jaccard_score([0, 0], [0, 0], average="binary") == 0.0 + + # tp=1, fp=0, fn=0, tn=0 (pos_label=0) + assert jaccard_score([0], [0], pos_label=0, average="binary") == 1.0 + y_true = np.array([1, 0, 1, 1, 0]) + y_pred = np.array([1, 0, 1, 1, 1]) + assert_almost_equal(jaccard_score(y_true, y_pred, average="binary"), 3.0 / 4) + assert_almost_equal( + jaccard_score(y_true, y_pred, average="binary", pos_label=0), 1.0 / 2 + ) + + assert not list(recwarn) + + +def test_jaccard_score_zero_division_warning(): + # check that we raised a warning with default behavior if a zero division + # happens + y_true = np.array([[1, 0, 1], [0, 0, 0]]) + y_pred = np.array([[0, 0, 0], [0, 0, 0]]) + msg = ( + "Jaccard is ill-defined and being set to 0.0 in " + "samples with no true or predicted labels." + " Use `zero_division` parameter to control this behavior." + ) + with pytest.warns(UndefinedMetricWarning, match=msg): + score = jaccard_score(y_true, y_pred, average="samples", zero_division="warn") + assert score == pytest.approx(0.0) + + +@pytest.mark.parametrize("zero_division, expected_score", [(0, 0), (1, 0.5)]) +def test_jaccard_score_zero_division_set_value(zero_division, expected_score): + # check that we don't issue warning by passing the zero_division parameter + y_true = np.array([[1, 0, 1], [0, 0, 0]]) + y_pred = np.array([[0, 0, 0], [0, 0, 0]]) + with warnings.catch_warnings(): + warnings.simplefilter("error", UndefinedMetricWarning) + score = jaccard_score( + y_true, y_pred, average="samples", zero_division=zero_division + ) + assert score == pytest.approx(expected_score) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_precision_recall_f1_score_multilabel_1(): + # Test precision_recall_f1_score on a crafted multilabel example + # First crafted example + + y_true = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 1]]) + y_pred = np.array([[0, 1, 0, 0], [0, 1, 0, 0], [1, 0, 1, 0]]) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + + # tp = [0, 1, 1, 0] + # fn = [1, 0, 0, 1] + # fp = [1, 1, 0, 0] + # Check per class + + assert_array_almost_equal(p, [0.0, 0.5, 1.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 1.0, 1.0, 0.0], 2) + assert_array_almost_equal(f, [0.0, 1 / 1.5, 1, 0.0], 2) + assert_array_almost_equal(s, [1, 1, 1, 1], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None) + support = s + assert_array_almost_equal(f2, [0, 0.83, 1, 0], 2) + + # Check macro + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") + assert_almost_equal(p, 1.5 / 4) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2.5 / 1.5 * 0.25) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2) + ) + + # Check micro + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") + assert_almost_equal(p, 0.5) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 0.5) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="micro"), + (1 + 4) * p * r / (4 * p + r), + ) + + # Check weighted + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") + assert_almost_equal(p, 1.5 / 4) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2.5 / 1.5 * 0.25) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="weighted"), + np.average(f2, weights=support), + ) + # Check samples + # |h(x_i) inter y_i | = [0, 1, 1] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [1, 1, 2] + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") + assert_almost_equal(p, 0.5) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 0.5) + assert s is None + assert_almost_equal(fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.5) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_precision_recall_f1_score_multilabel_2(): + # Test precision_recall_f1_score on a crafted multilabel example 2 + # Second crafted example + y_true = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 1, 0]]) + y_pred = np.array([[0, 0, 0, 1], [0, 0, 0, 1], [1, 1, 0, 0]]) + + # tp = [ 0. 1. 0. 0.] + # fp = [ 1. 0. 0. 2.] + # fn = [ 1. 1. 1. 0.] + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) + assert_array_almost_equal(p, [0.0, 1.0, 0.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 0.5, 0.0, 0.0], 2) + assert_array_almost_equal(f, [0.0, 0.66, 0.0, 0.0], 2) + assert_array_almost_equal(s, [1, 2, 1, 0], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None) + support = s + assert_array_almost_equal(f2, [0, 0.55, 0, 0], 2) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="micro") + assert_almost_equal(p, 0.25) + assert_almost_equal(r, 0.25) + assert_almost_equal(f, 2 * 0.25 * 0.25 / 0.5) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="micro"), + (1 + 4) * p * r / (4 * p + r), + ) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="macro") + assert_almost_equal(p, 0.25) + assert_almost_equal(r, 0.125) + assert_almost_equal(f, 2 / 12) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="macro"), np.mean(f2) + ) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="weighted") + assert_almost_equal(p, 2 / 4) + assert_almost_equal(r, 1 / 4) + assert_almost_equal(f, 2 / 3 * 2 / 4) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="weighted"), + np.average(f2, weights=support), + ) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") + # Check samples + # |h(x_i) inter y_i | = [0, 0, 1] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [1, 1, 2] + + assert_almost_equal(p, 1 / 6) + assert_almost_equal(r, 1 / 6) + assert_almost_equal(f, 2 / 4 * 1 / 3) + assert s is None + assert_almost_equal( + fbeta_score(y_true, y_pred, beta=2, average="samples"), 0.1666, 2 + ) + + +@pytest.mark.filterwarnings(r"ignore::sklearn.exceptions.UndefinedMetricWarning") +@pytest.mark.parametrize( + "zero_division, zero_division_expected", + [("warn", 0), (0, 0), (1, 1), (np.nan, np.nan)], +) +def test_precision_recall_f1_score_with_an_empty_prediction( + zero_division, zero_division_expected +): + y_true = np.array([[0, 1, 0, 0], [1, 0, 0, 0], [0, 1, 1, 0]]) + y_pred = np.array([[0, 0, 0, 0], [0, 0, 0, 1], [0, 1, 1, 0]]) + + # true_pos = [ 0. 1. 1. 0.] + # false_pos = [ 0. 0. 0. 1.] + # false_neg = [ 1. 1. 0. 0.] + + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, average=None, zero_division=zero_division + ) + + assert_array_almost_equal(p, [zero_division_expected, 1.0, 1.0, 0.0], 2) + assert_array_almost_equal(r, [0.0, 0.5, 1.0, zero_division_expected], 2) + expected_f = 0 + assert_array_almost_equal(f, [expected_f, 1 / 1.5, 1, expected_f], 2) + assert_array_almost_equal(s, [1, 2, 1, 0], 2) + + f2 = fbeta_score(y_true, y_pred, beta=2, average=None, zero_division=zero_division) + support = s + assert_array_almost_equal(f2, [expected_f, 0.55, 1, expected_f], 2) + + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, average="macro", zero_division=zero_division + ) + + value_to_sum = 0 if np.isnan(zero_division_expected) else zero_division_expected + values_to_average = 3 + (not np.isnan(zero_division_expected)) + + assert_almost_equal(p, (2 + value_to_sum) / values_to_average) + assert_almost_equal(r, (1.5 + value_to_sum) / values_to_average) + expected_f = (2 / 3 + 1) / 4 + assert_almost_equal(f, expected_f) + assert s is None + assert_almost_equal( + fbeta_score( + y_true, + y_pred, + beta=2, + average="macro", + zero_division=zero_division, + ), + _nanaverage(f2, weights=None), + ) + + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, average="micro", zero_division=zero_division + ) + assert_almost_equal(p, 2 / 3) + assert_almost_equal(r, 0.5) + assert_almost_equal(f, 2 / 3 / (2 / 3 + 0.5)) + assert s is None + assert_almost_equal( + fbeta_score( + y_true, y_pred, beta=2, average="micro", zero_division=zero_division + ), + (1 + 4) * p * r / (4 * p + r), + ) + + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, average="weighted", zero_division=zero_division + ) + assert_almost_equal(p, 3 / 4 if zero_division_expected == 0 else 1.0) + assert_almost_equal(r, 0.5) + values_to_average = 4 + assert_almost_equal(f, (2 * 2 / 3 + 1) / values_to_average) + assert s is None + assert_almost_equal( + fbeta_score( + y_true, y_pred, beta=2, average="weighted", zero_division=zero_division + ), + _nanaverage(f2, weights=support), + ) + + p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average="samples") + # |h(x_i) inter y_i | = [0, 0, 2] + # |y_i| = [1, 1, 2] + # |h(x_i)| = [0, 1, 2] + assert_almost_equal(p, 1 / 3) + assert_almost_equal(r, 1 / 3) + assert_almost_equal(f, 1 / 3) + assert s is None + expected_result = 0.333 + assert_almost_equal( + fbeta_score( + y_true, y_pred, beta=2, average="samples", zero_division=zero_division + ), + expected_result, + 2, + ) + + +@pytest.mark.parametrize("beta", [1]) +@pytest.mark.parametrize("average", ["macro", "micro", "weighted", "samples"]) +@pytest.mark.parametrize("zero_division", [0, 1, np.nan]) +def test_precision_recall_f1_no_labels(beta, average, zero_division): + y_true = np.zeros((20, 3)) + y_pred = np.zeros_like(y_true) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + + p, r, f, s = precision_recall_fscore_support( + y_true, + y_pred, + average=average, + beta=beta, + zero_division=zero_division, + ) + fbeta = fbeta_score( + y_true, + y_pred, + beta=beta, + average=average, + zero_division=zero_division, + ) + assert s is None + + # if zero_division = nan, check that all metrics are nan and exit + if np.isnan(zero_division): + for metric in [p, r, f, fbeta]: + assert np.isnan(metric) + return + + zero_division = float(zero_division) + assert_almost_equal(p, zero_division) + assert_almost_equal(r, zero_division) + assert_almost_equal(f, zero_division) + + assert_almost_equal(fbeta, float(zero_division)) + + +@pytest.mark.parametrize("average", ["macro", "micro", "weighted", "samples"]) +def test_precision_recall_f1_no_labels_check_warnings(average): + y_true = np.zeros((20, 3)) + y_pred = np.zeros_like(y_true) + + func = precision_recall_fscore_support + with pytest.warns(UndefinedMetricWarning): + p, r, f, s = func(y_true, y_pred, average=average, beta=1.0) + + assert_almost_equal(p, 0) + assert_almost_equal(r, 0) + assert_almost_equal(f, 0) + assert s is None + + with pytest.warns(UndefinedMetricWarning): + fbeta = fbeta_score(y_true, y_pred, average=average, beta=1.0) + + assert_almost_equal(fbeta, 0) + + +@pytest.mark.parametrize("zero_division", [0, 1, np.nan]) +def test_precision_recall_f1_no_labels_average_none(zero_division): + y_true = np.zeros((20, 3)) + y_pred = np.zeros_like(y_true) + + # tp = [0, 0, 0] + # fn = [0, 0, 0] + # fp = [0, 0, 0] + # support = [0, 0, 0] + # |y_hat_i inter y_i | = [0, 0, 0] + # |y_i| = [0, 0, 0] + # |y_hat_i| = [0, 0, 0] + + with warnings.catch_warnings(): + warnings.simplefilter("error") + + p, r, f, s = precision_recall_fscore_support( + y_true, + y_pred, + average=None, + beta=1.0, + zero_division=zero_division, + ) + fbeta = fbeta_score( + y_true, y_pred, beta=1.0, average=None, zero_division=zero_division + ) + + zero_division = np.float64(zero_division) + assert_array_almost_equal(p, [zero_division, zero_division, zero_division], 2) + assert_array_almost_equal(r, [zero_division, zero_division, zero_division], 2) + assert_array_almost_equal(f, [zero_division, zero_division, zero_division], 2) + assert_array_almost_equal(s, [0, 0, 0], 2) + + assert_array_almost_equal(fbeta, [zero_division, zero_division, zero_division], 2) + + +def test_precision_recall_f1_no_labels_average_none_warn(): + y_true = np.zeros((20, 3)) + y_pred = np.zeros_like(y_true) + + # tp = [0, 0, 0] + # fn = [0, 0, 0] + # fp = [0, 0, 0] + # support = [0, 0, 0] + # |y_hat_i inter y_i | = [0, 0, 0] + # |y_i| = [0, 0, 0] + # |y_hat_i| = [0, 0, 0] + + with pytest.warns(UndefinedMetricWarning): + p, r, f, s = precision_recall_fscore_support( + y_true, y_pred, average=None, beta=1 + ) + + assert_array_almost_equal(p, [0, 0, 0], 2) + assert_array_almost_equal(r, [0, 0, 0], 2) + assert_array_almost_equal(f, [0, 0, 0], 2) + assert_array_almost_equal(s, [0, 0, 0], 2) + + with pytest.warns(UndefinedMetricWarning): + fbeta = fbeta_score(y_true, y_pred, beta=1, average=None) + + assert_array_almost_equal(fbeta, [0, 0, 0], 2) + + +def test_prf_warnings(): + # average of per-label scores + f, w = precision_recall_fscore_support, UndefinedMetricWarning + for average in [None, "weighted", "macro"]: + msg = ( + "Precision is ill-defined and " + "being set to 0.0 in labels with no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f([0, 1, 2], [1, 1, 2], average=average) + + msg = ( + "Recall is ill-defined and " + "being set to 0.0 in labels with no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f([1, 1, 2], [0, 1, 2], average=average) + + # average of per-sample scores + msg = ( + "Precision is ill-defined and " + "being set to 0.0 in samples with no predicted labels." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f(np.array([[1, 0], [1, 0]]), np.array([[1, 0], [0, 0]]), average="samples") + + msg = ( + "Recall is ill-defined and " + "being set to 0.0 in samples with no true labels." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f(np.array([[1, 0], [0, 0]]), np.array([[1, 0], [1, 0]]), average="samples") + + # single score: micro-average + msg = ( + "Precision is ill-defined and " + "being set to 0.0 due to no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f(np.array([[1, 1], [1, 1]]), np.array([[0, 0], [0, 0]]), average="micro") + + msg = ( + "Recall is ill-defined and " + "being set to 0.0 due to no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f(np.array([[0, 0], [0, 0]]), np.array([[1, 1], [1, 1]]), average="micro") + + # single positive label + msg = ( + "Precision is ill-defined and " + "being set to 0.0 due to no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f([1, 1], [-1, -1], average="binary") + + msg = ( + "Recall is ill-defined and " + "being set to 0.0 due to no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + with pytest.warns(w, match=msg): + f([-1, -1], [1, 1], average="binary") + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + precision_recall_fscore_support([0, 0], [0, 0], average="binary") + msg = ( + "F-score is ill-defined and being set to 0.0 due to no true nor " + "predicted samples. Use `zero_division` parameter to control this" + " behavior." + ) + assert str(record.pop().message) == msg + msg = ( + "Recall is ill-defined and " + "being set to 0.0 due to no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + assert str(record.pop().message) == msg + msg = ( + "Precision is ill-defined and " + "being set to 0.0 due to no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + assert str(record.pop().message) == msg + + +@pytest.mark.parametrize("zero_division", [0, 1, np.nan]) +def test_prf_no_warnings_if_zero_division_set(zero_division): + with warnings.catch_warnings(): + warnings.simplefilter("error") + + # average of per-label scores + for average in [None, "weighted", "macro"]: + precision_recall_fscore_support( + [0, 1, 2], [1, 1, 2], average=average, zero_division=zero_division + ) + + precision_recall_fscore_support( + [1, 1, 2], [0, 1, 2], average=average, zero_division=zero_division + ) + + # average of per-sample scores + precision_recall_fscore_support( + np.array([[1, 0], [1, 0]]), + np.array([[1, 0], [0, 0]]), + average="samples", + zero_division=zero_division, + ) + + precision_recall_fscore_support( + np.array([[1, 0], [0, 0]]), + np.array([[1, 0], [1, 0]]), + average="samples", + zero_division=zero_division, + ) + + # single score: micro-average + precision_recall_fscore_support( + np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average="micro", + zero_division=zero_division, + ) + + precision_recall_fscore_support( + np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average="micro", + zero_division=zero_division, + ) + + # single positive label + precision_recall_fscore_support( + [1, 1], [-1, -1], average="binary", zero_division=zero_division + ) + + precision_recall_fscore_support( + [-1, -1], [1, 1], average="binary", zero_division=zero_division + ) + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + precision_recall_fscore_support( + [0, 0], [0, 0], average="binary", zero_division=zero_division + ) + assert len(record) == 0 + + +@pytest.mark.parametrize("zero_division", ["warn", 0, 1, np.nan]) +def test_recall_warnings(zero_division): + with warnings.catch_warnings(): + warnings.simplefilter("error") + + recall_score( + np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average="micro", + zero_division=zero_division, + ) + + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + recall_score( + np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average="micro", + zero_division=zero_division, + ) + if zero_division == "warn": + assert ( + str(record.pop().message) == "Recall is ill-defined and " + "being set to 0.0 due to no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + else: + assert len(record) == 0 + + recall_score([0, 0], [0, 0]) + if zero_division == "warn": + assert ( + str(record.pop().message) == "Recall is ill-defined and " + "being set to 0.0 due to no true samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + + +@pytest.mark.parametrize("zero_division", ["warn", 0, 1, np.nan]) +def test_precision_warnings(zero_division): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + precision_score( + np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average="micro", + zero_division=zero_division, + ) + if zero_division == "warn": + assert ( + str(record.pop().message) == "Precision is ill-defined and " + "being set to 0.0 due to no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + else: + assert len(record) == 0 + + precision_score([0, 0], [0, 0]) + if zero_division == "warn": + assert ( + str(record.pop().message) == "Precision is ill-defined and " + "being set to 0.0 due to no predicted samples." + " Use `zero_division` parameter to control" + " this behavior." + ) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + + precision_score( + np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average="micro", + zero_division=zero_division, + ) + + +@pytest.mark.parametrize("zero_division", ["warn", 0, 1, np.nan]) +def test_fscore_warnings(zero_division): + with warnings.catch_warnings(record=True) as record: + warnings.simplefilter("always") + + for score in [f1_score, partial(fbeta_score, beta=2)]: + score( + np.array([[1, 1], [1, 1]]), + np.array([[0, 0], [0, 0]]), + average="micro", + zero_division=zero_division, + ) + assert len(record) == 0 + + score( + np.array([[0, 0], [0, 0]]), + np.array([[1, 1], [1, 1]]), + average="micro", + zero_division=zero_division, + ) + assert len(record) == 0 + + score( + np.array([[0, 0], [0, 0]]), + np.array([[0, 0], [0, 0]]), + average="micro", + zero_division=zero_division, + ) + if zero_division == "warn": + assert ( + str(record.pop().message) == "F-score is ill-defined and " + "being set to 0.0 due to no true nor predicted " + "samples. Use `zero_division` parameter to " + "control this behavior." + ) + else: + assert len(record) == 0 + + +def test_prf_average_binary_data_non_binary(): + # Error if user does not explicitly set non-binary average mode + y_true_mc = [1, 2, 3, 3] + y_pred_mc = [1, 2, 3, 1] + msg_mc = ( + r"Target is multiclass but average='binary'. Please " + r"choose another average setting, one of \[" + r"None, 'micro', 'macro', 'weighted'\]." + ) + y_true_ind = np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]]) + y_pred_ind = np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]) + msg_ind = ( + r"Target is multilabel-indicator but average='binary'. Please " + r"choose another average setting, one of \[" + r"None, 'micro', 'macro', 'weighted', 'samples'\]." + ) + + for y_true, y_pred, msg in [ + (y_true_mc, y_pred_mc, msg_mc), + (y_true_ind, y_pred_ind, msg_ind), + ]: + for metric in [ + precision_score, + recall_score, + f1_score, + partial(fbeta_score, beta=2), + ]: + with pytest.raises(ValueError, match=msg): + metric(y_true, y_pred) + + +def test__check_targets(): + # Check that _check_targets correctly merges target types, squeezes + # output and fails if input lengths differ. + IND = "multilabel-indicator" + MC = "multiclass" + BIN = "binary" + CNT = "continuous" + MMC = "multiclass-multioutput" + MCN = "continuous-multioutput" + # all of length 3 + EXAMPLES = [ + (IND, np.array([[0, 1, 1], [1, 0, 0], [0, 0, 1]])), + # must not be considered binary + (IND, np.array([[0, 1], [1, 0], [1, 1]])), + (MC, [2, 3, 1]), + (BIN, [0, 1, 1]), + (CNT, [0.0, 1.5, 1.0]), + (MC, np.array([[2], [3], [1]])), + (BIN, np.array([[0], [1], [1]])), + (CNT, np.array([[0.0], [1.5], [1.0]])), + (MMC, np.array([[0, 2], [1, 3], [2, 3]])), + (MCN, np.array([[0.5, 2.0], [1.1, 3.0], [2.0, 3.0]])), + ] + # expected type given input types, or None for error + # (types will be tried in either order) + EXPECTED = { + (IND, IND): IND, + (MC, MC): MC, + (BIN, BIN): BIN, + (MC, IND): None, + (BIN, IND): None, + (BIN, MC): MC, + # Disallowed types + (CNT, CNT): None, + (MMC, MMC): None, + (MCN, MCN): None, + (IND, CNT): None, + (MC, CNT): None, + (BIN, CNT): None, + (MMC, CNT): None, + (MCN, CNT): None, + (IND, MMC): None, + (MC, MMC): None, + (BIN, MMC): None, + (MCN, MMC): None, + (IND, MCN): None, + (MC, MCN): None, + (BIN, MCN): None, + } + + for (type1, y1), (type2, y2) in product(EXAMPLES, repeat=2): + try: + expected = EXPECTED[type1, type2] + except KeyError: + expected = EXPECTED[type2, type1] + if expected is None: + with pytest.raises(ValueError): + _check_targets(y1, y2) + + if type1 != type2: + err_msg = ( + "Classification metrics can't handle a mix " + "of {0} and {1} targets".format(type1, type2) + ) + with pytest.raises(ValueError, match=err_msg): + _check_targets(y1, y2) + + else: + if type1 not in (BIN, MC, IND): + err_msg = "{0} is not supported".format(type1) + with pytest.raises(ValueError, match=err_msg): + _check_targets(y1, y2) + + else: + merged_type, y1out, y2out = _check_targets(y1, y2) + assert merged_type == expected + if merged_type.startswith("multilabel"): + assert y1out.format == "csr" + assert y2out.format == "csr" + else: + assert_array_equal(y1out, np.squeeze(y1)) + assert_array_equal(y2out, np.squeeze(y2)) + with pytest.raises(ValueError): + _check_targets(y1[:-1], y2) + + # Make sure seq of seq is not supported + y1 = [(1, 2), (0, 2, 3)] + y2 = [(2,), (0, 2)] + msg = ( + "You appear to be using a legacy multi-label data representation. " + "Sequence of sequences are no longer supported; use a binary array" + " or sparse matrix instead - the MultiLabelBinarizer" + " transformer can convert to this format." + ) + with pytest.raises(ValueError, match=msg): + _check_targets(y1, y2) + + +def test__check_targets_multiclass_with_both_y_true_and_y_pred_binary(): + # https://github.com/scikit-learn/scikit-learn/issues/8098 + y_true = [0, 1] + y_pred = [0, -1] + assert _check_targets(y_true, y_pred)[0] == "multiclass" + + +def test_hinge_loss_binary(): + y_true = np.array([-1, 1, 1, -1]) + pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) + assert hinge_loss(y_true, pred_decision) == 1.2 / 4 + + y_true = np.array([0, 2, 2, 0]) + pred_decision = np.array([-8.5, 0.5, 1.5, -0.3]) + assert hinge_loss(y_true, pred_decision) == 1.2 / 4 + + +def test_hinge_loss_multiclass(): + pred_decision = np.array( + [ + [+0.36, -0.17, -0.58, -0.99], + [-0.54, -0.37, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.54, -0.38, -0.48, -0.58], + [-2.36, -0.79, -0.27, +0.24], + [-1.45, -0.58, -0.38, -0.17], + ] + ) + y_true = np.array([0, 1, 2, 1, 3, 2]) + dummy_losses = np.array( + [ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][3] + pred_decision[4][2], + 1 - pred_decision[5][2] + pred_decision[5][3], + ] + ) + np.clip(dummy_losses, 0, None, out=dummy_losses) + dummy_hinge_loss = np.mean(dummy_losses) + assert hinge_loss(y_true, pred_decision) == dummy_hinge_loss + + +def test_hinge_loss_multiclass_missing_labels_with_labels_none(): + y_true = np.array([0, 1, 2, 2]) + pred_decision = np.array( + [ + [+1.27, 0.034, -0.68, -1.40], + [-1.45, -0.58, -0.38, -0.17], + [-2.36, -0.79, -0.27, +0.24], + [-2.36, -0.79, -0.27, +0.24], + ] + ) + error_message = ( + "Please include all labels in y_true or pass labels as third argument" + ) + with pytest.raises(ValueError, match=error_message): + 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], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + ] + ) + y_true = np.array([0, 1, 2, 1, 2]) + labels = np.array([0, 1, 2, 3]) + dummy_losses = np.array( + [ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][2] + pred_decision[4][3], + ] + ) + np.clip(dummy_losses, 0, None, out=dummy_losses) + dummy_hinge_loss = np.mean(dummy_losses) + assert hinge_loss(y_true, pred_decision, labels=labels) == dummy_hinge_loss + + +def test_hinge_loss_multiclass_missing_labels_only_two_unq_in_y_true(): + # non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/17630 + # check that we can compute the hinge loss when providing an array + # with labels allowing to not have all labels in y_true + pred_decision = np.array( + [ + [+0.36, -0.17, -0.58], + [-0.15, -0.58, -0.48], + [-1.45, -0.58, -0.38], + [-0.55, -0.78, -0.42], + [-1.45, -0.58, -0.38], + ] + ) + y_true = np.array([0, 2, 2, 0, 2]) + labels = np.array([0, 1, 2]) + dummy_losses = np.array( + [ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][2] + pred_decision[1][0], + 1 - pred_decision[2][2] + pred_decision[2][1], + 1 - pred_decision[3][0] + pred_decision[3][2], + 1 - pred_decision[4][2] + pred_decision[4][1], + ] + ) + np.clip(dummy_losses, 0, None, out=dummy_losses) + dummy_hinge_loss = np.mean(dummy_losses) + assert_almost_equal( + hinge_loss(y_true, pred_decision, labels=labels), dummy_hinge_loss + ) + + +def test_hinge_loss_multiclass_invariance_lists(): + # Currently, invariance of string and integer labels cannot be tested + # in common invariance tests because invariance tests for multiclass + # decision functions is not implemented yet. + y_true = ["blue", "green", "red", "green", "white", "red"] + pred_decision = [ + [+0.36, -0.17, -0.58, -0.99], + [-0.55, -0.38, -0.48, -0.58], + [-1.45, -0.58, -0.38, -0.17], + [-0.55, -0.38, -0.48, -0.58], + [-2.36, -0.79, -0.27, +0.24], + [-1.45, -0.58, -0.38, -0.17], + ] + dummy_losses = np.array( + [ + 1 - pred_decision[0][0] + pred_decision[0][1], + 1 - pred_decision[1][1] + pred_decision[1][2], + 1 - pred_decision[2][2] + pred_decision[2][3], + 1 - pred_decision[3][1] + pred_decision[3][2], + 1 - pred_decision[4][3] + pred_decision[4][2], + 1 - pred_decision[5][2] + pred_decision[5][3], + ] + ) + np.clip(dummy_losses, 0, None, out=dummy_losses) + dummy_hinge_loss = np.mean(dummy_losses) + assert hinge_loss(y_true, pred_decision) == dummy_hinge_loss + + +def test_log_loss(): + # binary case with symbolic labels ("no" < "yes") + y_true = ["no", "no", "no", "yes", "yes", "yes"] + y_pred = np.array( + [[0.5, 0.5], [0.1, 0.9], [0.01, 0.99], [0.9, 0.1], [0.75, 0.25], [0.001, 0.999]] + ) + loss = log_loss(y_true, y_pred) + loss_true = -np.mean(bernoulli.logpmf(np.array(y_true) == "yes", y_pred[:, 1])) + assert_allclose(loss, loss_true) + + # multiclass case; adapted from http://bit.ly/RJJHWA + y_true = [1, 0, 2] + y_pred = [[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]] + loss = log_loss(y_true, y_pred, normalize=True) + assert_allclose(loss, 0.6904911) + + # check that we got all the shapes and axes right + # by doubling the length of y_true and y_pred + y_true *= 2 + y_pred *= 2 + loss = log_loss(y_true, y_pred, normalize=False) + assert_allclose(loss, 0.6904911 * 6) + + # raise error if number of classes are not equal. + y_true = [1, 0, 2] + y_pred = [[0.3, 0.7], [0.6, 0.4], [0.4, 0.6]] + with pytest.raises(ValueError): + log_loss(y_true, y_pred) + + # raise error if labels do not contain all values of y_true + y_true = ["a", "b", "c"] + y_pred = [[0.9, 0.1, 0.0], [0.1, 0.9, 0.0], [0.1, 0.1, 0.8]] + labels = ["a", "c", "d"] + error_str = ( + "y_true contains values {'b'} not belonging to the passed " + "labels ['a', 'c', 'd']." + ) + with pytest.raises(ValueError, match=re.escape(error_str)): + log_loss(y_true, y_pred, labels=labels) + + # case when y_true is a string array object + y_true = ["ham", "spam", "spam", "ham"] + y_pred = [[0.3, 0.7], [0.6, 0.4], [0.4, 0.6], [0.7, 0.3]] + loss = log_loss(y_true, y_pred) + assert_allclose(loss, 0.7469410) + + # test labels option + + y_true = [2, 2] + y_pred = [[0.2, 0.8], [0.6, 0.4]] + y_score = np.array([[0.1, 0.9], [0.1, 0.9]]) + error_str = ( + "y_true contains only one label (2). Please provide the list of all " + "expected class labels explicitly through the labels argument." + ) + with pytest.raises(ValueError, match=re.escape(error_str)): + log_loss(y_true, y_pred) + + y_pred = [[0.2, 0.8], [0.6, 0.4], [0.7, 0.3]] + error_str = "Found input variables with inconsistent numbers of samples: [3, 2]" + with pytest.raises(ValueError, match=re.escape(error_str)): + log_loss(y_true, y_pred) + + # works when the labels argument is used + + true_log_loss = -np.mean(np.log(y_score[:, 1])) + calculated_log_loss = log_loss(y_true, y_score, labels=[1, 2]) + assert_allclose(calculated_log_loss, true_log_loss) + + # ensure labels work when len(np.unique(y_true)) != y_pred.shape[1] + y_true = [1, 2, 2] + y_score2 = [[0.7, 0.1, 0.2], [0.2, 0.7, 0.1], [0.1, 0.7, 0.2]] + loss = log_loss(y_true, y_score2, labels=[1, 2, 3]) + assert_allclose(loss, -np.log(0.7)) + + +@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.float16]) +def test_log_loss_eps(dtype): + """Check the behaviour internal eps that changes depending on the input dtype. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/24315 + """ + y_true = np.array([0, 1], dtype=dtype) + y_pred = np.array([1, 0], dtype=dtype) + + loss = log_loss(y_true, y_pred) + assert np.isfinite(loss) + + +@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.float16]) +def test_log_loss_not_probabilities_warning(dtype): + """Check that log_loss raises a warning when y_pred values don't sum to 1.""" + y_true = np.array([0, 1, 1, 0]) + y_pred = np.array([[0.2, 0.7], [0.6, 0.3], [0.4, 0.7], [0.8, 0.3]], dtype=dtype) + + with pytest.warns(UserWarning, match="The y_prob values do not sum to one."): + log_loss(y_true, y_pred) + + +@pytest.mark.parametrize( + "y_true, y_pred", + [ + ([0, 1, 0], [0, 1, 0]), + ([0, 1, 0], [[1, 0], [0, 1], [1, 0]]), + ([0, 1, 2], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]), + ], +) +def test_log_loss_perfect_predictions(y_true, y_pred): + """Check that log_loss returns 0 for perfect predictions.""" + # Because of the clipping, the result is not exactly 0 + assert log_loss(y_true, y_pred) == pytest.approx(0) + + +def test_log_loss_pandas_input(): + # case when input is a pandas series and dataframe gh-5715 + y_tr = np.array(["ham", "spam", "spam", "ham"]) + y_pr = np.array([[0.3, 0.7], [0.6, 0.4], [0.4, 0.6], [0.7, 0.3]]) + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import DataFrame, Series + + types.append((Series, DataFrame)) + except ImportError: + pass + for TrueInputType, PredInputType in types: + # y_pred dataframe, y_true series + y_true, y_pred = TrueInputType(y_tr), PredInputType(y_pr) + loss = log_loss(y_true, y_pred) + assert_allclose(loss, 0.7469410) + + +def test_log_loss_warnings(): + expected_message = re.escape( + "Labels passed were ['spam', 'eggs', 'ham']. But this function " + "assumes labels are ordered lexicographically. " + "Pass the ordered labels=['eggs', 'ham', 'spam'] and ensure that " + "the columns of y_prob correspond to this ordering." + ) + with pytest.warns(UserWarning, match=expected_message): + log_loss( + ["eggs", "spam", "ham"], + [[1, 0, 0], [0, 1, 0], [0, 0, 1]], + labels=["spam", "eggs", "ham"], + ) + + +def test_brier_score_loss_binary(): + # Check brier_score_loss function + y_true = np.array([0, 1, 1, 0, 1, 1]) + y_prob = np.array([0.1, 0.8, 0.9, 0.3, 1.0, 0.95]) + true_score = linalg.norm(y_true - y_prob) ** 2 / len(y_true) + + assert_almost_equal(brier_score_loss(y_true, y_true), 0.0) + assert_almost_equal(brier_score_loss(y_true, y_prob), true_score) + assert_almost_equal(brier_score_loss(1.0 + y_true, y_prob), true_score) + assert_almost_equal(brier_score_loss(2 * y_true - 1, y_prob), true_score) + + # check that using (n_samples, 2) y_prob or y_true gives the same score + y_prob_reshaped = np.column_stack((1 - y_prob, y_prob)) + y_true_reshaped = np.column_stack((1 - y_true, y_true)) + assert_almost_equal(brier_score_loss(y_true, y_prob_reshaped), true_score) + assert_almost_equal(brier_score_loss(y_true_reshaped, y_prob_reshaped), true_score) + + # check scale_by_half argument + assert_almost_equal( + brier_score_loss(y_true, y_prob, scale_by_half="auto"), true_score + ) + assert_almost_equal( + brier_score_loss(y_true, y_prob, scale_by_half=True), true_score + ) + assert_almost_equal( + brier_score_loss(y_true, y_prob, scale_by_half=False), 2 * true_score + ) + + # calculate correctly when there's only one class in y_true + assert_almost_equal(brier_score_loss([-1], [0.4]), 0.4**2) + assert_almost_equal(brier_score_loss([0], [0.4]), 0.4**2) + assert_almost_equal(brier_score_loss([1], [0.4]), (1 - 0.4) ** 2) + assert_almost_equal(brier_score_loss(["foo"], [0.4], pos_label="bar"), 0.4**2) + assert_almost_equal( + brier_score_loss(["foo"], [0.4], pos_label="foo"), + (1 - 0.4) ** 2, + ) + + +def test_brier_score_loss_multiclass(): + # test cases for multi-class + assert_almost_equal( + brier_score_loss( + ["eggs", "spam", "ham"], + [[1, 0, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0]], + labels=["eggs", "ham", "spam", "yams"], + ), + 2 / 3, + ) + + assert_almost_equal( + brier_score_loss( + [1, 0, 2], [[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]] + ), + 0.41333333, + ) + + # check perfect predictions for 3 classes + assert_almost_equal( + brier_score_loss( + [0, 1, 2], [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + ), + 0, + ) + + # check perfectly incorrect predictions for 3 classes + assert_almost_equal( + brier_score_loss( + [0, 1, 2], [[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.0, 0.0]] + ), + 2, + ) + + +def test_brier_score_loss_invalid_inputs(): + # binary case + y_true = np.array([0, 1, 1, 0, 1, 1]) + y_prob = np.array([0.1, 0.8, 0.9, 0.3, 1.0, 0.95]) + with pytest.raises(ValueError): + # bad length of y_prob + brier_score_loss(y_true, y_prob[1:]) + with pytest.raises(ValueError): + # y_pred has value greater than 1 + brier_score_loss(y_true, y_prob + 1.0) + with pytest.raises(ValueError): + # y_pred has value less than 0 + brier_score_loss(y_true, y_prob - 1.0) + + # multiclass case + y_true = np.array([1, 0, 2]) + y_prob = np.array([[0.2, 0.7, 0.1], [0.6, 0.2, 0.2], [0.6, 0.1, 0.3]]) + with pytest.raises(ValueError): + # bad length of y_pred + brier_score_loss(y_true, y_prob[1:]) + with pytest.raises(ValueError): + # y_pred has value greater than 1 + brier_score_loss(y_true, y_prob + 1.0) + with pytest.raises(ValueError): + # y_pred has value less than 0 + brier_score_loss(y_true, y_prob - 1.0) + + # raise an error for multiclass y_true and binary y_prob + y_true = np.array([0, 1, 2, 0]) + y_prob = np.array([0.8, 0.6, 0.4, 0.2]) + error_message = re.escape( + "The type of the target inferred from y_true is multiclass " + "but should be binary according to the shape of y_prob." + ) + with pytest.raises(ValueError, match=error_message): + brier_score_loss(y_true, y_prob) + + # raise an error for wrong number of classes + y_true = [0, 1, 2] + y_prob = [[1, 0], [0, 1], [0, 1]] + error_message = ( + "y_true and y_prob contain different number of " + "classes: 3 vs 2. Please provide the true " + "labels explicitly through the labels argument. " + "Classes found in " + "y_true: [0 1 2]" + ) + with pytest.raises(ValueError, match=re.escape(error_message)): + brier_score_loss(y_true, y_prob) + + y_true = ["eggs", "spam", "ham"] + y_prob = [[1, 0, 0], [0, 1, 0], [0, 1, 0]] + labels = ["eggs", "spam", "ham", "yams"] + error_message = ( + "The number of classes in labels is different " + "from that in y_prob. Classes found in " + "labels: ['eggs' 'ham' 'spam' 'yams']" + ) + with pytest.raises(ValueError, match=re.escape(error_message)): + brier_score_loss(y_true, y_prob, labels=labels) + + # raise error message when there's only one class in y_true + y_true = ["eggs"] + y_prob = [[0.9, 0.1]] + error_message = ( + "y_true contains only one label (eggs). Please " + "provide the list of all expected class labels explicitly through the " + "labels argument." + ) + with pytest.raises(ValueError, match=re.escape(error_message)): + brier_score_loss(y_true, y_prob) + + # error is fixed when labels is specified + assert_almost_equal(brier_score_loss(y_true, y_prob, labels=["eggs", "ham"]), 0.01) + + +def test_brier_score_loss_warnings(): + expected_message = re.escape( + "Labels passed were ['spam', 'eggs', 'ham']. But this function " + "assumes labels are ordered lexicographically. " + "Pass the ordered labels=['eggs', 'ham', 'spam'] and ensure that " + "the columns of y_prob correspond to this ordering." + ) + with pytest.warns(UserWarning, match=expected_message): + brier_score_loss( + ["eggs", "spam", "ham"], + [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + ], + labels=["spam", "eggs", "ham"], + ) + + +def test_balanced_accuracy_score_unseen(): + msg = "y_pred contains classes not in y_true" + with pytest.warns(UserWarning, match=msg): + balanced_accuracy_score([0, 0, 0], [0, 0, 1]) + + +@pytest.mark.parametrize( + "y_true,y_pred", + [ + (["a", "b", "a", "b"], ["a", "a", "a", "b"]), + (["a", "b", "c", "b"], ["a", "a", "a", "b"]), + (["a", "a", "a", "b"], ["a", "b", "c", "b"]), + ], +) +def test_balanced_accuracy_score(y_true, y_pred): + macro_recall = recall_score( + y_true, y_pred, average="macro", labels=np.unique(y_true) + ) + with ignore_warnings(): + # Warnings are tested in test_balanced_accuracy_score_unseen + balanced = balanced_accuracy_score(y_true, y_pred) + assert balanced == pytest.approx(macro_recall) + adjusted = balanced_accuracy_score(y_true, y_pred, adjusted=True) + chance = balanced_accuracy_score(y_true, np.full_like(y_true, y_true[0])) + assert adjusted == (balanced - chance) / (1 - chance) + + +@pytest.mark.parametrize( + "metric", + [ + jaccard_score, + f1_score, + partial(fbeta_score, beta=0.5), + precision_recall_fscore_support, + precision_score, + recall_score, + brier_score_loss, + ], +) +@pytest.mark.parametrize( + "classes", [(False, True), (0, 1), (0.0, 1.0), ("zero", "one")] +) +def test_classification_metric_pos_label_types(metric, classes): + """Check that the metric works with different types of `pos_label`. + + We can expect `pos_label` to be a bool, an integer, a float, a string. + No error should be raised for those types. + """ + rng = np.random.RandomState(42) + n_samples, pos_label = 10, classes[-1] + y_true = rng.choice(classes, size=n_samples, replace=True) + if metric is brier_score_loss: + # brier score loss requires probabilities + y_pred = rng.uniform(size=n_samples) + else: + y_pred = y_true.copy() + result = metric(y_true, y_pred, pos_label=pos_label) + assert not np.any(np.isnan(result)) + + +@pytest.mark.parametrize( + "y_true, y_pred, expected_score", + [ + (np.array([0, 1]), np.array([1, 0]), 0.0), + (np.array([0, 1]), np.array([0, 1]), 1.0), + (np.array([0, 1]), np.array([0, 0]), 0.0), + (np.array([0, 0]), np.array([0, 0]), 1.0), + ], +) +def test_f1_for_small_binary_inputs_with_zero_division(y_true, y_pred, expected_score): + """Check the behaviour of `zero_division` for f1-score. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/26965 + """ + assert f1_score(y_true, y_pred, zero_division=1.0) == pytest.approx(expected_score) + + +@pytest.mark.parametrize( + "scoring", + [ + make_scorer(f1_score, zero_division=np.nan), + make_scorer(fbeta_score, beta=2, zero_division=np.nan), + make_scorer(precision_score, zero_division=np.nan), + make_scorer(recall_score, zero_division=np.nan), + ], +) +def test_classification_metric_division_by_zero_nan_validaton(scoring): + """Check that we validate `np.nan` properly for classification metrics. + + With `n_jobs=2` in cross-validation, the `np.nan` used for the singleton will be + different in the sub-process and we should not use the `is` operator but + `math.isnan`. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/27563 + """ + X, y = datasets.make_classification(random_state=0) + classifier = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X, y) + cross_val_score(classifier, X, y, scoring=scoring, n_jobs=2, error_score="raise") + + +def test_d2_log_loss_score(): + y_true = [0, 0, 0, 1, 1, 1] + y_true_string = ["no", "no", "no", "yes", "yes", "yes"] + y_pred = np.array( + [ + [0.5, 0.5], + [0.9, 0.1], + [0.4, 0.6], + [0.6, 0.4], + [0.35, 0.65], + [0.01, 0.99], + ] + ) + y_pred_null = np.array( + [ + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + ] + ) + d2_score = d2_log_loss_score(y_true=y_true, y_pred=y_pred) + log_likelihood = log_loss(y_true=y_true, y_pred=y_pred, normalize=False) + log_likelihood_null = log_loss(y_true=y_true, y_pred=y_pred_null, normalize=False) + d2_score_true = 1 - log_likelihood / log_likelihood_null + assert d2_score == pytest.approx(d2_score_true) + + # check that using sample weight also gives the correct d2 score + sample_weight = np.array([2, 1, 3, 4, 3, 1]) + y_pred_null[:, 0] = sample_weight[:3].sum() / sample_weight.sum() + y_pred_null[:, 1] = sample_weight[3:].sum() / sample_weight.sum() + d2_score = d2_log_loss_score( + y_true=y_true, y_pred=y_pred, sample_weight=sample_weight + ) + log_likelihood = log_loss( + y_true=y_true, + y_pred=y_pred, + sample_weight=sample_weight, + normalize=False, + ) + log_likelihood_null = log_loss( + y_true=y_true, + y_pred=y_pred_null, + sample_weight=sample_weight, + normalize=False, + ) + d2_score_true = 1 - log_likelihood / log_likelihood_null + assert d2_score == pytest.approx(d2_score_true) + + # check if good predictions give a relatively higher value for the d2 score + y_pred = np.array( + [ + [0.9, 0.1], + [0.8, 0.2], + [0.9, 0.1], + [0.1, 0.9], + [0.2, 0.8], + [0.1, 0.9], + ] + ) + d2_score = d2_log_loss_score(y_true, y_pred) + assert 0.5 < d2_score < 1.0 + # check that a similar value is obtained for string labels + d2_score_string = d2_log_loss_score(y_true_string, y_pred) + assert d2_score_string == pytest.approx(d2_score) + + # check if poor predictions gives a relatively low value for the d2 score + y_pred = np.array( + [ + [0.5, 0.5], + [0.1, 0.9], + [0.1, 0.9], + [0.9, 0.1], + [0.75, 0.25], + [0.1, 0.9], + ] + ) + d2_score = d2_log_loss_score(y_true, y_pred) + assert d2_score < 0 + # check that a similar value is obtained for string labels + d2_score_string = d2_log_loss_score(y_true_string, y_pred) + assert d2_score_string == pytest.approx(d2_score) + + # check if simply using the average of the classes as the predictions + # gives a d2 score of 0 + y_true = [0, 0, 0, 1, 1, 1] + y_pred = np.array( + [ + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + [0.5, 0.5], + ] + ) + d2_score = d2_log_loss_score(y_true, y_pred) + assert d2_score == 0 + d2_score_string = d2_log_loss_score(y_true_string, y_pred) + assert d2_score_string == 0 + + # check if simply using the average of the classes as the predictions + # gives a d2 score of 0 when the positive class has a higher proportion + y_true = [0, 1, 1, 1] + y_true_string = ["no", "yes", "yes", "yes"] + y_pred = np.array([[0.25, 0.75], [0.25, 0.75], [0.25, 0.75], [0.25, 0.75]]) + d2_score = d2_log_loss_score(y_true, y_pred) + assert d2_score == 0 + d2_score_string = d2_log_loss_score(y_true_string, y_pred) + assert d2_score_string == 0 + sample_weight = [2, 2, 2, 2] + d2_score_with_sample_weight = d2_log_loss_score( + y_true, y_pred, sample_weight=sample_weight + ) + assert d2_score_with_sample_weight == 0 + + # check that the d2 scores seem correct when more than 2 + # labels are specified + y_true = ["high", "high", "low", "neutral"] + sample_weight = [1.4, 0.6, 0.8, 0.2] + + y_pred = np.array( + [ + [0.8, 0.1, 0.1], + [0.8, 0.1, 0.1], + [0.1, 0.8, 0.1], + [0.1, 0.1, 0.8], + ] + ) + d2_score = d2_log_loss_score(y_true, y_pred) + assert 0.5 < d2_score < 1.0 + d2_score = d2_log_loss_score(y_true, y_pred, sample_weight=sample_weight) + assert 0.5 < d2_score < 1.0 + + y_pred = np.array( + [ + [0.2, 0.5, 0.3], + [0.1, 0.7, 0.2], + [0.1, 0.1, 0.8], + [0.2, 0.7, 0.1], + ] + ) + d2_score = d2_log_loss_score(y_true, y_pred) + assert d2_score < 0 + d2_score = d2_log_loss_score(y_true, y_pred, sample_weight=sample_weight) + assert d2_score < 0 + + +def test_d2_log_loss_score_missing_labels(): + """Check that d2_log_loss_score works when not all labels are present in y_true + + non-regression test for https://github.com/scikit-learn/scikit-learn/issues/30713 + """ + y_true = [2, 0, 2, 0] + labels = [0, 1, 2] + sample_weight = [1.4, 0.6, 0.7, 0.3] + y_pred = np.tile([1, 0, 0], (4, 1)) + + log_loss_obs = log_loss(y_true, y_pred, sample_weight=sample_weight, labels=labels) + + # Null model consists of weighted average of the classes. + # Given that the sum of the weights is 3, + # - weighted average of 0s is (0.6 + 0.3) / 3 = 0.3 + # - weighted average of 1s is 0 + # - weighted average of 2s is (1.4 + 0.7) / 3 = 0.7 + y_pred_null = np.tile([0.3, 0, 0.7], (4, 1)) + log_loss_null = log_loss( + y_true, y_pred_null, sample_weight=sample_weight, labels=labels + ) + + expected_d2_score = 1 - log_loss_obs / log_loss_null + d2_score = d2_log_loss_score( + y_true, y_pred, sample_weight=sample_weight, labels=labels + ) + assert_allclose(d2_score, expected_d2_score) + + +def test_d2_log_loss_score_label_order(): + """Check that d2_log_loss_score doesn't depend on the order of the labels.""" + y_true = [2, 0, 2, 0] + y_pred = np.tile([1, 0, 0], (4, 1)) + + d2_score = d2_log_loss_score(y_true, y_pred, labels=[0, 1, 2]) + d2_score_other = d2_log_loss_score(y_true, y_pred, labels=[0, 2, 1]) + + assert_allclose(d2_score, d2_score_other) + + +def test_d2_log_loss_score_raises(): + """Test that d2_log_loss_score raises the appropriate errors on + invalid inputs.""" + y_true = [0, 1, 2] + y_pred = [[0.2, 0.8], [0.5, 0.5], [0.4, 0.6]] + err = "contain different number of classes" + with pytest.raises(ValueError, match=err): + d2_log_loss_score(y_true, y_pred) + + # check error if the number of classes in labels do not match the number + # of classes in y_pred. + y_true = [0, 1, 2] + y_pred = [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] + labels = [0, 1, 2] + err = "number of classes in labels is different" + with pytest.raises(ValueError, match=err): + d2_log_loss_score(y_true, y_pred, labels=labels) + + # check error if y_true and y_pred do not have equal lengths + y_true = [0, 1, 2] + y_pred = [[0.5, 0.5, 0.5], [0.6, 0.3, 0.1]] + err = "inconsistent numbers of samples" + with pytest.raises(ValueError, match=err): + d2_log_loss_score(y_true, y_pred) + + # check warning for samples < 2 + y_true = [1] + y_pred = [[0.5, 0.5]] + err = "score is not well-defined" + with pytest.warns(UndefinedMetricWarning, match=err): + d2_log_loss_score(y_true, y_pred) + + # check error when y_true only has 1 label + y_true = [1, 1, 1] + y_pred = [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] + err = "y_true contains only one label" + with pytest.raises(ValueError, match=err): + d2_log_loss_score(y_true, y_pred) + + # check error when y_true only has 1 label and labels also has + # only 1 label + y_true = [1, 1, 1] + labels = [1] + y_pred = [[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]] + err = "The labels array needs to contain at least two" + with pytest.raises(ValueError, match=err): + d2_log_loss_score(y_true, y_pred, labels=labels) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py new file mode 100644 index 0000000000000000000000000000000000000000..39522876e8f24589174fa6ce2f6890ad552e5899 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_common.py @@ -0,0 +1,2348 @@ +import math +from functools import partial +from inspect import signature +from itertools import chain, permutations, product + +import numpy as np +import pytest + +from sklearn._config import config_context +from sklearn.datasets import make_multilabel_classification +from sklearn.exceptions import UndefinedMetricWarning +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + cohen_kappa_score, + confusion_matrix, + coverage_error, + d2_absolute_error_score, + d2_pinball_score, + d2_tweedie_score, + dcg_score, + det_curve, + explained_variance_score, + f1_score, + fbeta_score, + hamming_loss, + hinge_loss, + jaccard_score, + label_ranking_average_precision_score, + label_ranking_loss, + log_loss, + matthews_corrcoef, + max_error, + mean_absolute_error, + mean_absolute_percentage_error, + mean_gamma_deviance, + mean_pinball_loss, + mean_poisson_deviance, + mean_squared_error, + mean_squared_log_error, + mean_tweedie_deviance, + median_absolute_error, + multilabel_confusion_matrix, + ndcg_score, + precision_recall_curve, + precision_score, + r2_score, + recall_score, + roc_auc_score, + roc_curve, + root_mean_squared_error, + root_mean_squared_log_error, + top_k_accuracy_score, + zero_one_loss, +) +from sklearn.metrics._base import _average_binary_score +from sklearn.metrics.pairwise import ( + additive_chi2_kernel, + chi2_kernel, + cosine_distances, + cosine_similarity, + euclidean_distances, + linear_kernel, + paired_cosine_distances, + paired_euclidean_distances, + polynomial_kernel, + rbf_kernel, + sigmoid_kernel, +) +from sklearn.preprocessing import LabelBinarizer +from sklearn.utils import shuffle +from sklearn.utils._array_api import ( + _atol_for_type, + _convert_to_numpy, + _get_namespace_device_dtype_ids, + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._testing import ( + _array_api_for_tests, + assert_allclose, + assert_almost_equal, + assert_array_equal, + assert_array_less, + ignore_warnings, +) +from sklearn.utils.fixes import COO_CONTAINERS, parse_version, sp_version +from sklearn.utils.multiclass import type_of_target +from sklearn.utils.validation import _num_samples, check_random_state + +# Note toward developers about metric testing +# ------------------------------------------- +# It is often possible to write one general test for several metrics: +# +# - invariance properties, e.g. invariance to sample order +# - common behavior for an argument, e.g. the "normalize" with value True +# will return the mean of the metrics and with value False will return +# the sum of the metrics. +# +# In order to improve the overall metric testing, it is a good idea to write +# first a specific test for the given metric and then add a general test for +# all metrics that have the same behavior. +# +# Two types of datastructures are used in order to implement this system: +# dictionaries of metrics and lists of metrics with common properties. +# +# Dictionaries of metrics +# ------------------------ +# The goal of having those dictionaries is to have an easy way to call a +# particular metric and associate a name to each function: +# +# - REGRESSION_METRICS: all regression metrics. +# - CLASSIFICATION_METRICS: all classification metrics +# which compare a ground truth and the estimated targets as returned by a +# classifier. +# - THRESHOLDED_METRICS: all classification metrics which +# compare a ground truth and a score, e.g. estimated probabilities or +# decision function (format might vary) +# +# Those dictionaries will be used to test systematically some invariance +# properties, e.g. invariance toward several input layout. +# + +REGRESSION_METRICS = { + "max_error": max_error, + "mean_absolute_error": mean_absolute_error, + "mean_squared_error": mean_squared_error, + "mean_squared_log_error": mean_squared_log_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, + "r2_score": partial(r2_score, multioutput="variance_weighted"), + "root_mean_squared_error": root_mean_squared_error, + "root_mean_squared_log_error": root_mean_squared_log_error, + "mean_normal_deviance": partial(mean_tweedie_deviance, power=0), + "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), + "d2_pinball_score": d2_pinball_score, + "d2_absolute_error_score": d2_absolute_error_score, +} + +CLASSIFICATION_METRICS = { + "accuracy_score": accuracy_score, + "balanced_accuracy_score": balanced_accuracy_score, + "adjusted_balanced_accuracy_score": partial(balanced_accuracy_score, adjusted=True), + "unnormalized_accuracy_score": partial(accuracy_score, normalize=False), + # `confusion_matrix` returns absolute values and hence behaves unnormalized + # . Naming it with an unnormalized_ prefix is necessary for this module to + # skip sample_weight scaling checks which will fail for unnormalized + # metrics. + "unnormalized_confusion_matrix": confusion_matrix, + "normalized_confusion_matrix": lambda *args, **kwargs: ( + confusion_matrix(*args, **kwargs).astype("float") + / confusion_matrix(*args, **kwargs).sum(axis=1)[:, np.newaxis] + ), + "unnormalized_multilabel_confusion_matrix": multilabel_confusion_matrix, + "unnormalized_multilabel_confusion_matrix_sample": partial( + multilabel_confusion_matrix, samplewise=True + ), + "hamming_loss": hamming_loss, + "zero_one_loss": zero_one_loss, + "unnormalized_zero_one_loss": partial(zero_one_loss, normalize=False), + # These are needed to test averaging + "jaccard_score": jaccard_score, + "precision_score": precision_score, + "recall_score": recall_score, + "f1_score": f1_score, + "f2_score": partial(fbeta_score, beta=2), + "f0.5_score": partial(fbeta_score, beta=0.5), + "matthews_corrcoef_score": matthews_corrcoef, + "weighted_f0.5_score": partial(fbeta_score, average="weighted", beta=0.5), + "weighted_f1_score": partial(f1_score, average="weighted"), + "weighted_f2_score": partial(fbeta_score, average="weighted", beta=2), + "weighted_precision_score": partial(precision_score, average="weighted"), + "weighted_recall_score": partial(recall_score, average="weighted"), + "weighted_jaccard_score": partial(jaccard_score, average="weighted"), + "micro_f0.5_score": partial(fbeta_score, average="micro", beta=0.5), + "micro_f1_score": partial(f1_score, average="micro"), + "micro_f2_score": partial(fbeta_score, average="micro", beta=2), + "micro_precision_score": partial(precision_score, average="micro"), + "micro_recall_score": partial(recall_score, average="micro"), + "micro_jaccard_score": partial(jaccard_score, average="micro"), + "macro_f0.5_score": partial(fbeta_score, average="macro", beta=0.5), + "macro_f1_score": partial(f1_score, average="macro"), + "macro_f2_score": partial(fbeta_score, average="macro", beta=2), + "macro_precision_score": partial(precision_score, average="macro"), + "macro_recall_score": partial(recall_score, average="macro"), + "macro_jaccard_score": partial(jaccard_score, average="macro"), + "samples_f0.5_score": partial(fbeta_score, average="samples", beta=0.5), + "samples_f1_score": partial(f1_score, average="samples"), + "samples_f2_score": partial(fbeta_score, average="samples", beta=2), + "samples_precision_score": partial(precision_score, average="samples"), + "samples_recall_score": partial(recall_score, average="samples"), + "samples_jaccard_score": partial(jaccard_score, average="samples"), + "cohen_kappa_score": cohen_kappa_score, +} + + +def precision_recall_curve_padded_thresholds(*args, **kwargs): + """ + The dimensions of precision-recall pairs and the threshold array as + returned by the precision_recall_curve do not match. See + func:`sklearn.metrics.precision_recall_curve` + + This prevents implicit conversion of return value triple to an higher + dimensional np.array of dtype('float64') (it will be of dtype('object) + instead). This again is needed for assert_array_equal to work correctly. + + As a workaround we pad the threshold array with NaN values to match + the dimension of precision and recall arrays respectively. + """ + precision, recall, thresholds = precision_recall_curve(*args, **kwargs) + + pad_threshholds = len(precision) - len(thresholds) + + return np.array( + [ + precision, + recall, + np.pad( + thresholds.astype(np.float64), + pad_width=(0, pad_threshholds), + mode="constant", + constant_values=[np.nan], + ), + ] + ) + + +CURVE_METRICS = { + "roc_curve": roc_curve, + "precision_recall_curve": precision_recall_curve_padded_thresholds, + "det_curve": det_curve, +} + +THRESHOLDED_METRICS = { + "coverage_error": coverage_error, + "label_ranking_loss": label_ranking_loss, + "log_loss": log_loss, + "unnormalized_log_loss": partial(log_loss, normalize=False), + "hinge_loss": hinge_loss, + "brier_score_loss": brier_score_loss, + "roc_auc_score": roc_auc_score, # default: average="macro" + "weighted_roc_auc": partial(roc_auc_score, average="weighted"), + "samples_roc_auc": partial(roc_auc_score, average="samples"), + "micro_roc_auc": partial(roc_auc_score, average="micro"), + "ovr_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovr"), + "weighted_ovr_roc_auc": partial( + roc_auc_score, average="weighted", multi_class="ovr" + ), + "ovo_roc_auc": partial(roc_auc_score, average="macro", multi_class="ovo"), + "weighted_ovo_roc_auc": partial( + roc_auc_score, average="weighted", multi_class="ovo" + ), + "partial_roc_auc": partial(roc_auc_score, max_fpr=0.5), + "average_precision_score": average_precision_score, # default: average="macro" + "weighted_average_precision_score": partial( + average_precision_score, average="weighted" + ), + "samples_average_precision_score": partial( + average_precision_score, average="samples" + ), + "micro_average_precision_score": partial(average_precision_score, average="micro"), + "label_ranking_average_precision_score": label_ranking_average_precision_score, + "ndcg_score": ndcg_score, + "dcg_score": dcg_score, + "top_k_accuracy_score": top_k_accuracy_score, +} + +ALL_METRICS = dict() +ALL_METRICS.update(THRESHOLDED_METRICS) +ALL_METRICS.update(CLASSIFICATION_METRICS) +ALL_METRICS.update(REGRESSION_METRICS) +ALL_METRICS.update(CURVE_METRICS) + +# Lists of metrics with common properties +# --------------------------------------- +# Lists of metrics with common properties are used to test systematically some +# functionalities and invariance, e.g. SYMMETRIC_METRICS lists all metrics that +# are symmetric with respect to their input argument y_true and y_pred. +# +# When you add a new metric or functionality, check if a general test +# is already written. + +# Those metrics don't support binary inputs +METRIC_UNDEFINED_BINARY = { + "samples_f0.5_score", + "samples_f1_score", + "samples_f2_score", + "samples_precision_score", + "samples_recall_score", + "samples_jaccard_score", + "coverage_error", + "unnormalized_multilabel_confusion_matrix_sample", + "label_ranking_loss", + "label_ranking_average_precision_score", + "dcg_score", + "ndcg_score", +} + +# Those metrics don't support multiclass inputs +METRIC_UNDEFINED_MULTICLASS = { + "micro_roc_auc", + "samples_roc_auc", + "partial_roc_auc", + "roc_auc_score", + "weighted_roc_auc", + "jaccard_score", + # with default average='binary', multiclass is prohibited + "precision_score", + "recall_score", + "f1_score", + "f2_score", + "f0.5_score", + # curves + "roc_curve", + "precision_recall_curve", + "det_curve", +} + +# Metric undefined with "binary" or "multiclass" input +METRIC_UNDEFINED_BINARY_MULTICLASS = METRIC_UNDEFINED_BINARY.union( + METRIC_UNDEFINED_MULTICLASS +) + +# Metrics with an "average" argument +METRICS_WITH_AVERAGING = { + "precision_score", + "recall_score", + "f1_score", + "f2_score", + "f0.5_score", + "jaccard_score", +} + +# Threshold-based metrics with an "average" argument +THRESHOLDED_METRICS_WITH_AVERAGING = { + "roc_auc_score", + "average_precision_score", + "partial_roc_auc", +} + +# Metrics with a "pos_label" argument +METRICS_WITH_POS_LABEL = { + "roc_curve", + "precision_recall_curve", + "det_curve", + "brier_score_loss", + "precision_score", + "recall_score", + "f1_score", + "f2_score", + "f0.5_score", + "jaccard_score", + "average_precision_score", + "weighted_average_precision_score", + "micro_average_precision_score", + "samples_average_precision_score", +} + +# Metrics with a "labels" argument +# TODO: Handle multi_class metrics that has a labels argument as well as a +# decision function argument. e.g hinge_loss +METRICS_WITH_LABELS = { + "unnormalized_confusion_matrix", + "normalized_confusion_matrix", + "roc_curve", + "precision_recall_curve", + "det_curve", + "precision_score", + "recall_score", + "f1_score", + "f2_score", + "f0.5_score", + "jaccard_score", + "weighted_f0.5_score", + "weighted_f1_score", + "weighted_f2_score", + "weighted_precision_score", + "weighted_recall_score", + "weighted_jaccard_score", + "micro_f0.5_score", + "micro_f1_score", + "micro_f2_score", + "micro_precision_score", + "micro_recall_score", + "micro_jaccard_score", + "macro_f0.5_score", + "macro_f1_score", + "macro_f2_score", + "macro_precision_score", + "macro_recall_score", + "macro_jaccard_score", + "unnormalized_multilabel_confusion_matrix", + "unnormalized_multilabel_confusion_matrix_sample", + "cohen_kappa_score", + "log_loss", + "brier_score_loss", +} + +# Metrics with a "normalize" option +METRICS_WITH_NORMALIZE_OPTION = { + "accuracy_score", + "top_k_accuracy_score", + "zero_one_loss", +} + +# Threshold-based metrics with "multilabel-indicator" format support +THRESHOLDED_MULTILABEL_METRICS = { + "log_loss", + "unnormalized_log_loss", + "brier_score_loss", + "roc_auc_score", + "weighted_roc_auc", + "samples_roc_auc", + "micro_roc_auc", + "partial_roc_auc", + "average_precision_score", + "weighted_average_precision_score", + "samples_average_precision_score", + "micro_average_precision_score", + "coverage_error", + "label_ranking_loss", + "ndcg_score", + "dcg_score", + "label_ranking_average_precision_score", +} + +# Classification metrics with "multilabel-indicator" format +MULTILABELS_METRICS = { + "accuracy_score", + "unnormalized_accuracy_score", + "hamming_loss", + "zero_one_loss", + "unnormalized_zero_one_loss", + "weighted_f0.5_score", + "weighted_f1_score", + "weighted_f2_score", + "weighted_precision_score", + "weighted_recall_score", + "weighted_jaccard_score", + "macro_f0.5_score", + "macro_f1_score", + "macro_f2_score", + "macro_precision_score", + "macro_recall_score", + "macro_jaccard_score", + "micro_f0.5_score", + "micro_f1_score", + "micro_f2_score", + "micro_precision_score", + "micro_recall_score", + "micro_jaccard_score", + "unnormalized_multilabel_confusion_matrix", + "samples_f0.5_score", + "samples_f1_score", + "samples_f2_score", + "samples_precision_score", + "samples_recall_score", + "samples_jaccard_score", +} + +# Regression metrics with "multioutput-continuous" format support +MULTIOUTPUT_METRICS = { + "mean_absolute_error", + "median_absolute_error", + "mean_squared_error", + "mean_squared_log_error", + "r2_score", + "root_mean_squared_error", + "root_mean_squared_log_error", + "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 +# metric(y_true, y_pred) == metric(y_pred, y_true). +SYMMETRIC_METRICS = { + "accuracy_score", + "unnormalized_accuracy_score", + "hamming_loss", + "zero_one_loss", + "unnormalized_zero_one_loss", + "micro_jaccard_score", + "macro_jaccard_score", + "jaccard_score", + "samples_jaccard_score", + "f1_score", + "micro_f1_score", + "macro_f1_score", + "weighted_recall_score", + "mean_squared_log_error", + "root_mean_squared_error", + "root_mean_squared_log_error", + # P = R = F = accuracy in multiclass case + "micro_f0.5_score", + "micro_f1_score", + "micro_f2_score", + "micro_precision_score", + "micro_recall_score", + "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", +} + +# Asymmetric with respect to their input arguments y_true and y_pred +# metric(y_true, y_pred) != metric(y_pred, y_true). +NOT_SYMMETRIC_METRICS = { + "balanced_accuracy_score", + "adjusted_balanced_accuracy_score", + "explained_variance_score", + "r2_score", + "unnormalized_confusion_matrix", + "normalized_confusion_matrix", + "roc_curve", + "precision_recall_curve", + "det_curve", + "precision_score", + "recall_score", + "f2_score", + "f0.5_score", + "weighted_f0.5_score", + "weighted_f1_score", + "weighted_f2_score", + "weighted_precision_score", + "weighted_jaccard_score", + "unnormalized_multilabel_confusion_matrix", + "macro_f0.5_score", + "macro_f2_score", + "macro_precision_score", + "macro_recall_score", + "hinge_loss", + "mean_gamma_deviance", + "mean_poisson_deviance", + "mean_compound_poisson_deviance", + "d2_tweedie_score", + "d2_pinball_score", + "d2_absolute_error_score", + "mean_absolute_percentage_error", +} + + +# No Sample weight support +METRICS_WITHOUT_SAMPLE_WEIGHT = { + "median_absolute_error", + "max_error", + "ovo_roc_auc", + "weighted_ovo_roc_auc", +} + +METRICS_REQUIRE_POSITIVE_Y = { + "mean_poisson_deviance", + "mean_gamma_deviance", + "mean_compound_poisson_deviance", + "d2_tweedie_score", +} + +# Metrics involving y = log(1+x) +METRICS_WITH_LOG1P_Y = { + "mean_squared_log_error", + "root_mean_squared_log_error", +} + + +def _require_positive_targets(y1, y2): + """Make targets strictly positive""" + offset = abs(min(y1.min(), y2.min())) + 1 + y1 += offset + y2 += offset + return y1, y2 + + +def _require_log1p_targets(y1, y2): + """Make targets strictly larger than -1""" + offset = abs(min(y1.min(), y2.min())) - 0.99 + y1 = y1.astype(np.float64) + y2 = y2.astype(np.float64) + y1 += offset + y2 += offset + return y1, y2 + + +def test_symmetry_consistency(): + # We shouldn't forget any metrics + assert ( + SYMMETRIC_METRICS + | NOT_SYMMETRIC_METRICS + | set(THRESHOLDED_METRICS) + | METRIC_UNDEFINED_BINARY_MULTICLASS + ) == set(ALL_METRICS) + + assert (SYMMETRIC_METRICS & NOT_SYMMETRIC_METRICS) == set() + + +@pytest.mark.parametrize("name", sorted(SYMMETRIC_METRICS)) +def test_symmetric_metric(name): + # Test the symmetry of score and loss functions + 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) + + elif name in METRICS_WITH_LOG1P_Y: + y_true, y_pred = _require_log1p_targets(y_true, y_pred) + + y_true_bin = random_state.randint(0, 2, size=(20, 25)) + y_pred_bin = random_state.randint(0, 2, size=(20, 25)) + + metric = ALL_METRICS[name] + if name in METRIC_UNDEFINED_BINARY: + if name in MULTILABELS_METRICS: + assert_allclose( + metric(y_true_bin, y_pred_bin), + metric(y_pred_bin, y_true_bin), + err_msg="%s is not symmetric" % name, + ) + else: + assert False, "This case is currently unhandled" + else: + assert_allclose( + metric(y_true, y_pred), + metric(y_pred, y_true), + err_msg="%s is not symmetric" % name, + ) + + +@pytest.mark.parametrize("name", sorted(NOT_SYMMETRIC_METRICS)) +def test_not_symmetric_metric(name): + # Test the symmetry of score and loss functions + random_state = check_random_state(0) + metric = ALL_METRICS[name] + + # The metric can be accidentally symmetric on a random draw. + # We run several random draws to check that at least of them + # gives an asymmetric result. + always_symmetric = True + for _ in range(5): + 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) + + nominal = metric(y_true, y_pred) + swapped = metric(y_pred, y_true) + if not np.allclose(nominal, swapped): + always_symmetric = False + break + + if always_symmetric: + raise ValueError(f"{name} seems to be symmetric") + + +def test_symmetry_tests(): + # check test_symmetric_metric and test_not_symmetric_metric + sym = "accuracy_score" + not_sym = "recall_score" + # test_symmetric_metric passes on a symmetric metric + # but fails on a not symmetric metric + test_symmetric_metric(sym) + with pytest.raises(AssertionError, match=f"{not_sym} is not symmetric"): + test_symmetric_metric(not_sym) + # test_not_symmetric_metric passes on a not symmetric metric + # but fails on a symmetric metric + test_not_symmetric_metric(not_sym) + with pytest.raises(ValueError, match=f"{sym} seems to be symmetric"): + test_not_symmetric_metric(sym) + + +@pytest.mark.parametrize( + "name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) +) +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) + elif name in METRICS_WITH_LOG1P_Y: + y_true, y_pred = _require_log1p_targets(y_true, y_pred) + + y_true_shuffle, y_pred_shuffle = shuffle(y_true, y_pred, random_state=0) + + with ignore_warnings(): + metric = ALL_METRICS[name] + assert_allclose( + metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" % name, + ) + + +def test_sample_order_invariance_multilabel_and_multioutput(): + random_state = check_random_state(0) + + # Generate some data + y_true = random_state.randint(0, 2, size=(20, 25)) + y_pred = random_state.randint(0, 2, size=(20, 25)) + y_score = random_state.uniform(size=y_true.shape) + + # Some metrics (e.g. log_loss) require y_score to be probabilities (sum to 1) + y_score /= y_score.sum(axis=1, keepdims=True) + + y_true_shuffle, y_pred_shuffle, y_score_shuffle = shuffle( + y_true, y_pred, y_score, random_state=0 + ) + + for name in MULTILABELS_METRICS: + metric = ALL_METRICS[name] + assert_allclose( + metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" % name, + ) + + for name in THRESHOLDED_MULTILABEL_METRICS: + metric = ALL_METRICS[name] + assert_allclose( + metric(y_true, y_score), + metric(y_true_shuffle, y_score_shuffle), + err_msg="%s is not sample order invariant" % name, + ) + + for name in MULTIOUTPUT_METRICS: + metric = ALL_METRICS[name] + assert_allclose( + metric(y_true, y_score), + metric(y_true_shuffle, y_score_shuffle), + err_msg="%s is not sample order invariant" % name, + ) + assert_allclose( + metric(y_true, y_pred), + metric(y_true_shuffle, y_pred_shuffle), + err_msg="%s is not sample order invariant" % name, + ) + + +@pytest.mark.parametrize( + "name", sorted(set(ALL_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) +) +def test_format_invariance_with_1d_vectors(name): + random_state = check_random_state(0) + y1 = random_state.randint(0, 2, size=(20,)) + y2 = random_state.randint(0, 2, size=(20,)) + + if name in METRICS_REQUIRE_POSITIVE_Y: + y1, y2 = _require_positive_targets(y1, y2) + elif name in METRICS_WITH_LOG1P_Y: + y1, y2 = _require_log1p_targets(y1, y2) + + y1_list = list(y1) + y2_list = list(y2) + + y1_1d, y2_1d = np.array(y1), np.array(y2) + assert_array_equal(y1_1d.ndim, 1) + assert_array_equal(y2_1d.ndim, 1) + y1_column = np.reshape(y1_1d, (-1, 1)) + y2_column = np.reshape(y2_1d, (-1, 1)) + y1_row = np.reshape(y1_1d, (1, -1)) + y2_row = np.reshape(y2_1d, (1, -1)) + + with ignore_warnings(): + metric = ALL_METRICS[name] + + measure = metric(y1, y2) + + assert_allclose( + metric(y1_list, y2_list), + measure, + err_msg="%s is not representation invariant with list" % name, + ) + + assert_allclose( + metric(y1_1d, y2_1d), + measure, + err_msg="%s is not representation invariant with np-array-1d" % name, + ) + + assert_allclose( + metric(y1_column, y2_column), + measure, + err_msg="%s is not representation invariant with np-array-column" % name, + ) + + # Mix format support + assert_allclose( + metric(y1_1d, y2_list), + measure, + err_msg="%s is not representation invariant with mix np-array-1d and list" + % name, + ) + + assert_allclose( + metric(y1_list, y2_1d), + measure, + err_msg="%s is not representation invariant with mix np-array-1d and list" + % name, + ) + + assert_allclose( + metric(y1_1d, y2_column), + measure, + err_msg=( + "%s is not representation invariant with mix " + "np-array-1d and np-array-column" + ) + % name, + ) + + assert_allclose( + metric(y1_column, y2_1d), + measure, + err_msg=( + "%s is not representation invariant with mix " + "np-array-1d and np-array-column" + ) + % name, + ) + + assert_allclose( + metric(y1_list, y2_column), + measure, + err_msg=( + "%s is not representation invariant with mix list and np-array-column" + ) + % name, + ) + + assert_allclose( + metric(y1_column, y2_list), + measure, + err_msg=( + "%s is not representation invariant with mix list and np-array-column" + ) + % name, + ) + + # These mix representations aren't allowed + with pytest.raises(ValueError): + metric(y1_1d, y2_row) + with pytest.raises(ValueError): + metric(y1_row, y2_1d) + with pytest.raises(ValueError): + metric(y1_list, y2_row) + with pytest.raises(ValueError): + metric(y1_row, y2_list) + with pytest.raises(ValueError): + metric(y1_column, y2_row) + with pytest.raises(ValueError): + metric(y1_row, y2_column) + + # NB: We do not test for y1_row, y2_row as these may be + # interpreted as multilabel or multioutput data. + if name not in ( + MULTIOUTPUT_METRICS | THRESHOLDED_MULTILABEL_METRICS | MULTILABELS_METRICS + ): + if "roc_auc" in name: + # for consistency between the `roc_cuve` and `roc_auc_score` + # np.nan is returned and an `UndefinedMetricWarning` is raised + with pytest.warns(UndefinedMetricWarning): + assert math.isnan(metric(y1_row, y2_row)) + else: + with pytest.raises(ValueError): + metric(y1_row, y2_row) + + +@pytest.mark.parametrize( + "name", sorted(set(CLASSIFICATION_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) +) +def test_classification_invariance_string_vs_numbers_labels(name): + # Ensure that classification metrics with string labels are invariant + random_state = check_random_state(0) + y1 = random_state.randint(0, 2, size=(20,)) + y2 = random_state.randint(0, 2, size=(20,)) + + y1_str = np.array(["eggs", "spam"])[y1] + y2_str = np.array(["eggs", "spam"])[y2] + + pos_label_str = "spam" + labels_str = ["eggs", "spam"] + + with ignore_warnings(): + metric = CLASSIFICATION_METRICS[name] + measure_with_number = metric(y1, y2) + + # Ugly, but handle case with a pos_label and label + metric_str = metric + if name in METRICS_WITH_POS_LABEL: + metric_str = partial(metric_str, pos_label=pos_label_str) + + measure_with_str = metric_str(y1_str, y2_str) + + assert_array_equal( + measure_with_number, + measure_with_str, + err_msg="{0} failed string vs number invariance test".format(name), + ) + + measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O")) + assert_array_equal( + measure_with_number, + measure_with_strobj, + err_msg="{0} failed string object vs number invariance test".format(name), + ) + + if name in METRICS_WITH_LABELS: + metric_str = partial(metric_str, labels=labels_str) + measure_with_str = metric_str(y1_str, y2_str) + assert_array_equal( + measure_with_number, + measure_with_str, + err_msg="{0} failed string vs number invariance test".format(name), + ) + + measure_with_strobj = metric_str(y1_str.astype("O"), y2_str.astype("O")) + assert_array_equal( + measure_with_number, + measure_with_strobj, + err_msg="{0} failed string vs number invariance test".format(name), + ) + + +@pytest.mark.parametrize("name", THRESHOLDED_METRICS) +def test_thresholded_invariance_string_vs_numbers_labels(name): + # Ensure that thresholded metrics with string labels are invariant + random_state = check_random_state(0) + y1 = random_state.randint(0, 2, size=(20,)) + y2 = random_state.randint(0, 2, size=(20,)) + + y1_str = np.array(["eggs", "spam"])[y1] + + pos_label_str = "spam" + + with ignore_warnings(): + metric = THRESHOLDED_METRICS[name] + if name not in METRIC_UNDEFINED_BINARY: + # Ugly, but handle case with a pos_label and label + metric_str = metric + if name in METRICS_WITH_POS_LABEL: + metric_str = partial(metric_str, pos_label=pos_label_str) + + measure_with_number = metric(y1, y2) + measure_with_str = metric_str(y1_str, y2) + assert_array_equal( + measure_with_number, + measure_with_str, + err_msg="{0} failed string vs number invariance test".format(name), + ) + + measure_with_strobj = metric_str(y1_str.astype("O"), y2) + assert_array_equal( + measure_with_number, + measure_with_strobj, + err_msg="{0} failed string object vs number invariance test".format( + name + ), + ) + else: + # TODO those metrics doesn't support string label yet + with pytest.raises(ValueError): + metric(y1_str, y2) + with pytest.raises(ValueError): + metric(y1_str.astype("O"), y2) + + +invalids_nan_inf = [ + ([0, 1], [np.inf, np.inf]), + ([0, 1], [np.nan, np.nan]), + ([0, 1], [np.nan, np.inf]), + ([0, 1], [np.inf, 1]), + ([0, 1], [np.nan, 1]), +] + + +@pytest.mark.parametrize( + "metric", chain(THRESHOLDED_METRICS.values(), REGRESSION_METRICS.values()) +) +@pytest.mark.parametrize("y_true, y_score", invalids_nan_inf) +def test_regression_thresholded_inf_nan_input(metric, y_true, y_score): + # Reshape since coverage_error only accepts 2D arrays. + if metric == coverage_error: + y_true = [y_true] + y_score = [y_score] + with pytest.raises(ValueError, match=r"contains (NaN|infinity)"): + metric(y_true, y_score) + + +@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values()) +@pytest.mark.parametrize( + "y_true, y_score", + invalids_nan_inf + + + # 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]), + ([np.inf, 1, 2], [1, 2, 3]), + ], +) +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.""" + 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) + + +@pytest.mark.parametrize("metric", CLASSIFICATION_METRICS.values()) +def test_classification_binary_continuous_input(metric): + """check that classification metrics raise a message of mixed type data + with continuous/binary target vectors.""" + y_true, y_score = ["a", "b", "a"], [0.1, 0.2, 0.3] + err_msg = ( + "Classification metrics can't handle a mix of binary and continuous targets" + ) + with pytest.raises(ValueError, match=err_msg): + metric(y_true, y_score) + + +def check_single_sample(name): + # Non-regression test: scores should work with a single sample. + # This is important for leave-one-out cross validation. + # Score functions tested are those that formerly called np.squeeze, + # which turns an array of size 1 into a 0-d array (!). + metric = ALL_METRICS[name] + + # assert that no exception is thrown + if name in METRICS_REQUIRE_POSITIVE_Y: + values = [1, 2] + elif name in METRICS_WITH_LOG1P_Y: + values = [-0.7, 1] + else: + values = [0, 1] + for i, j in product(values, repeat=2): + metric([i], [j]) + + +def check_single_sample_multioutput(name): + metric = ALL_METRICS[name] + for i, j, k, l in product([0, 1], repeat=4): + metric(np.array([[i, j]]), np.array([[k, l]])) + + +# filter many metric specific warnings +@pytest.mark.filterwarnings("ignore") +@pytest.mark.parametrize( + "name", + sorted( + set(ALL_METRICS) + # Those metrics are not always defined with one sample + # or in multiclass classification + - METRIC_UNDEFINED_BINARY_MULTICLASS + - set(THRESHOLDED_METRICS) + ), +) +def test_single_sample(name): + check_single_sample(name) + + +# filter many metric specific warnings +@pytest.mark.filterwarnings("ignore") +@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS | MULTILABELS_METRICS)) +def test_single_sample_multioutput(name): + check_single_sample_multioutput(name) + + +@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS)) +def test_multioutput_number_of_output_differ(name): + y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) + y_pred = np.array([[0, 0], [1, 0], [0, 0]]) + + metric = ALL_METRICS[name] + with pytest.raises(ValueError): + metric(y_true, y_pred) + + +@pytest.mark.parametrize("name", sorted(MULTIOUTPUT_METRICS)) +def test_multioutput_regression_invariance_to_dimension_shuffling(name): + # test invariance to dimension shuffling + random_state = check_random_state(0) + y_true = random_state.uniform(0, 2, size=(20, 5)) + y_pred = random_state.uniform(0, 2, size=(20, 5)) + + metric = ALL_METRICS[name] + error = metric(y_true, y_pred) + + for _ in range(3): + perm = random_state.permutation(y_true.shape[1]) + assert_allclose( + metric(y_true[:, perm], y_pred[:, perm]), + error, + err_msg="%s is not dimension shuffling invariant" % (name), + ) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.UndefinedMetricWarning") +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_multilabel_representation_invariance(coo_container): + # Generate some data + n_classes = 4 + n_samples = 50 + + _, y1 = make_multilabel_classification( + n_features=1, + n_classes=n_classes, + random_state=0, + n_samples=n_samples, + allow_unlabeled=True, + ) + _, y2 = make_multilabel_classification( + n_features=1, + n_classes=n_classes, + random_state=1, + n_samples=n_samples, + allow_unlabeled=True, + ) + + # To make sure at least one empty label is present + y1 = np.vstack([y1, [[0] * n_classes]]) + y2 = np.vstack([y2, [[0] * n_classes]]) + + y1_sparse_indicator = coo_container(y1) + y2_sparse_indicator = coo_container(y2) + + y1_list_array_indicator = list(y1) + y2_list_array_indicator = list(y2) + + y1_list_list_indicator = [list(a) for a in y1_list_array_indicator] + y2_list_list_indicator = [list(a) for a in y2_list_array_indicator] + + for name in MULTILABELS_METRICS: + metric = ALL_METRICS[name] + + # XXX cruel hack to work with partial functions + if isinstance(metric, partial): + metric.__module__ = "tmp" + metric.__name__ = name + + measure = metric(y1, y2) + + # Check representation invariance + assert_allclose( + metric(y1_sparse_indicator, y2_sparse_indicator), + measure, + err_msg=( + "%s failed representation invariance between " + "dense and sparse indicator formats." + ) + % name, + ) + assert_almost_equal( + metric(y1_list_list_indicator, y2_list_list_indicator), + measure, + err_msg=( + "%s failed representation invariance " + "between dense array and list of list " + "indicator formats." + ) + % name, + ) + assert_almost_equal( + metric(y1_list_array_indicator, y2_list_array_indicator), + measure, + err_msg=( + "%s failed representation invariance " + "between dense and list of array " + "indicator formats." + ) + % name, + ) + + +@pytest.mark.parametrize("name", sorted(MULTILABELS_METRICS)) +def test_raise_value_error_multilabel_sequences(name): + # make sure the multilabel-sequence format raises ValueError + multilabel_sequences = [ + [[1], [2], [0, 1]], + [(), (2), (0, 1)], + [[]], + [()], + np.array([[], [1, 2]], dtype="object"), + ] + + metric = ALL_METRICS[name] + for seq in multilabel_sequences: + with pytest.raises(ValueError): + metric(seq, seq) + + +@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, 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] + 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}", + ) + + +@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, 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] + 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}", + ) + + +@pytest.mark.parametrize( + "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 + _, y_true = make_multilabel_classification( + n_features=1, + n_classes=n_classes, + random_state=0, + allow_unlabeled=True, + n_samples=n_samples, + ) + _, y_pred = make_multilabel_classification( + n_features=1, + n_classes=n_classes, + random_state=1, + 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 + + 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}", + ) + + +def _check_averaging( + metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel +): + n_samples, n_classes = y_true_binarize.shape + + # No averaging + label_measure = metric(y_true, y_pred, average=None) + assert_allclose( + label_measure, + [ + metric(y_true_binarize[:, i], y_pred_binarize[:, i]) + for i in range(n_classes) + ], + ) + + # Micro measure + micro_measure = metric(y_true, y_pred, average="micro") + assert_allclose( + micro_measure, metric(y_true_binarize.ravel(), y_pred_binarize.ravel()) + ) + + # Macro measure + macro_measure = metric(y_true, y_pred, average="macro") + assert_allclose(macro_measure, np.mean(label_measure)) + + # Weighted measure + weights = np.sum(y_true_binarize, axis=0, dtype=int) + + if np.sum(weights) != 0: + weighted_measure = metric(y_true, y_pred, average="weighted") + assert_allclose(weighted_measure, np.average(label_measure, weights=weights)) + else: + weighted_measure = metric(y_true, y_pred, average="weighted") + assert_allclose(weighted_measure, 0) + + # Sample measure + if is_multilabel: + sample_measure = metric(y_true, y_pred, average="samples") + assert_allclose( + sample_measure, + np.mean( + [ + metric(y_true_binarize[i], y_pred_binarize[i]) + for i in range(n_samples) + ] + ), + ) + + with pytest.raises(ValueError): + metric(y_true, y_pred, average="unknown") + with pytest.raises(ValueError): + metric(y_true, y_pred, average="garbage") + + +def check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score): + is_multilabel = type_of_target(y_true).startswith("multilabel") + + metric = ALL_METRICS[name] + + if name in METRICS_WITH_AVERAGING: + _check_averaging( + metric, y_true, y_pred, y_true_binarize, y_pred_binarize, is_multilabel + ) + elif name in THRESHOLDED_METRICS_WITH_AVERAGING: + _check_averaging( + metric, y_true, y_score, y_true_binarize, y_score, is_multilabel + ) + else: + raise ValueError("Metric is not recorded as having an average option") + + +@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING)) +def test_averaging_multiclass(name): + n_samples, n_classes = 50, 3 + random_state = check_random_state(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)) + + lb = LabelBinarizer().fit(y_true) + y_true_binarize = lb.transform(y_true) + y_pred_binarize = lb.transform(y_pred) + + check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) + + +@pytest.mark.parametrize( + "name", sorted(METRICS_WITH_AVERAGING | THRESHOLDED_METRICS_WITH_AVERAGING) +) +def test_averaging_multilabel(name): + n_samples, n_classes = 40, 5 + _, y = make_multilabel_classification( + n_features=1, + n_classes=n_classes, + random_state=5, + n_samples=n_samples, + allow_unlabeled=False, + ) + y_true = y[:20] + y_pred = y[20:] + y_score = check_random_state(0).normal(size=(20, n_classes)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) + + +@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING)) +def test_averaging_multilabel_all_zeroes(name): + y_true = np.zeros((20, 3)) + y_pred = np.zeros((20, 3)) + y_score = np.zeros((20, 3)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) + + +def test_averaging_binary_multilabel_all_zeroes(): + y_true = np.zeros((20, 3)) + y_pred = np.zeros((20, 3)) + y_true_binarize = y_true + y_pred_binarize = y_pred + # Test _average_binary_score for weight.sum() == 0 + binary_metric = lambda y_true, y_score, average="macro": _average_binary_score( + precision_score, y_true, y_score, average + ) + _check_averaging( + binary_metric, + y_true, + y_pred, + y_true_binarize, + y_pred_binarize, + is_multilabel=True, + ) + + +@pytest.mark.parametrize("name", sorted(METRICS_WITH_AVERAGING)) +def test_averaging_multilabel_all_ones(name): + y_true = np.ones((20, 3)) + y_pred = np.ones((20, 3)) + y_score = np.ones((20, 3)) + y_true_binarize = y_true + y_pred_binarize = y_pred + + check_averaging(name, y_true, y_true_binarize, y_pred, y_pred_binarize, y_score) + + +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) + + assert_allclose( + unweighted_score, + metric(y1, y2, sample_weight=np.ones(shape=len(y1))), + err_msg="For %s sample_weight=None is not equivalent to sample_weight=ones" + % name, + ) + + # check that the weighted and unweighted scores are unequal + weighted_score = metric(y1, y2, sample_weight=sample_weight) + + # use context manager to supply custom error message + with pytest.raises(AssertionError): + assert_allclose(unweighted_score, weighted_score) + raise ValueError( + "Unweighted and weighted scores are unexpectedly " + "almost equal (%s) and (%s) " + "for %s" % (unweighted_score, weighted_score, name) + ) + + # check that sample_weight can be a list + weighted_score_list = metric(y1, y2, sample_weight=sample_weight.tolist()) + assert_allclose( + weighted_score, + weighted_score_list, + err_msg=( + "Weighted scores for array and list " + "sample_weight input are not equal (%s != %s) for %s" + ) + % (weighted_score, weighted_score_list, name), + ) + + # check that integer weights is the same as repeated samples + repeat_weighted_score = metric( + np.repeat(y1, sample_weight, axis=0), + np.repeat(y2, sample_weight, axis=0), + sample_weight=None, + ) + assert_allclose( + weighted_score, + repeat_weighted_score, + err_msg="Weighting %s is not equal to repeating samples" % name, + ) + + # check that ignoring a fraction of the samples is equivalent to setting + # the corresponding weights to zero + sample_weight_subset = sample_weight[1::2] + sample_weight_zeroed = np.copy(sample_weight) + sample_weight_zeroed[::2] = 0 + y1_subset = y1[1::2] + y2_subset = y2[1::2] + weighted_score_subset = metric( + y1_subset, y2_subset, sample_weight=sample_weight_subset + ) + weighted_score_zeroed = metric(y1, y2, sample_weight=sample_weight_zeroed) + assert_allclose( + weighted_score_subset, + weighted_score_zeroed, + err_msg=( + "Zeroing weights does not give the same result as " + "removing the corresponding samples (%s != %s) for %s" + ) + % (weighted_score_zeroed, weighted_score_subset, name), + ) + + if not name.startswith("unnormalized"): + # check that the score is invariant under scaling of the weights by a + # common factor + for scaling in [2, 0.3]: + assert_allclose( + weighted_score, + metric(y1, y2, sample_weight=sample_weight * scaling), + err_msg="%s sample_weight is not invariant under scaling" % name, + ) + + # Check that if number of samples in y_true and sample_weight are not + # equal, meaningful error is raised. + error_message = ( + r"Found input variables with inconsistent numbers of " + r"samples: \[{}, {}, {}\]".format( + _num_samples(y1), _num_samples(y2), _num_samples(sample_weight) * 2 + ) + ) + with pytest.raises(ValueError, match=error_message): + metric(y1, y2, sample_weight=np.hstack([sample_weight, sample_weight])) + + +@pytest.mark.parametrize( + "name", + sorted( + set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) + - METRICS_WITHOUT_SAMPLE_WEIGHT + ), +) +def test_regression_sample_weight_invariance(name): + n_samples = 50 + random_state = check_random_state(0) + # regression + y_true = random_state.random_sample(size=(n_samples,)) + y_pred = random_state.random_sample(size=(n_samples,)) + metric = ALL_METRICS[name] + check_sample_weight_invariance(name, metric, y_true, y_pred) + + +@pytest.mark.parametrize( + "name", + sorted( + set(ALL_METRICS).intersection(set(REGRESSION_METRICS)) + - METRICS_WITHOUT_SAMPLE_WEIGHT + ), +) +def test_regression_with_invalid_sample_weight(name): + # Check that `sample_weight` with incorrect length raises error + n_samples = 50 + random_state = check_random_state(0) + y_true = random_state.random_sample(size=(n_samples,)) + y_pred = random_state.random_sample(size=(n_samples,)) + metric = ALL_METRICS[name] + + sample_weight = random_state.random_sample(size=(n_samples - 1,)) + with pytest.raises(ValueError, match="Found input variables with inconsistent"): + metric(y_true, y_pred, sample_weight=sample_weight) + + sample_weight = random_state.random_sample(size=(n_samples * 2,)).reshape( + (n_samples, 2) + ) + with pytest.raises(ValueError, match="Sample weights must be 1D array or scalar"): + metric(y_true, y_pred, sample_weight=sample_weight) + + +@pytest.mark.parametrize( + "name", + sorted( + set(ALL_METRICS) + - set(REGRESSION_METRICS) + - METRICS_WITHOUT_SAMPLE_WEIGHT + - METRIC_UNDEFINED_BINARY + ), +) +def test_binary_sample_weight_invariance(name): + # binary + n_samples = 50 + 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_score = random_state.random_sample(size=(n_samples,)) + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + check_sample_weight_invariance(name, metric, y_true, y_score) + else: + check_sample_weight_invariance(name, metric, y_true, y_pred) + + +@pytest.mark.parametrize( + "name", + sorted( + set(ALL_METRICS) + - set(REGRESSION_METRICS) + - METRICS_WITHOUT_SAMPLE_WEIGHT + - METRIC_UNDEFINED_BINARY_MULTICLASS + ), +) +def test_multiclass_sample_weight_invariance(name): + # multiclass + n_samples = 50 + random_state = check_random_state(0) + y_true = random_state.randint(0, 5, size=(n_samples,)) + y_pred = random_state.randint(0, 5, size=(n_samples,)) + y_score = random_state.random_sample(size=(n_samples, 5)) + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + # softmax + temp = np.exp(-y_score) + y_score_norm = temp / temp.sum(axis=-1).reshape(-1, 1) + check_sample_weight_invariance(name, metric, y_true, y_score_norm) + else: + check_sample_weight_invariance(name, metric, y_true, y_pred) + + +@pytest.mark.parametrize( + "name", + sorted( + (MULTILABELS_METRICS | THRESHOLDED_MULTILABEL_METRICS) + - METRICS_WITHOUT_SAMPLE_WEIGHT + ), +) +def test_multilabel_sample_weight_invariance(name): + # multilabel indicator + random_state = check_random_state(0) + _, ya = make_multilabel_classification( + n_features=1, n_classes=10, random_state=0, n_samples=50, allow_unlabeled=False + ) + _, yb = make_multilabel_classification( + n_features=1, n_classes=10, random_state=1, n_samples=50, allow_unlabeled=False + ) + y_true = np.vstack([ya, yb]) + y_pred = np.vstack([ya, ya]) + y_score = random_state.uniform(size=y_true.shape) + + # Some metrics (e.g. log_loss) require y_score to be probabilities (sum to 1) + y_score /= y_score.sum(axis=1, keepdims=True) + + metric = ALL_METRICS[name] + if name in THRESHOLDED_METRICS: + check_sample_weight_invariance(name, metric, y_true, y_score) + else: + check_sample_weight_invariance(name, metric, y_true, y_pred) + + +@pytest.mark.parametrize( + "name", + sorted(MULTIOUTPUT_METRICS - METRICS_WITHOUT_SAMPLE_WEIGHT), +) +def test_multioutput_sample_weight_invariance(name): + random_state = check_random_state(0) + y_true = random_state.uniform(0, 2, size=(20, 5)) + y_pred = random_state.uniform(0, 2, size=(20, 5)) + + metric = ALL_METRICS[name] + check_sample_weight_invariance(name, metric, y_true, y_pred) + + +def test_no_averaging_labels(): + # test labels argument when not using averaging + # in multi-class and multi-label cases + y_true_multilabel = np.array([[1, 1, 0, 0], [1, 1, 0, 0]]) + y_pred_multilabel = np.array([[0, 0, 1, 1], [0, 1, 1, 0]]) + y_true_multiclass = np.array([0, 1, 2]) + y_pred_multiclass = np.array([0, 2, 3]) + labels = np.array([3, 0, 1, 2]) + _, inverse_labels = np.unique(labels, return_inverse=True) + + for name in METRICS_WITH_AVERAGING: + for y_true, y_pred in [ + [y_true_multiclass, y_pred_multiclass], + [y_true_multilabel, y_pred_multilabel], + ]: + if name not in MULTILABELS_METRICS and y_pred.ndim > 1: + continue + + metric = ALL_METRICS[name] + + score_labels = metric(y_true, y_pred, labels=labels, average=None) + score = metric(y_true, y_pred, average=None) + assert_array_equal(score_labels, score[inverse_labels]) + + +@pytest.mark.parametrize( + "name", sorted(MULTILABELS_METRICS - {"unnormalized_multilabel_confusion_matrix"}) +) +def test_multilabel_label_permutations_invariance(name): + random_state = check_random_state(0) + n_samples, n_classes = 20, 4 + + y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) + y_score = random_state.randint(0, 2, size=(n_samples, n_classes)) + + metric = ALL_METRICS[name] + score = metric(y_true, y_score) + + for perm in permutations(range(n_classes), n_classes): + y_score_perm = y_score[:, perm] + y_true_perm = y_true[:, perm] + + current_score = metric(y_true_perm, y_score_perm) + assert_almost_equal(score, current_score) + + +@pytest.mark.parametrize( + "name", sorted(THRESHOLDED_MULTILABEL_METRICS | MULTIOUTPUT_METRICS) +) +def test_thresholded_multilabel_multioutput_permutations_invariance(name): + random_state = check_random_state(0) + n_samples, n_classes = 20, 4 + y_true = random_state.randint(0, 2, size=(n_samples, n_classes)) + y_score = random_state.uniform(size=y_true.shape) + + # Some metrics (e.g. log_loss) require y_score to be probabilities (sum to 1) + y_score /= y_score.sum(axis=1, keepdims=True) + + # Makes sure all samples have at least one label. This works around errors + # when running metrics where average="sample" + y_true[y_true.sum(1) == 4, 0] = 0 + y_true[y_true.sum(1) == 0, 0] = 1 + + metric = ALL_METRICS[name] + score = metric(y_true, y_score) + + for perm in permutations(range(n_classes), n_classes): + y_score_perm = y_score[:, perm] + y_true_perm = y_true[:, perm] + + current_score = metric(y_true_perm, y_score_perm) + if metric == mean_absolute_percentage_error: + assert np.isfinite(current_score) + assert current_score > 1e6 + # Here we are not comparing the values in case of MAPE because + # whenever y_true value is exactly zero, the MAPE value doesn't + # signify anything. Thus, in this case we are just expecting + # very large finite value. + else: + assert_almost_equal(score, current_score) + + +@pytest.mark.parametrize( + "name", sorted(set(THRESHOLDED_METRICS) - METRIC_UNDEFINED_BINARY_MULTICLASS) +) +def test_thresholded_metric_permutation_invariance(name): + n_samples, n_classes = 100, 3 + random_state = check_random_state(0) + + y_score = random_state.rand(n_samples, n_classes) + temp = np.exp(-y_score) + y_score = temp / temp.sum(axis=-1).reshape(-1, 1) + y_true = random_state.randint(0, n_classes, size=n_samples) + + metric = ALL_METRICS[name] + score = metric(y_true, y_score) + for perm in permutations(range(n_classes), n_classes): + inverse_perm = np.zeros(n_classes, dtype=int) + inverse_perm[list(perm)] = np.arange(n_classes) + y_score_perm = y_score[:, inverse_perm] + y_true_perm = np.take(perm, y_true) + + current_score = metric(y_true_perm, y_score_perm) + assert_almost_equal(score, current_score) + + +@pytest.mark.parametrize("metric_name", CLASSIFICATION_METRICS) +def test_metrics_consistent_type_error(metric_name): + # check that an understable message is raised when the type between y_true + # and y_pred mismatch + rng = np.random.RandomState(42) + y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=object) + y2 = rng.randint(0, 2, size=y1.size) + + err_msg = "Labels in y_true and y_pred should be of the same type." + with pytest.raises(TypeError, match=err_msg): + CLASSIFICATION_METRICS[metric_name](y1, y2) + + +@pytest.mark.parametrize( + "metric, y_pred_threshold", + [ + (average_precision_score, True), + (brier_score_loss, True), + (f1_score, False), + (partial(fbeta_score, beta=1), False), + (jaccard_score, False), + (precision_recall_curve, True), + (precision_score, False), + (recall_score, False), + (roc_curve, True), + ], +) +@pytest.mark.parametrize("dtype_y_str", [str, object]) +def test_metrics_pos_label_error_str(metric, y_pred_threshold, dtype_y_str): + # check that the error message if `pos_label` is not specified and the + # targets is made of strings. + rng = np.random.RandomState(42) + y1 = np.array(["spam"] * 3 + ["eggs"] * 2, dtype=dtype_y_str) + y2 = rng.randint(0, 2, size=y1.size) + + if not y_pred_threshold: + y2 = np.array(["spam", "eggs"], dtype=dtype_y_str)[y2] + + err_msg_pos_label_None = ( + "y_true takes value in {'eggs', 'spam'} and pos_label is not " + "specified: either make y_true take value in {0, 1} or {-1, 1} or " + "pass pos_label explicit" + ) + err_msg_pos_label_1 = ( + r"pos_label=1 is not a valid label. It should be one of \['eggs', 'spam'\]" + ) + + pos_label_default = signature(metric).parameters["pos_label"].default + + err_msg = err_msg_pos_label_1 if pos_label_default == 1 else err_msg_pos_label_None + with pytest.raises(ValueError, match=err_msg): + metric(y1, y2) + + +def check_array_api_metric( + metric, array_namespace, device, dtype_name, a_np, b_np, **metric_kwargs +): + xp = _array_api_for_tests(array_namespace, device) + + a_xp = xp.asarray(a_np, device=device) + b_xp = xp.asarray(b_np, device=device) + + metric_np = metric(a_np, b_np, **metric_kwargs) + + if metric_kwargs.get("sample_weight") is not None: + metric_kwargs["sample_weight"] = xp.asarray( + metric_kwargs["sample_weight"], device=device + ) + + multioutput = metric_kwargs.get("multioutput") + if isinstance(multioutput, np.ndarray): + metric_kwargs["multioutput"] = xp.asarray(multioutput, device=device) + + # When array API dispatch is disabled, and np.asarray works (for example PyTorch + # with CPU device), calling the metric function with such numpy compatible inputs + # should work (albeit by implicitly converting to numpy arrays instead of + # dispatching to the array library). + try: + np.asarray(a_xp) + np.asarray(b_xp) + numpy_as_array_works = True + except (TypeError, RuntimeError, ValueError): + # PyTorch with CUDA device and CuPy raise TypeError consistently. + # array-api-strict chose to raise RuntimeError instead. NumPy raises + # a ValueError if the `__array__` dunder does not return an array. + # Exception type may need to be updated in the future for other libraries. + numpy_as_array_works = False + + if numpy_as_array_works: + metric_xp = metric(a_xp, b_xp, **metric_kwargs) + assert_allclose( + metric_xp, + metric_np, + atol=_atol_for_type(dtype_name), + ) + metric_xp_mixed_1 = metric(a_np, b_xp, **metric_kwargs) + assert_allclose( + metric_xp_mixed_1, + metric_np, + atol=_atol_for_type(dtype_name), + ) + metric_xp_mixed_2 = metric(a_xp, b_np, **metric_kwargs) + assert_allclose( + metric_xp_mixed_2, + metric_np, + atol=_atol_for_type(dtype_name), + ) + + with config_context(array_api_dispatch=True): + metric_xp = metric(a_xp, b_xp, **metric_kwargs) + + assert_allclose( + _convert_to_numpy(xp.asarray(metric_xp), xp), + metric_np, + atol=_atol_for_type(dtype_name), + ) + + +def check_array_api_binary_classification_metric( + metric, array_namespace, device, dtype_name +): + y_true_np = np.array([0, 0, 1, 1]) + y_pred_np = np.array([0, 1, 0, 1]) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=None, + ) + + sample_weight = np.array([0.0, 0.1, 2.0, 1.0], dtype=dtype_name) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=sample_weight, + ) + + +def check_array_api_multiclass_classification_metric( + metric, array_namespace, device, dtype_name +): + y_true_np = np.array([0, 1, 2, 3]) + y_pred_np = np.array([0, 1, 0, 2]) + + additional_params = { + "average": ("micro", "macro", "weighted"), + "beta": (0.2, 0.5, 0.8), + } + metric_kwargs_combinations = _get_metric_kwargs_for_array_api_testing( + metric=metric, + params=additional_params, + ) + for metric_kwargs in metric_kwargs_combinations: + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=None, + **metric_kwargs, + ) + + sample_weight = np.array([0.0, 0.1, 2.0, 1.0], dtype=dtype_name) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=sample_weight, + **metric_kwargs, + ) + + +def check_array_api_multilabel_classification_metric( + metric, array_namespace, device, dtype_name +): + y_true_np = np.array([[1, 1], [0, 1], [0, 0]], dtype=dtype_name) + y_pred_np = np.array([[1, 1], [1, 1], [1, 1]], dtype=dtype_name) + + additional_params = { + "average": ("micro", "macro", "weighted"), + "beta": (0.2, 0.5, 0.8), + } + metric_kwargs_combinations = _get_metric_kwargs_for_array_api_testing( + metric=metric, + params=additional_params, + ) + for metric_kwargs in metric_kwargs_combinations: + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=None, + **metric_kwargs, + ) + + sample_weight = np.array([0.0, 0.1, 2.0], dtype=dtype_name) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=sample_weight, + **metric_kwargs, + ) + + +def check_array_api_regression_metric(metric, array_namespace, device, dtype_name): + func_name = metric.func.__name__ if isinstance(metric, partial) else metric.__name__ + if func_name == "mean_poisson_deviance" and sp_version < parse_version("1.14.0"): + pytest.skip( + "mean_poisson_deviance's dependency `xlogy` is available as of scipy 1.14.0" + ) + + y_true_np = np.array([2.0, 0.1, 1.0, 4.0], dtype=dtype_name) + y_pred_np = np.array([0.5, 0.5, 2, 2], dtype=dtype_name) + + metric_kwargs = {} + metric_params = signature(metric).parameters + + if "sample_weight" in metric_params: + metric_kwargs["sample_weight"] = None + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + **metric_kwargs, + ) + + if "sample_weight" in metric_params: + metric_kwargs["sample_weight"] = np.array( + [0.1, 2.0, 1.5, 0.5], dtype=dtype_name + ) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + **metric_kwargs, + ) + + +def check_array_api_regression_metric_multioutput( + metric, array_namespace, device, dtype_name +): + y_true_np = np.array([[1, 3, 2], [1, 2, 2]], dtype=dtype_name) + y_pred_np = np.array([[1, 4, 4], [1, 1, 1]], dtype=dtype_name) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=None, + ) + + sample_weight = np.array([0.1, 2.0], dtype=dtype_name) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + sample_weight=sample_weight, + ) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + multioutput=np.array([0.1, 0.3, 0.7], dtype=dtype_name), + ) + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=y_true_np, + b_np=y_pred_np, + multioutput="raw_values", + ) + + +def check_array_api_metric_pairwise(metric, array_namespace, device, dtype_name): + X_np = np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]], dtype=dtype_name) + Y_np = np.array([[0.2, 0.3, 0.4], [0.5, 0.6, 0.7]], dtype=dtype_name) + + metric_kwargs = {} + if "dense_output" in signature(metric).parameters: + metric_kwargs["dense_output"] = False + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=X_np, + b_np=Y_np, + **metric_kwargs, + ) + metric_kwargs["dense_output"] = True + + check_array_api_metric( + metric, + array_namespace, + device, + dtype_name, + a_np=X_np, + b_np=Y_np, + **metric_kwargs, + ) + + +array_api_metric_checkers = { + accuracy_score: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + f1_score: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + fbeta_score: [ + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + jaccard_score: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + multilabel_confusion_matrix: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + precision_score: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + recall_score: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + zero_one_loss: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + hamming_loss: [ + check_array_api_binary_classification_metric, + check_array_api_multiclass_classification_metric, + check_array_api_multilabel_classification_metric, + ], + mean_tweedie_deviance: [check_array_api_regression_metric], + partial(mean_tweedie_deviance, power=-0.5): [check_array_api_regression_metric], + partial(mean_tweedie_deviance, power=1.5): [check_array_api_regression_metric], + r2_score: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + cosine_similarity: [check_array_api_metric_pairwise], + explained_variance_score: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + mean_absolute_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + mean_pinball_loss: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + mean_squared_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + mean_squared_log_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + d2_tweedie_score: [ + check_array_api_regression_metric, + ], + paired_cosine_distances: [check_array_api_metric_pairwise], + mean_poisson_deviance: [check_array_api_regression_metric], + additive_chi2_kernel: [check_array_api_metric_pairwise], + mean_gamma_deviance: [check_array_api_regression_metric], + max_error: [check_array_api_regression_metric], + mean_absolute_percentage_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + chi2_kernel: [check_array_api_metric_pairwise], + paired_euclidean_distances: [check_array_api_metric_pairwise], + cosine_distances: [check_array_api_metric_pairwise], + euclidean_distances: [check_array_api_metric_pairwise], + linear_kernel: [check_array_api_metric_pairwise], + polynomial_kernel: [check_array_api_metric_pairwise], + rbf_kernel: [check_array_api_metric_pairwise], + root_mean_squared_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + root_mean_squared_log_error: [ + check_array_api_regression_metric, + check_array_api_regression_metric_multioutput, + ], + sigmoid_kernel: [check_array_api_metric_pairwise], +} + + +def yield_metric_checker_combinations(metric_checkers=array_api_metric_checkers): + for metric, checkers in metric_checkers.items(): + for checker in checkers: + yield metric, checker + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", + yield_namespace_device_dtype_combinations(), + ids=_get_namespace_device_dtype_ids, +) +@pytest.mark.parametrize("metric, check_func", yield_metric_checker_combinations()) +def test_array_api_compliance(metric, array_namespace, device, dtype_name, check_func): + check_func(metric, array_namespace, device, dtype_name) + + +@pytest.mark.parametrize("df_lib_name", ["pandas", "polars"]) +@pytest.mark.parametrize("metric_name", sorted(ALL_METRICS)) +def test_metrics_dataframe_series(metric_name, df_lib_name): + df_lib = pytest.importorskip(df_lib_name) + + y_pred = df_lib.Series([0.0, 1.0, 0, 1.0]) + y_true = df_lib.Series([1.0, 0.0, 0.0, 0.0]) + + metric = ALL_METRICS[metric_name] + try: + expected_metric = metric(y_pred.to_numpy(), y_true.to_numpy()) + except ValueError: + pytest.skip(f"{metric_name} can not deal with 1d inputs") + + assert_allclose(metric(y_pred, y_true), expected_metric) + + +def _get_metric_kwargs_for_array_api_testing(metric, params): + """Helper function to enable specifying a variety of additional params and + their corresponding values, so that they can be passed to a metric function + when testing for array api compliance.""" + metric_kwargs_combinations = [{}] + for param, values in params.items(): + if param not in signature(metric).parameters: + continue + + new_combinations = [] + for kwargs in metric_kwargs_combinations: + for value in values: + new_kwargs = kwargs.copy() + new_kwargs[param] = value + new_combinations.append(new_kwargs) + + metric_kwargs_combinations = new_combinations + + return metric_kwargs_combinations + + +@pytest.mark.parametrize("name", sorted(ALL_METRICS)) +def test_returned_value_consistency(name): + """Ensure that the returned values of all metrics are consistent. + + It can either be a float, a numpy array, or a tuple of floats or numpy arrays. + It should not be a numpy float64 or float32. + """ + + rng = np.random.RandomState(0) + y_true = rng.randint(0, 2, size=(20,)) + y_pred = rng.randint(0, 2, size=(20,)) + + if name in METRICS_REQUIRE_POSITIVE_Y: + y_true, y_pred = _require_positive_targets(y_true, y_pred) + + if name in METRIC_UNDEFINED_BINARY: + y_true = rng.randint(0, 2, size=(20, 3)) + y_pred = rng.randint(0, 2, size=(20, 3)) + + metric = ALL_METRICS[name] + score = metric(y_true, y_pred) + + assert isinstance(score, (float, np.ndarray, tuple)) + assert not isinstance(score, (np.float64, np.float32)) + + if isinstance(score, tuple): + assert all(isinstance(v, float) for v in score) or all( + isinstance(v, np.ndarray) for v in score + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..f93d3b984bdb7c218d0517ca9e6c21ec930f96fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_dist_metrics.py @@ -0,0 +1,431 @@ +import copy +import itertools +import pickle + +import numpy as np +import pytest +from scipy.spatial.distance import cdist + +from sklearn.metrics import DistanceMetric +from sklearn.metrics._dist_metrics import ( + BOOL_METRICS, + DEPRECATED_METRICS, + DistanceMetric32, + DistanceMetric64, +) +from sklearn.utils import check_random_state +from sklearn.utils._testing import ( + assert_allclose, + create_memmap_backed_data, + ignore_warnings, +) +from sklearn.utils.fixes import CSR_CONTAINERS + + +def dist_func(x1, x2, p): + return np.sum((x1 - x2) ** p) ** (1.0 / p) + + +rng = check_random_state(0) +d = 4 +n1 = 20 +n2 = 25 +X64 = rng.random_sample((n1, d)) +Y64 = rng.random_sample((n2, d)) +X32 = X64.astype("float32") +Y32 = Y64.astype("float32") + +[X_mmap, Y_mmap] = create_memmap_backed_data([X64, Y64]) + +# make boolean arrays: ones and zeros +X_bool = (X64 < 0.3).astype(np.float64) # quite sparse +Y_bool = (Y64 < 0.7).astype(np.float64) # not too sparse + +[X_bool_mmap, Y_bool_mmap] = create_memmap_backed_data([X_bool, Y_bool]) + + +V = rng.random_sample((d, d)) +VI = np.dot(V, V.T) + +METRICS_DEFAULT_PARAMS = [ + ("euclidean", {}), + ("cityblock", {}), + ("minkowski", dict(p=(0.5, 1, 1.5, 2, 3))), + ("chebyshev", {}), + ("seuclidean", dict(V=(rng.random_sample(d),))), + ("mahalanobis", dict(VI=(VI,))), + ("hamming", {}), + ("canberra", {}), + ("braycurtis", {}), + ("minkowski", dict(p=(0.5, 1, 1.5, 3), w=(rng.random_sample(d),))), +] + + +@pytest.mark.parametrize( + "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0] +) +@pytest.mark.parametrize("X, Y", [(X64, Y64), (X32, Y32), (X_mmap, Y_mmap)]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_cdist(metric_param_grid, X, Y, csr_container): + metric, param_grid = metric_param_grid + keys = param_grid.keys() + X_csr, Y_csr = csr_container(X), csr_container(Y) + for vals in itertools.product(*param_grid.values()): + kwargs = dict(zip(keys, vals)) + rtol_dict = {} + if metric == "mahalanobis" and X.dtype == np.float32: + # Computation of mahalanobis differs between + # the scipy and scikit-learn implementation. + # Hence, we increase the relative tolerance. + # TODO: Inspect slight numerical discrepancy + # with scipy + rtol_dict = {"rtol": 1e-6} + + D_scipy_cdist = cdist(X, Y, metric, **kwargs) + + dm = DistanceMetric.get_metric(metric, X.dtype, **kwargs) + + # DistanceMetric.pairwise must be consistent for all + # combinations of formats in {sparse, dense}. + D_sklearn = dm.pairwise(X, Y) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict) + + D_sklearn = dm.pairwise(X_csr, Y_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict) + + D_sklearn = dm.pairwise(X_csr, Y) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict) + + D_sklearn = dm.pairwise(X, Y_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist, **rtol_dict) + + +@pytest.mark.parametrize("metric", BOOL_METRICS) +@pytest.mark.parametrize( + "X_bool, Y_bool", [(X_bool, Y_bool), (X_bool_mmap, Y_bool_mmap)] +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_cdist_bool_metric(metric, X_bool, Y_bool, csr_container): + if metric in DEPRECATED_METRICS: + with ignore_warnings(category=DeprecationWarning): + # Some metrics can be deprecated depending on the scipy version. + # But if they are present, we still want to test whether + # scikit-learn gives the same result, whether or not they are + # deprecated. + D_scipy_cdist = cdist(X_bool, Y_bool, metric) + else: + D_scipy_cdist = cdist(X_bool, Y_bool, metric) + + dm = DistanceMetric.get_metric(metric) + D_sklearn = dm.pairwise(X_bool, Y_bool) + assert_allclose(D_sklearn, D_scipy_cdist) + + # DistanceMetric.pairwise must be consistent + # on all combinations of format in {sparse, dense}². + X_bool_csr, Y_bool_csr = csr_container(X_bool), csr_container(Y_bool) + + D_sklearn = dm.pairwise(X_bool, Y_bool) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist) + + D_sklearn = dm.pairwise(X_bool_csr, Y_bool_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist) + + D_sklearn = dm.pairwise(X_bool, Y_bool_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist) + + D_sklearn = dm.pairwise(X_bool_csr, Y_bool) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_cdist) + + +@pytest.mark.parametrize( + "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0] +) +@pytest.mark.parametrize("X", [X64, X32, X_mmap]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pdist(metric_param_grid, X, csr_container): + metric, param_grid = metric_param_grid + keys = param_grid.keys() + X_csr = csr_container(X) + for vals in itertools.product(*param_grid.values()): + kwargs = dict(zip(keys, vals)) + rtol_dict = {} + if metric == "mahalanobis" and X.dtype == np.float32: + # Computation of mahalanobis differs between + # the scipy and scikit-learn implementation. + # Hence, we increase the relative tolerance. + # TODO: Inspect slight numerical discrepancy + # with scipy + rtol_dict = {"rtol": 1e-6} + + D_scipy_pdist = cdist(X, X, metric, **kwargs) + + dm = DistanceMetric.get_metric(metric, X.dtype, **kwargs) + D_sklearn = dm.pairwise(X) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_scipy_pdist, **rtol_dict) + + D_sklearn_csr = dm.pairwise(X_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn_csr, D_scipy_pdist, **rtol_dict) + + D_sklearn_csr = dm.pairwise(X_csr, X_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn_csr, D_scipy_pdist, **rtol_dict) + + +@pytest.mark.parametrize( + "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0] +) +def test_distance_metrics_dtype_consistency(metric_param_grid): + # DistanceMetric must return similar distances for both float32 and float64 + # input data. + metric, param_grid = metric_param_grid + keys = param_grid.keys() + + # Choose rtol to make sure that this test is robust to changes in the random + # seed in the module-level test data generation code. + rtol = 1e-5 + + for vals in itertools.product(*param_grid.values()): + kwargs = dict(zip(keys, vals)) + dm64 = DistanceMetric.get_metric(metric, np.float64, **kwargs) + dm32 = DistanceMetric.get_metric(metric, np.float32, **kwargs) + + D64 = dm64.pairwise(X64) + D32 = dm32.pairwise(X32) + + assert D64.dtype == np.float64 + assert D32.dtype == np.float32 + + # assert_allclose introspects the dtype of the input arrays to decide + # which rtol value to use by default but in this case we know that D32 + # is not computed with the same precision so we set rtol manually. + assert_allclose(D64, D32, rtol=rtol) + + D64 = dm64.pairwise(X64, Y64) + D32 = dm32.pairwise(X32, Y32) + assert_allclose(D64, D32, rtol=rtol) + + +@pytest.mark.parametrize("metric", BOOL_METRICS) +@pytest.mark.parametrize("X_bool", [X_bool, X_bool_mmap]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pdist_bool_metrics(metric, X_bool, csr_container): + if metric in DEPRECATED_METRICS: + with ignore_warnings(category=DeprecationWarning): + # Some metrics can be deprecated depending on the scipy version. + # But if they are present, we still want to test whether + # scikit-learn gives the same result, whether or not they are + # deprecated. + D_scipy_pdist = cdist(X_bool, X_bool, metric) + else: + D_scipy_pdist = cdist(X_bool, X_bool, metric) + + dm = DistanceMetric.get_metric(metric) + D_sklearn = dm.pairwise(X_bool) + assert_allclose(D_sklearn, D_scipy_pdist) + + X_bool_csr = csr_container(X_bool) + D_sklearn = dm.pairwise(X_bool_csr) + assert_allclose(D_sklearn, D_scipy_pdist) + + +@pytest.mark.parametrize("writable_kwargs", [True, False]) +@pytest.mark.parametrize( + "metric_param_grid", METRICS_DEFAULT_PARAMS, ids=lambda params: params[0] +) +@pytest.mark.parametrize("X", [X64, X32]) +def test_pickle(writable_kwargs, metric_param_grid, X): + metric, param_grid = metric_param_grid + keys = param_grid.keys() + for vals in itertools.product(*param_grid.values()): + if any(isinstance(val, np.ndarray) for val in vals): + vals = copy.deepcopy(vals) + for val in vals: + if isinstance(val, np.ndarray): + val.setflags(write=writable_kwargs) + kwargs = dict(zip(keys, vals)) + dm = DistanceMetric.get_metric(metric, X.dtype, **kwargs) + D1 = dm.pairwise(X) + dm2 = pickle.loads(pickle.dumps(dm)) + D2 = dm2.pairwise(X) + assert_allclose(D1, D2) + + +@pytest.mark.parametrize("metric", BOOL_METRICS) +@pytest.mark.parametrize("X_bool", [X_bool, X_bool_mmap]) +def test_pickle_bool_metrics(metric, X_bool): + dm = DistanceMetric.get_metric(metric) + D1 = dm.pairwise(X_bool) + dm2 = pickle.loads(pickle.dumps(dm)) + D2 = dm2.pairwise(X_bool) + assert_allclose(D1, D2) + + +@pytest.mark.parametrize("X, Y", [(X64, Y64), (X32, Y32), (X_mmap, Y_mmap)]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_haversine_metric(X, Y, csr_container): + # The Haversine DistanceMetric only works on 2 features. + X = np.asarray(X[:, :2]) + Y = np.asarray(Y[:, :2]) + + X_csr, Y_csr = csr_container(X), csr_container(Y) + + # Haversine is not supported by scipy.special.distance.{cdist,pdist} + # So we reimplement it to have a reference. + def haversine_slow(x1, x2): + return 2 * np.arcsin( + np.sqrt( + np.sin(0.5 * (x1[0] - x2[0])) ** 2 + + np.cos(x1[0]) * np.cos(x2[0]) * np.sin(0.5 * (x1[1] - x2[1])) ** 2 + ) + ) + + D_reference = np.zeros((X_csr.shape[0], Y_csr.shape[0])) + for i, xi in enumerate(X): + for j, yj in enumerate(Y): + D_reference[i, j] = haversine_slow(xi, yj) + + haversine = DistanceMetric.get_metric("haversine", X.dtype) + + D_sklearn = haversine.pairwise(X, Y) + assert_allclose( + haversine.dist_to_rdist(D_sklearn), np.sin(0.5 * D_reference) ** 2, rtol=1e-6 + ) + + assert_allclose(D_sklearn, D_reference) + + D_sklearn = haversine.pairwise(X_csr, Y_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_reference) + + D_sklearn = haversine.pairwise(X_csr, Y) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_reference) + + D_sklearn = haversine.pairwise(X, Y_csr) + assert D_sklearn.flags.c_contiguous + assert_allclose(D_sklearn, D_reference) + + +def test_pyfunc_metric(): + X = np.random.random((10, 3)) + + euclidean = DistanceMetric.get_metric("euclidean") + pyfunc = DistanceMetric.get_metric("pyfunc", func=dist_func, p=2) + + # Check if both callable metric and predefined metric initialized + # DistanceMetric object is picklable + euclidean_pkl = pickle.loads(pickle.dumps(euclidean)) + pyfunc_pkl = pickle.loads(pickle.dumps(pyfunc)) + + D1 = euclidean.pairwise(X) + D2 = pyfunc.pairwise(X) + + D1_pkl = euclidean_pkl.pairwise(X) + D2_pkl = pyfunc_pkl.pairwise(X) + + assert_allclose(D1, D2) + assert_allclose(D1_pkl, D2_pkl) + + +def test_input_data_size(): + # Regression test for #6288 + # Previously, a metric requiring a particular input dimension would fail + def custom_metric(x, y): + assert x.shape[0] == 3 + return np.sum((x - y) ** 2) + + rng = check_random_state(0) + X = rng.rand(10, 3) + + pyfunc = DistanceMetric.get_metric("pyfunc", func=custom_metric) + eucl = DistanceMetric.get_metric("euclidean") + assert_allclose(pyfunc.pairwise(X), eucl.pairwise(X) ** 2) + + +def test_readonly_kwargs(): + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/21685 + + rng = check_random_state(0) + + weights = rng.rand(100) + VI = rng.rand(10, 10) + weights.setflags(write=False) + VI.setflags(write=False) + + # Those distances metrics have to support readonly buffers. + DistanceMetric.get_metric("seuclidean", V=weights) + DistanceMetric.get_metric("mahalanobis", VI=VI) + + +@pytest.mark.parametrize( + "w, err_type, err_msg", + [ + (np.array([1, 1.5, -13]), ValueError, "w cannot contain negative weights"), + (np.array([1, 1.5, np.nan]), ValueError, "w contains NaN"), + *[ + ( + csr_container([[1, 1.5, 1]]), + TypeError, + "Sparse data was passed for w, but dense data is required", + ) + for csr_container in CSR_CONTAINERS + ], + (np.array(["a", "b", "c"]), ValueError, "could not convert string to float"), + (np.array([]), ValueError, "a minimum of 1 is required"), + ], +) +def test_minkowski_metric_validate_weights_values(w, err_type, err_msg): + with pytest.raises(err_type, match=err_msg): + DistanceMetric.get_metric("minkowski", p=3, w=w) + + +def test_minkowski_metric_validate_weights_size(): + w2 = rng.random_sample(d + 1) + dm = DistanceMetric.get_metric("minkowski", p=3, w=w2) + msg = ( + "MinkowskiDistance: the size of w must match " + f"the number of features \\({X64.shape[1]}\\). " + f"Currently len\\(w\\)={w2.shape[0]}." + ) + with pytest.raises(ValueError, match=msg): + dm.pairwise(X64, Y64) + + +@pytest.mark.parametrize("metric, metric_kwargs", METRICS_DEFAULT_PARAMS) +@pytest.mark.parametrize("dtype", (np.float32, np.float64)) +def test_get_metric_dtype(metric, metric_kwargs, dtype): + specialized_cls = { + np.float32: DistanceMetric32, + np.float64: DistanceMetric64, + }[dtype] + + # We don't need the entire grid, just one for a sanity check + metric_kwargs = {k: v[0] for k, v in metric_kwargs.items()} + generic_type = type(DistanceMetric.get_metric(metric, dtype, **metric_kwargs)) + specialized_type = type(specialized_cls.get_metric(metric, **metric_kwargs)) + + assert generic_type is specialized_type + + +def test_get_metric_bad_dtype(): + dtype = np.int32 + msg = r"Unexpected dtype .* provided. Please select a dtype from" + with pytest.raises(ValueError, match=msg): + DistanceMetric.get_metric("manhattan", dtype) + + +def test_minkowski_metric_validate_bad_p_parameter(): + msg = "p must be greater than 0" + with pytest.raises(ValueError, match=msg): + DistanceMetric.get_metric("minkowski", p=0) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py new file mode 100644 index 0000000000000000000000000000000000000000..4c1ba4b2f7d5280235ed2038ac2bd933db4b701d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise.py @@ -0,0 +1,1683 @@ +import warnings +from types import GeneratorType + +import numpy as np +import pytest +from numpy import linalg +from scipy.sparse import issparse +from scipy.spatial.distance import ( + cdist, + cityblock, + cosine, + minkowski, + pdist, + squareform, +) + +from sklearn import config_context +from sklearn.exceptions import DataConversionWarning +from sklearn.metrics.pairwise import ( + PAIRED_DISTANCES, + PAIRWISE_BOOLEAN_FUNCTIONS, + PAIRWISE_DISTANCE_FUNCTIONS, + PAIRWISE_KERNEL_FUNCTIONS, + _euclidean_distances_upcast, + additive_chi2_kernel, + check_paired_arrays, + check_pairwise_arrays, + chi2_kernel, + cosine_distances, + cosine_similarity, + euclidean_distances, + haversine_distances, + laplacian_kernel, + linear_kernel, + manhattan_distances, + nan_euclidean_distances, + paired_cosine_distances, + paired_distances, + paired_euclidean_distances, + paired_manhattan_distances, + pairwise_distances, + pairwise_distances_argmin, + pairwise_distances_argmin_min, + pairwise_distances_chunked, + pairwise_kernels, + polynomial_kernel, + rbf_kernel, + sigmoid_kernel, +) +from sklearn.preprocessing import normalize +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_equal, + ignore_warnings, +) +from sklearn.utils.fixes import ( + BSR_CONTAINERS, + COO_CONTAINERS, + CSC_CONTAINERS, + CSR_CONTAINERS, + DOK_CONTAINERS, +) +from sklearn.utils.parallel import Parallel, delayed + + +def test_pairwise_distances_for_dense_data(global_dtype): + # Test the pairwise_distance helper function. + rng = np.random.RandomState(0) + + # Euclidean distance should be equivalent to calling the function. + X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + S = pairwise_distances(X, metric="euclidean") + S2 = euclidean_distances(X) + assert_allclose(S, S2) + assert S.dtype == S2.dtype == global_dtype + + # Euclidean distance, with Y != X. + Y = rng.random_sample((2, 4)).astype(global_dtype, copy=False) + S = pairwise_distances(X, Y, metric="euclidean") + S2 = euclidean_distances(X, Y) + assert_allclose(S, S2) + assert S.dtype == S2.dtype == global_dtype + + # Check to ensure NaNs work with pairwise_distances. + X_masked = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + Y_masked = rng.random_sample((2, 4)).astype(global_dtype, copy=False) + X_masked[0, 0] = np.nan + Y_masked[0, 0] = np.nan + S_masked = pairwise_distances(X_masked, Y_masked, metric="nan_euclidean") + S2_masked = nan_euclidean_distances(X_masked, Y_masked) + assert_allclose(S_masked, S2_masked) + assert S_masked.dtype == S2_masked.dtype == global_dtype + + # Test with tuples as X and Y + X_tuples = tuple([tuple([v for v in row]) for row in X]) + Y_tuples = tuple([tuple([v for v in row]) for row in Y]) + S2 = pairwise_distances(X_tuples, Y_tuples, metric="euclidean") + assert_allclose(S, S2) + assert S.dtype == S2.dtype == global_dtype + + # Test haversine distance + # The data should be valid latitude and longitude + # haversine converts to float64 currently so we don't check dtypes. + X = rng.random_sample((5, 2)).astype(global_dtype, copy=False) + X[:, 0] = (X[:, 0] - 0.5) * 2 * np.pi / 2 + X[:, 1] = (X[:, 1] - 0.5) * 2 * np.pi + S = pairwise_distances(X, metric="haversine") + S2 = haversine_distances(X) + assert_allclose(S, S2) + + # Test haversine distance, with Y != X + Y = rng.random_sample((2, 2)).astype(global_dtype, copy=False) + Y[:, 0] = (Y[:, 0] - 0.5) * 2 * np.pi / 2 + Y[:, 1] = (Y[:, 1] - 0.5) * 2 * np.pi + S = pairwise_distances(X, Y, metric="haversine") + S2 = haversine_distances(X, Y) + assert_allclose(S, S2) + + # "cityblock" uses scikit-learn metric, cityblock (function) is + # scipy.spatial. + # The metric functions from scipy converts to float64 so we don't check the dtypes. + S = pairwise_distances(X, metric="cityblock") + S2 = pairwise_distances(X, metric=cityblock) + assert S.shape[0] == S.shape[1] + assert S.shape[0] == X.shape[0] + assert_allclose(S, S2) + + # The manhattan metric should be equivalent to cityblock. + S = pairwise_distances(X, Y, metric="manhattan") + S2 = pairwise_distances(X, Y, metric=cityblock) + assert S.shape[0] == X.shape[0] + assert S.shape[1] == Y.shape[0] + assert_allclose(S, S2) + + # Test cosine as a string metric versus cosine callable + # The string "cosine" uses sklearn.metric, + # while the function cosine is scipy.spatial + S = pairwise_distances(X, Y, metric="cosine") + S2 = pairwise_distances(X, Y, metric=cosine) + assert S.shape[0] == X.shape[0] + assert S.shape[1] == Y.shape[0] + assert_allclose(S, S2) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +@pytest.mark.parametrize("csc_container", CSC_CONTAINERS) +@pytest.mark.parametrize("bsr_container", BSR_CONTAINERS) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_distances_for_sparse_data( + coo_container, csc_container, bsr_container, csr_container, global_dtype +): + # Test the pairwise_distance helper function. + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + Y = rng.random_sample((2, 4)).astype(global_dtype, copy=False) + + # Test with sparse X and Y, + # currently only supported for Euclidean, L1 and cosine. + X_sparse = csr_container(X) + Y_sparse = csr_container(Y) + + S = pairwise_distances(X_sparse, Y_sparse, metric="euclidean") + S2 = euclidean_distances(X_sparse, Y_sparse) + assert_allclose(S, S2) + assert S.dtype == S2.dtype == global_dtype + + S = pairwise_distances(X_sparse, Y_sparse, metric="cosine") + S2 = cosine_distances(X_sparse, Y_sparse) + assert_allclose(S, S2) + assert S.dtype == S2.dtype == global_dtype + + S = pairwise_distances(X_sparse, csc_container(Y), metric="manhattan") + S2 = manhattan_distances(bsr_container(X), coo_container(Y)) + assert_allclose(S, S2) + if global_dtype == np.float64: + assert S.dtype == S2.dtype == global_dtype + else: + # TODO Fix manhattan_distances to preserve dtype. + # currently pairwise_distances uses manhattan_distances but converts the result + # back to the input dtype + with pytest.raises(AssertionError): + assert S.dtype == S2.dtype == global_dtype + + S2 = manhattan_distances(X, Y) + assert_allclose(S, S2) + if global_dtype == np.float64: + assert S.dtype == S2.dtype == global_dtype + else: + # TODO Fix manhattan_distances to preserve dtype. + # currently pairwise_distances uses manhattan_distances but converts the result + # back to the input dtype + with pytest.raises(AssertionError): + assert S.dtype == S2.dtype == global_dtype + + # Test with scipy.spatial.distance metric, with a kwd + kwds = {"p": 2.0} + S = pairwise_distances(X, Y, metric="minkowski", **kwds) + S2 = pairwise_distances(X, Y, metric=minkowski, **kwds) + assert_allclose(S, S2) + + # same with Y = None + kwds = {"p": 2.0} + S = pairwise_distances(X, metric="minkowski", **kwds) + S2 = pairwise_distances(X, metric=minkowski, **kwds) + assert_allclose(S, S2) + + # Test that scipy distance metrics throw an error if sparse matrix given + with pytest.raises(TypeError): + pairwise_distances(X_sparse, metric="minkowski") + with pytest.raises(TypeError): + pairwise_distances(X, Y_sparse, metric="minkowski") + + +# Some scipy metrics are deprecated (depending on the scipy version) but we +# still want to test them. +@ignore_warnings(category=DeprecationWarning) +@pytest.mark.parametrize("metric", PAIRWISE_BOOLEAN_FUNCTIONS) +def test_pairwise_boolean_distance(metric): + # test that we convert to boolean arrays for boolean distances + rng = np.random.RandomState(0) + X = rng.randn(5, 4) + Y = X.copy() + Y[0, 0] = 1 - Y[0, 0] + + # ignore conversion to boolean in pairwise_distances + with ignore_warnings(category=DataConversionWarning): + for Z in [Y, None]: + res = pairwise_distances(X, Z, metric=metric) + np.nan_to_num(res, nan=0, posinf=0, neginf=0, copy=False) + assert np.sum(res != 0) == 0 + + # non-boolean arrays are converted to boolean for boolean + # distance metrics with a data conversion warning + msg = "Data was converted to boolean for metric %s" % metric + with pytest.warns(DataConversionWarning, match=msg): + pairwise_distances(X, metric=metric) + + # Check that the warning is raised if X is boolean by Y is not boolean: + with pytest.warns(DataConversionWarning, match=msg): + pairwise_distances(X.astype(bool), Y=Y, metric=metric) + + # Check that no warning is raised if X is already boolean and Y is None: + with warnings.catch_warnings(): + warnings.simplefilter("error", DataConversionWarning) + pairwise_distances(X.astype(bool), metric=metric) + + +def test_no_data_conversion_warning(): + # No warnings issued if metric is not a boolean distance function + rng = np.random.RandomState(0) + X = rng.randn(5, 4) + with warnings.catch_warnings(): + warnings.simplefilter("error", DataConversionWarning) + pairwise_distances(X, metric="minkowski") + + +@pytest.mark.parametrize("func", [pairwise_distances, pairwise_kernels]) +def test_pairwise_precomputed(func): + # Test correct shape + with pytest.raises(ValueError, match=".* shape .*"): + func(np.zeros((5, 3)), metric="precomputed") + # with two args + with pytest.raises(ValueError, match=".* shape .*"): + func(np.zeros((5, 3)), np.zeros((4, 4)), metric="precomputed") + # even if shape[1] agrees (although thus second arg is spurious) + with pytest.raises(ValueError, match=".* shape .*"): + func(np.zeros((5, 3)), np.zeros((4, 3)), metric="precomputed") + + # Test not copied (if appropriate dtype) + S = np.zeros((5, 5)) + S2 = func(S, metric="precomputed") + assert S is S2 + # with two args + S = np.zeros((5, 3)) + S2 = func(S, np.zeros((3, 3)), metric="precomputed") + assert S is S2 + + # Test always returns float dtype + S = func(np.array([[1]], dtype="int"), metric="precomputed") + assert "f" == S.dtype.kind + + # Test converts list to array-like + S = func([[1.0]], metric="precomputed") + assert isinstance(S, np.ndarray) + + +def test_pairwise_precomputed_non_negative(): + # Test non-negative values + with pytest.raises(ValueError, match=".* non-negative values.*"): + pairwise_distances(np.full((5, 5), -1), metric="precomputed") + + +_minkowski_kwds = {"w": np.arange(1, 5).astype("double", copy=False), "p": 1} + + +def callable_rbf_kernel(x, y, **kwds): + # Callable version of pairwise.rbf_kernel. + K = rbf_kernel(np.atleast_2d(x), np.atleast_2d(y), **kwds) + # unpack the output since this is a scalar packed in a 0-dim array + return K.item() + + +@pytest.mark.parametrize( + "func, metric, kwds", + [ + (pairwise_distances, "euclidean", {}), + ( + pairwise_distances, + minkowski, + _minkowski_kwds, + ), + ( + pairwise_distances, + "minkowski", + _minkowski_kwds, + ), + (pairwise_kernels, "polynomial", {"degree": 1}), + (pairwise_kernels, callable_rbf_kernel, {"gamma": 0.1}), + ], +) +@pytest.mark.parametrize("dtype", [np.float64, np.float32, int]) +def test_pairwise_parallel(func, metric, kwds, dtype): + rng = np.random.RandomState(0) + X = np.array(5 * rng.random_sample((5, 4)), dtype=dtype) + Y = np.array(5 * rng.random_sample((3, 4)), dtype=dtype) + + S = func(X, metric=metric, n_jobs=1, **kwds) + S2 = func(X, metric=metric, n_jobs=2, **kwds) + assert_allclose(S, S2) + + S = func(X, Y, metric=metric, n_jobs=1, **kwds) + S2 = func(X, Y, metric=metric, n_jobs=2, **kwds) + assert_allclose(S, S2) + + +def test_pairwise_callable_nonstrict_metric(): + # paired_distances should allow callable metric where metric(x, x) != 0 + # Knowing that the callable is a strict metric would allow the diagonal to + # be left uncalculated and set to 0. + assert pairwise_distances([[1.0]], metric=lambda x, y: 5)[0, 0] == 5 + + +# Test with all metrics that should be in PAIRWISE_KERNEL_FUNCTIONS. +@pytest.mark.parametrize( + "metric", + ["rbf", "laplacian", "sigmoid", "polynomial", "linear", "chi2", "additive_chi2"], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_kernels(metric, csr_container): + # Test the pairwise_kernels helper function. + + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((2, 4)) + function = PAIRWISE_KERNEL_FUNCTIONS[metric] + # Test with Y=None + K1 = pairwise_kernels(X, metric=metric) + K2 = function(X) + assert_allclose(K1, K2) + # Test with Y=Y + K1 = pairwise_kernels(X, Y=Y, metric=metric) + K2 = function(X, Y=Y) + assert_allclose(K1, K2) + # Test with tuples as X and Y + X_tuples = tuple([tuple([v for v in row]) for row in X]) + Y_tuples = tuple([tuple([v for v in row]) for row in Y]) + K2 = pairwise_kernels(X_tuples, Y_tuples, metric=metric) + assert_allclose(K1, K2) + + # Test with sparse X and Y + X_sparse = csr_container(X) + Y_sparse = csr_container(Y) + if metric in ["chi2", "additive_chi2"]: + # these don't support sparse matrices yet + return + K1 = pairwise_kernels(X_sparse, Y=Y_sparse, metric=metric) + assert_allclose(K1, K2) + + +def test_pairwise_kernels_callable(): + # Test the pairwise_kernels helper function + # with a callable function, with given keywords. + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((2, 4)) + + metric = callable_rbf_kernel + kwds = {"gamma": 0.1} + K1 = pairwise_kernels(X, Y=Y, metric=metric, **kwds) + K2 = rbf_kernel(X, Y=Y, **kwds) + assert_allclose(K1, K2) + + # callable function, X=Y + K1 = pairwise_kernels(X, Y=X, metric=metric, **kwds) + K2 = rbf_kernel(X, Y=X, **kwds) + assert_allclose(K1, K2) + + +def test_pairwise_kernels_filter_param(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((2, 4)) + K = rbf_kernel(X, Y, gamma=0.1) + params = {"gamma": 0.1, "blabla": ":)"} + K2 = pairwise_kernels(X, Y, metric="rbf", filter_params=True, **params) + assert_allclose(K, K2) + + with pytest.raises(TypeError): + pairwise_kernels(X, Y, metric="rbf", **params) + + +@pytest.mark.parametrize("metric, func", PAIRED_DISTANCES.items()) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_paired_distances(metric, func, csr_container): + # Test the pairwise_distance helper function. + rng = np.random.RandomState(0) + # Euclidean distance should be equivalent to calling the function. + X = rng.random_sample((5, 4)) + # Euclidean distance, with Y != X. + Y = rng.random_sample((5, 4)) + + S = paired_distances(X, Y, metric=metric) + S2 = func(X, Y) + assert_allclose(S, S2) + S3 = func(csr_container(X), csr_container(Y)) + assert_allclose(S, S3) + if metric in PAIRWISE_DISTANCE_FUNCTIONS: + # Check the pairwise_distances implementation + # gives the same value + distances = PAIRWISE_DISTANCE_FUNCTIONS[metric](X, Y) + distances = np.diag(distances) + assert_allclose(distances, S) + + +def test_paired_distances_callable(global_dtype): + # Test the paired_distance helper function + # with the callable implementation + rng = np.random.RandomState(0) + # Euclidean distance should be equivalent to calling the function. + X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + # Euclidean distance, with Y != X. + Y = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + + S = paired_distances(X, Y, metric="manhattan") + S2 = paired_distances(X, Y, metric=lambda x, y: np.abs(x - y).sum(axis=0)) + assert_allclose(S, S2) + + # Test that a value error is raised when the lengths of X and Y should not + # differ + Y = rng.random_sample((3, 4)) + with pytest.raises(ValueError): + paired_distances(X, Y) + + +@pytest.mark.parametrize("dok_container", DOK_CONTAINERS) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_distances_argmin_min(dok_container, csr_container, global_dtype): + # Check pairwise minimum distances computation for any metric + X = np.asarray([[0], [1]], dtype=global_dtype) + Y = np.asarray([[-2], [3]], dtype=global_dtype) + + Xsp = dok_container(X) + Ysp = csr_container(Y, dtype=global_dtype) + + expected_idx = [0, 1] + expected_vals = [2, 2] + expected_vals_sq = [4, 4] + + # euclidean metric + idx, vals = pairwise_distances_argmin_min(X, Y, metric="euclidean") + idx2 = pairwise_distances_argmin(X, Y, metric="euclidean") + assert_allclose(idx, expected_idx) + assert_allclose(idx2, expected_idx) + assert_allclose(vals, expected_vals) + # sparse matrix case + idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric="euclidean") + idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric="euclidean") + assert_allclose(idxsp, expected_idx) + assert_allclose(idxsp2, expected_idx) + assert_allclose(valssp, expected_vals) + # We don't want np.matrix here + assert type(idxsp) == np.ndarray + assert type(valssp) == np.ndarray + + # Squared Euclidean metric + idx, vals = pairwise_distances_argmin_min(X, Y, metric="sqeuclidean") + idx2, vals2 = pairwise_distances_argmin_min( + X, Y, metric="euclidean", metric_kwargs={"squared": True} + ) + idx3 = pairwise_distances_argmin(X, Y, metric="sqeuclidean") + idx4 = pairwise_distances_argmin( + X, Y, metric="euclidean", metric_kwargs={"squared": True} + ) + + assert_allclose(vals, expected_vals_sq) + assert_allclose(vals2, expected_vals_sq) + + assert_allclose(idx, expected_idx) + assert_allclose(idx2, expected_idx) + assert_allclose(idx3, expected_idx) + assert_allclose(idx4, expected_idx) + + # Non-euclidean scikit-learn metric + idx, vals = pairwise_distances_argmin_min(X, Y, metric="manhattan") + idx2 = pairwise_distances_argmin(X, Y, metric="manhattan") + assert_allclose(idx, expected_idx) + assert_allclose(idx2, expected_idx) + assert_allclose(vals, expected_vals) + # sparse matrix case + idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric="manhattan") + idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric="manhattan") + assert_allclose(idxsp, expected_idx) + assert_allclose(idxsp2, expected_idx) + assert_allclose(valssp, expected_vals) + + # Non-euclidean Scipy distance (callable) + idx, vals = pairwise_distances_argmin_min( + X, Y, metric=minkowski, metric_kwargs={"p": 2} + ) + assert_allclose(idx, expected_idx) + assert_allclose(vals, expected_vals) + + # Non-euclidean Scipy distance (string) + idx, vals = pairwise_distances_argmin_min( + X, Y, metric="minkowski", metric_kwargs={"p": 2} + ) + assert_allclose(idx, expected_idx) + assert_allclose(vals, expected_vals) + + # Compare with naive implementation + rng = np.random.RandomState(0) + X = rng.randn(97, 149) + Y = rng.randn(111, 149) + + dist = pairwise_distances(X, Y, metric="manhattan") + dist_orig_ind = dist.argmin(axis=0) + dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))] + + dist_chunked_ind, dist_chunked_val = pairwise_distances_argmin_min( + X, Y, axis=0, metric="manhattan" + ) + assert_allclose(dist_orig_ind, dist_chunked_ind, rtol=1e-7) + assert_allclose(dist_orig_val, dist_chunked_val, rtol=1e-7) + + # Changing the axis and permuting datasets must give the same results + argmin_0, dist_0 = pairwise_distances_argmin_min(X, Y, axis=0) + argmin_1, dist_1 = pairwise_distances_argmin_min(Y, X, axis=1) + + assert_allclose(dist_0, dist_1) + assert_array_equal(argmin_0, argmin_1) + + argmin_0, dist_0 = pairwise_distances_argmin_min(X, X, axis=0) + argmin_1, dist_1 = pairwise_distances_argmin_min(X, X, axis=1) + + assert_allclose(dist_0, dist_1) + assert_array_equal(argmin_0, argmin_1) + + # Changing the axis and permuting datasets must give the same results + argmin_0 = pairwise_distances_argmin(X, Y, axis=0) + argmin_1 = pairwise_distances_argmin(Y, X, axis=1) + + assert_array_equal(argmin_0, argmin_1) + + argmin_0 = pairwise_distances_argmin(X, X, axis=0) + argmin_1 = pairwise_distances_argmin(X, X, axis=1) + + assert_array_equal(argmin_0, argmin_1) + + # F-contiguous arrays must be supported and must return identical results. + argmin_C_contiguous = pairwise_distances_argmin(X, Y) + argmin_F_contiguous = pairwise_distances_argmin( + np.asfortranarray(X), np.asfortranarray(Y) + ) + + assert_array_equal(argmin_C_contiguous, argmin_F_contiguous) + + +def _reduce_func(dist, start): + return dist[:, :100] + + +def test_pairwise_distances_chunked_reduce(global_dtype): + rng = np.random.RandomState(0) + X = rng.random_sample((400, 4)).astype(global_dtype, copy=False) + # Reduced Euclidean distance + S = pairwise_distances(X)[:, :100] + S_chunks = pairwise_distances_chunked( + X, None, reduce_func=_reduce_func, working_memory=2**-16 + ) + assert isinstance(S_chunks, GeneratorType) + S_chunks = list(S_chunks) + assert len(S_chunks) > 1 + assert S_chunks[0].dtype == X.dtype + + # atol is for diagonal where S is explicitly zeroed on the diagonal + assert_allclose(np.vstack(S_chunks), S, atol=1e-7) + + +def test_pairwise_distances_chunked_reduce_none(global_dtype): + # check that the reduce func is allowed to return None + rng = np.random.RandomState(0) + X = rng.random_sample((10, 4)).astype(global_dtype, copy=False) + S_chunks = pairwise_distances_chunked( + X, None, reduce_func=lambda dist, start: None, working_memory=2**-16 + ) + assert isinstance(S_chunks, GeneratorType) + S_chunks = list(S_chunks) + assert len(S_chunks) > 1 + assert all(chunk is None for chunk in S_chunks) + + +@pytest.mark.parametrize( + "good_reduce", + [ + lambda D, start: list(D), + lambda D, start: np.array(D), + lambda D, start: (list(D), list(D)), + ] + + [ + lambda D, start, scipy_csr_type=scipy_csr_type: scipy_csr_type(D) + for scipy_csr_type in CSR_CONTAINERS + ] + + [ + lambda D, start, scipy_dok_type=scipy_dok_type: ( + scipy_dok_type(D), + np.array(D), + list(D), + ) + for scipy_dok_type in DOK_CONTAINERS + ], +) +def test_pairwise_distances_chunked_reduce_valid(good_reduce): + X = np.arange(10).reshape(-1, 1) + S_chunks = pairwise_distances_chunked( + X, None, reduce_func=good_reduce, working_memory=64 + ) + next(S_chunks) + + +@pytest.mark.parametrize( + ("bad_reduce", "err_type", "message"), + [ + ( + lambda D, s: np.concatenate([D, D[-1:]]), + ValueError, + r"length 11\..* input: 10\.", + ), + ( + lambda D, s: (D, np.concatenate([D, D[-1:]])), + ValueError, + r"length \(10, 11\)\..* input: 10\.", + ), + (lambda D, s: (D[:9], D), ValueError, r"length \(9, 10\)\..* input: 10\."), + ( + lambda D, s: 7, + TypeError, + r"returned 7\. Expected sequence\(s\) of length 10\.", + ), + ( + lambda D, s: (7, 8), + TypeError, + r"returned \(7, 8\)\. Expected sequence\(s\) of length 10\.", + ), + ( + lambda D, s: (np.arange(10), 9), + TypeError, + r", 9\)\. Expected sequence\(s\) of length 10\.", + ), + ], +) +def test_pairwise_distances_chunked_reduce_invalid( + global_dtype, bad_reduce, err_type, message +): + X = np.arange(10).reshape(-1, 1).astype(global_dtype, copy=False) + S_chunks = pairwise_distances_chunked( + X, None, reduce_func=bad_reduce, working_memory=64 + ) + with pytest.raises(err_type, match=message): + next(S_chunks) + + +def check_pairwise_distances_chunked(X, Y, working_memory, metric="euclidean"): + gen = pairwise_distances_chunked(X, Y, working_memory=working_memory, metric=metric) + assert isinstance(gen, GeneratorType) + blockwise_distances = list(gen) + Y = X if Y is None else Y + min_block_mib = len(Y) * 8 * 2**-20 + + for block in blockwise_distances: + memory_used = block.nbytes + assert memory_used <= max(working_memory, min_block_mib) * 2**20 + + blockwise_distances = np.vstack(blockwise_distances) + S = pairwise_distances(X, Y, metric=metric) + assert_allclose(blockwise_distances, S, atol=1e-7) + + +@pytest.mark.parametrize("metric", ("euclidean", "l2", "sqeuclidean")) +def test_pairwise_distances_chunked_diagonal(metric, global_dtype): + rng = np.random.RandomState(0) + X = rng.normal(size=(1000, 10), scale=1e10).astype(global_dtype, copy=False) + chunks = list(pairwise_distances_chunked(X, working_memory=1, metric=metric)) + assert len(chunks) > 1 + assert_allclose(np.diag(np.vstack(chunks)), 0, rtol=1e-10) + + +@pytest.mark.parametrize("metric", ("euclidean", "l2", "sqeuclidean")) +def test_parallel_pairwise_distances_diagonal(metric, global_dtype): + rng = np.random.RandomState(0) + X = rng.normal(size=(1000, 10), scale=1e10).astype(global_dtype, copy=False) + distances = pairwise_distances(X, metric=metric, n_jobs=2) + assert_allclose(np.diag(distances), 0, atol=1e-10) + + +@pytest.mark.filterwarnings("ignore:Could not adhere to working_memory config") +def test_pairwise_distances_chunked(global_dtype): + # Test the pairwise_distance helper function. + rng = np.random.RandomState(0) + # Euclidean distance should be equivalent to calling the function. + X = rng.random_sample((200, 4)).astype(global_dtype, copy=False) + check_pairwise_distances_chunked(X, None, working_memory=1, metric="euclidean") + # Test small amounts of memory + for power in range(-16, 0): + check_pairwise_distances_chunked( + X, None, working_memory=2**power, metric="euclidean" + ) + # X as list + check_pairwise_distances_chunked( + X.tolist(), None, working_memory=1, metric="euclidean" + ) + # Euclidean distance, with Y != X. + Y = rng.random_sample((100, 4)).astype(global_dtype, copy=False) + check_pairwise_distances_chunked(X, Y, working_memory=1, metric="euclidean") + check_pairwise_distances_chunked( + X.tolist(), Y.tolist(), working_memory=1, metric="euclidean" + ) + # absurdly large working_memory + check_pairwise_distances_chunked(X, Y, working_memory=10000, metric="euclidean") + # "cityblock" uses scikit-learn metric, cityblock (function) is + # scipy.spatial. + check_pairwise_distances_chunked(X, Y, working_memory=1, metric="cityblock") + + # Test precomputed returns all at once + D = pairwise_distances(X) + gen = pairwise_distances_chunked(D, working_memory=2**-16, metric="precomputed") + assert isinstance(gen, GeneratorType) + assert next(gen) is D + with pytest.raises(StopIteration): + next(gen) + + +@pytest.mark.parametrize( + "x_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +@pytest.mark.parametrize( + "y_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances_known_result(x_array_constr, y_array_constr): + # Check the pairwise Euclidean distances computation on known result + X = x_array_constr([[0]]) + Y = y_array_constr([[1], [2]]) + D = euclidean_distances(X, Y) + assert_allclose(D, [[1.0, 2.0]]) + + +@pytest.mark.parametrize( + "y_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances_with_norms(global_dtype, y_array_constr): + # check that we still get the right answers with {X,Y}_norm_squared + # and that we get a wrong answer with wrong {X,Y}_norm_squared + rng = np.random.RandomState(0) + X = rng.random_sample((10, 10)).astype(global_dtype, copy=False) + Y = rng.random_sample((20, 10)).astype(global_dtype, copy=False) + + # norms will only be used if their dtype is float64 + X_norm_sq = (X.astype(np.float64) ** 2).sum(axis=1).reshape(1, -1) + Y_norm_sq = (Y.astype(np.float64) ** 2).sum(axis=1).reshape(1, -1) + + Y = y_array_constr(Y) + + D1 = euclidean_distances(X, Y) + D2 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq) + D3 = euclidean_distances(X, Y, Y_norm_squared=Y_norm_sq) + D4 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq, Y_norm_squared=Y_norm_sq) + assert_allclose(D2, D1) + assert_allclose(D3, D1) + assert_allclose(D4, D1) + + # check we get the wrong answer with wrong {X,Y}_norm_squared + wrong_D = euclidean_distances( + X, + Y, + X_norm_squared=np.zeros_like(X_norm_sq), + Y_norm_squared=np.zeros_like(Y_norm_sq), + ) + with pytest.raises(AssertionError): + assert_allclose(wrong_D, D1) + + +@pytest.mark.parametrize("symmetric", [True, False]) +def test_euclidean_distances_float32_norms(global_random_seed, symmetric): + # Non-regression test for #27621 + rng = np.random.RandomState(global_random_seed) + X = rng.random_sample((10, 10)) + Y = X if symmetric else rng.random_sample((20, 10)) + X_norm_sq = (X.astype(np.float32) ** 2).sum(axis=1).reshape(1, -1) + Y_norm_sq = (Y.astype(np.float32) ** 2).sum(axis=1).reshape(1, -1) + D1 = euclidean_distances(X, Y) + D2 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq) + D3 = euclidean_distances(X, Y, Y_norm_squared=Y_norm_sq) + D4 = euclidean_distances(X, Y, X_norm_squared=X_norm_sq, Y_norm_squared=Y_norm_sq) + assert_allclose(D2, D1) + assert_allclose(D3, D1) + assert_allclose(D4, D1) + + +def test_euclidean_distances_norm_shapes(): + # Check all accepted shapes for the norms or appropriate error messages. + rng = np.random.RandomState(0) + X = rng.random_sample((10, 10)) + Y = rng.random_sample((20, 10)) + + X_norm_squared = (X**2).sum(axis=1) + Y_norm_squared = (Y**2).sum(axis=1) + + D1 = euclidean_distances( + X, Y, X_norm_squared=X_norm_squared, Y_norm_squared=Y_norm_squared + ) + D2 = euclidean_distances( + X, + Y, + X_norm_squared=X_norm_squared.reshape(-1, 1), + Y_norm_squared=Y_norm_squared.reshape(-1, 1), + ) + D3 = euclidean_distances( + X, + Y, + X_norm_squared=X_norm_squared.reshape(1, -1), + Y_norm_squared=Y_norm_squared.reshape(1, -1), + ) + + assert_allclose(D2, D1) + assert_allclose(D3, D1) + + with pytest.raises(ValueError, match="Incompatible dimensions for X"): + euclidean_distances(X, Y, X_norm_squared=X_norm_squared[:5]) + with pytest.raises(ValueError, match="Incompatible dimensions for Y"): + euclidean_distances(X, Y, Y_norm_squared=Y_norm_squared[:5]) + + +@pytest.mark.parametrize( + "x_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +@pytest.mark.parametrize( + "y_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances(global_dtype, x_array_constr, y_array_constr): + # check that euclidean distances gives same result as scipy cdist + # when X and Y != X are provided + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)).astype(global_dtype, copy=False) + X[X < 0.8] = 0 + Y = rng.random_sample((10, 10)).astype(global_dtype, copy=False) + Y[Y < 0.8] = 0 + + expected = cdist(X, Y) + + X = x_array_constr(X) + Y = y_array_constr(Y) + distances = euclidean_distances(X, Y) + + # the default rtol=1e-7 is too close to the float32 precision + # and fails due to rounding errors. + assert_allclose(distances, expected, rtol=1e-6) + assert distances.dtype == global_dtype + + +@pytest.mark.parametrize( + "x_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances_sym(global_dtype, x_array_constr): + # check that euclidean distances gives same result as scipy pdist + # when only X is provided + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)).astype(global_dtype, copy=False) + X[X < 0.8] = 0 + + expected = squareform(pdist(X)) + + X = x_array_constr(X) + distances = euclidean_distances(X) + + # the default rtol=1e-7 is too close to the float32 precision + # and fails due to rounding errors. + assert_allclose(distances, expected, rtol=1e-6) + assert distances.dtype == global_dtype + + +@pytest.mark.parametrize("batch_size", [None, 5, 7, 101]) +@pytest.mark.parametrize( + "x_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +@pytest.mark.parametrize( + "y_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances_upcast(batch_size, x_array_constr, y_array_constr): + # check batches handling when Y != X (#13910) + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)).astype(np.float32) + X[X < 0.8] = 0 + Y = rng.random_sample((10, 10)).astype(np.float32) + Y[Y < 0.8] = 0 + + expected = cdist(X, Y) + + X = x_array_constr(X) + Y = y_array_constr(Y) + distances = _euclidean_distances_upcast(X, Y=Y, batch_size=batch_size) + distances = np.sqrt(np.maximum(distances, 0)) + + # the default rtol=1e-7 is too close to the float32 precision + # and fails due to rounding errors. + assert_allclose(distances, expected, rtol=1e-6) + + +@pytest.mark.parametrize("batch_size", [None, 5, 7, 101]) +@pytest.mark.parametrize( + "x_array_constr", + [np.array] + CSR_CONTAINERS, + ids=["dense"] + [container.__name__ for container in CSR_CONTAINERS], +) +def test_euclidean_distances_upcast_sym(batch_size, x_array_constr): + # check batches handling when X is Y (#13910) + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)).astype(np.float32) + X[X < 0.8] = 0 + + expected = squareform(pdist(X)) + + X = x_array_constr(X) + distances = _euclidean_distances_upcast(X, Y=X, batch_size=batch_size) + distances = np.sqrt(np.maximum(distances, 0)) + + # the default rtol=1e-7 is too close to the float32 precision + # and fails due to rounding errors. + assert_allclose(distances, expected, rtol=1e-6) + + +@pytest.mark.parametrize( + "dtype, eps, rtol", + [ + (np.float32, 1e-4, 1e-5), + pytest.param( + np.float64, + 1e-8, + 0.99, + marks=pytest.mark.xfail(reason="failing due to lack of precision"), + ), + ], +) +@pytest.mark.parametrize("dim", [1, 1000000]) +def test_euclidean_distances_extreme_values(dtype, eps, rtol, dim): + # check that euclidean distances is correct with float32 input thanks to + # upcasting. On float64 there are still precision issues. + X = np.array([[1.0] * dim], dtype=dtype) + Y = np.array([[1.0 + eps] * dim], dtype=dtype) + + distances = euclidean_distances(X, Y) + expected = cdist(X, Y) + + assert_allclose(distances, expected, rtol=1e-5) + + +@pytest.mark.parametrize("squared", [True, False]) +def test_nan_euclidean_distances_equal_to_euclidean_distance(squared): + # with no nan values + rng = np.random.RandomState(1337) + X = rng.randn(3, 4) + Y = rng.randn(4, 4) + + normal_distance = euclidean_distances(X, Y=Y, squared=squared) + nan_distance = nan_euclidean_distances(X, Y=Y, squared=squared) + assert_allclose(normal_distance, nan_distance) + + +@pytest.mark.parametrize("X", [np.array([[np.inf, 0]]), np.array([[0, -np.inf]])]) +@pytest.mark.parametrize("Y", [np.array([[np.inf, 0]]), np.array([[0, -np.inf]]), None]) +def test_nan_euclidean_distances_infinite_values(X, Y): + with pytest.raises(ValueError) as excinfo: + nan_euclidean_distances(X, Y=Y) + + exp_msg = "Input contains infinity or a value too large for dtype('float64')." + assert exp_msg == str(excinfo.value) + + +@pytest.mark.parametrize( + "X, X_diag, missing_value", + [ + (np.array([[0, 1], [1, 0]]), np.sqrt(2), np.nan), + (np.array([[0, 1], [1, np.nan]]), np.sqrt(2), np.nan), + (np.array([[np.nan, 1], [1, np.nan]]), np.nan, np.nan), + (np.array([[np.nan, 1], [np.nan, 0]]), np.sqrt(2), np.nan), + (np.array([[0, np.nan], [1, np.nan]]), np.sqrt(2), np.nan), + (np.array([[0, 1], [1, 0]]), np.sqrt(2), -1), + (np.array([[0, 1], [1, -1]]), np.sqrt(2), -1), + (np.array([[-1, 1], [1, -1]]), np.nan, -1), + (np.array([[-1, 1], [-1, 0]]), np.sqrt(2), -1), + (np.array([[0, -1], [1, -1]]), np.sqrt(2), -1), + ], +) +def test_nan_euclidean_distances_2x2(X, X_diag, missing_value): + exp_dist = np.array([[0.0, X_diag], [X_diag, 0]]) + + dist = nan_euclidean_distances(X, missing_values=missing_value) + assert_allclose(exp_dist, dist) + + dist_sq = nan_euclidean_distances(X, squared=True, missing_values=missing_value) + assert_allclose(exp_dist**2, dist_sq) + + dist_two = nan_euclidean_distances(X, X, missing_values=missing_value) + assert_allclose(exp_dist, dist_two) + + dist_two_copy = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) + assert_allclose(exp_dist, dist_two_copy) + + +@pytest.mark.parametrize("missing_value", [np.nan, -1]) +def test_nan_euclidean_distances_complete_nan(missing_value): + X = np.array([[missing_value, missing_value], [0, 1]]) + + exp_dist = np.array([[np.nan, np.nan], [np.nan, 0]]) + + dist = nan_euclidean_distances(X, missing_values=missing_value) + assert_allclose(exp_dist, dist) + + dist = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) + assert_allclose(exp_dist, dist) + + +@pytest.mark.parametrize("missing_value", [np.nan, -1]) +def test_nan_euclidean_distances_not_trival(missing_value): + X = np.array( + [ + [1.0, missing_value, 3.0, 4.0, 2.0], + [missing_value, 4.0, 6.0, 1.0, missing_value], + [3.0, missing_value, missing_value, missing_value, 1.0], + ] + ) + + Y = np.array( + [ + [missing_value, 7.0, 7.0, missing_value, 2.0], + [missing_value, missing_value, 5.0, 4.0, 7.0], + [missing_value, missing_value, missing_value, 4.0, 5.0], + ] + ) + + # Check for symmetry + D1 = nan_euclidean_distances(X, Y, missing_values=missing_value) + D2 = nan_euclidean_distances(Y, X, missing_values=missing_value) + + assert_almost_equal(D1, D2.T) + + # Check with explicit formula and squared=True + assert_allclose( + nan_euclidean_distances( + X[:1], Y[:1], squared=True, missing_values=missing_value + ), + [[5.0 / 2.0 * ((7 - 3) ** 2 + (2 - 2) ** 2)]], + ) + + # Check with explicit formula and squared=False + assert_allclose( + nan_euclidean_distances( + X[1:2], Y[1:2], squared=False, missing_values=missing_value + ), + [[np.sqrt(5.0 / 2.0 * ((6 - 5) ** 2 + (1 - 4) ** 2))]], + ) + + # Check when Y = X is explicitly passed + D3 = nan_euclidean_distances(X, missing_values=missing_value) + D4 = nan_euclidean_distances(X, X, missing_values=missing_value) + D5 = nan_euclidean_distances(X, X.copy(), missing_values=missing_value) + assert_allclose(D3, D4) + assert_allclose(D4, D5) + + # Check copy = True against copy = False + D6 = nan_euclidean_distances(X, Y, copy=True) + D7 = nan_euclidean_distances(X, Y, copy=False) + assert_allclose(D6, D7) + + +@pytest.mark.parametrize("missing_value", [np.nan, -1]) +def test_nan_euclidean_distances_one_feature_match_positive(missing_value): + # First feature is the only feature that is non-nan and in both + # samples. The result of `nan_euclidean_distances` with squared=True + # should be non-negative. The non-squared version should all be close to 0. + X = np.array( + [ + [-122.27, 648.0, missing_value, 37.85], + [-122.27, missing_value, 2.34701493, missing_value], + ] + ) + + dist_squared = nan_euclidean_distances( + X, missing_values=missing_value, squared=True + ) + assert np.all(dist_squared >= 0) + + dist = nan_euclidean_distances(X, missing_values=missing_value, squared=False) + assert_allclose(dist, 0.0) + + +def test_cosine_distances(): + # Check the pairwise Cosine distances computation + rng = np.random.RandomState(1337) + x = np.abs(rng.rand(910)) + XA = np.vstack([x, x]) + D = cosine_distances(XA) + assert_allclose(D, [[0.0, 0.0], [0.0, 0.0]], atol=1e-10) + # check that all elements are in [0, 2] + assert np.all(D >= 0.0) + assert np.all(D <= 2.0) + # check that diagonal elements are equal to 0 + assert_allclose(D[np.diag_indices_from(D)], [0.0, 0.0]) + + XB = np.vstack([x, -x]) + D2 = cosine_distances(XB) + # check that all elements are in [0, 2] + assert np.all(D2 >= 0.0) + assert np.all(D2 <= 2.0) + # check that diagonal elements are equal to 0 and non diagonal to 2 + assert_allclose(D2, [[0.0, 2.0], [2.0, 0.0]]) + + # check large random matrix + X = np.abs(rng.rand(1000, 5000)) + D = cosine_distances(X) + # check that diagonal elements are equal to 0 + assert_allclose(D[np.diag_indices_from(D)], [0.0] * D.shape[0]) + assert np.all(D >= 0.0) + assert np.all(D <= 2.0) + + +def test_haversine_distances(): + # Check haversine distance with distances computation + def slow_haversine_distances(x, y): + diff_lat = y[0] - x[0] + diff_lon = y[1] - x[1] + a = np.sin(diff_lat / 2) ** 2 + ( + np.cos(x[0]) * np.cos(y[0]) * np.sin(diff_lon / 2) ** 2 + ) + c = 2 * np.arcsin(np.sqrt(a)) + return c + + rng = np.random.RandomState(0) + X = rng.random_sample((5, 2)) + Y = rng.random_sample((10, 2)) + D1 = np.array([[slow_haversine_distances(x, y) for y in Y] for x in X]) + D2 = haversine_distances(X, Y) + assert_allclose(D1, D2) + # Test haversine distance does not accept X where n_feature != 2 + X = rng.random_sample((10, 3)) + err_msg = "Haversine distance only valid in 2 dimensions" + with pytest.raises(ValueError, match=err_msg): + haversine_distances(X) + + +# Paired distances + + +def test_paired_euclidean_distances(): + # Check the paired Euclidean distances computation + X = [[0], [0]] + Y = [[1], [2]] + D = paired_euclidean_distances(X, Y) + assert_allclose(D, [1.0, 2.0]) + + +def test_paired_manhattan_distances(): + # Check the paired manhattan distances computation + X = [[0], [0]] + Y = [[1], [2]] + D = paired_manhattan_distances(X, Y) + assert_allclose(D, [1.0, 2.0]) + + +def test_paired_cosine_distances(): + # Check the paired manhattan distances computation + X = [[0], [0]] + Y = [[1], [2]] + D = paired_cosine_distances(X, Y) + assert_allclose(D, [0.5, 0.5]) + + +def test_chi_square_kernel(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((10, 4)) + K_add = additive_chi2_kernel(X, Y) + gamma = 0.1 + K = chi2_kernel(X, Y, gamma=gamma) + assert K.dtype == float + for i, x in enumerate(X): + for j, y in enumerate(Y): + chi2 = -np.sum((x - y) ** 2 / (x + y)) + chi2_exp = np.exp(gamma * chi2) + assert_almost_equal(K_add[i, j], chi2) + assert_almost_equal(K[i, j], chi2_exp) + + # check diagonal is ones for data with itself + K = chi2_kernel(Y) + assert_array_equal(np.diag(K), 1) + # check off-diagonal is < 1 but > 0: + assert np.all(K > 0) + assert np.all(K - np.diag(np.diag(K)) < 1) + # check that float32 is preserved + X = rng.random_sample((5, 4)).astype(np.float32) + Y = rng.random_sample((10, 4)).astype(np.float32) + K = chi2_kernel(X, Y) + assert K.dtype == np.float32 + + # check integer type gets converted, + # check that zeros are handled + X = rng.random_sample((10, 4)).astype(np.int32) + K = chi2_kernel(X, X) + assert np.isfinite(K).all() + assert K.dtype == float + + # check that kernel of similar things is greater than dissimilar ones + X = [[0.3, 0.7], [1.0, 0]] + Y = [[0, 1], [0.9, 0.1]] + K = chi2_kernel(X, Y) + assert K[0, 0] > K[0, 1] + assert K[1, 1] > K[1, 0] + + # test negative input + with pytest.raises(ValueError): + chi2_kernel([[0, -1]]) + with pytest.raises(ValueError): + chi2_kernel([[0, -1]], [[-1, -1]]) + with pytest.raises(ValueError): + chi2_kernel([[0, 1]], [[-1, -1]]) + + # different n_features in X and Y + with pytest.raises(ValueError): + chi2_kernel([[0, 1]], [[0.2, 0.2, 0.6]]) + + +@pytest.mark.parametrize( + "kernel", + ( + linear_kernel, + polynomial_kernel, + rbf_kernel, + laplacian_kernel, + sigmoid_kernel, + cosine_similarity, + ), +) +def test_kernel_symmetry(kernel): + # Valid kernels should be symmetric + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + K = kernel(X, X) + assert_allclose(K, K.T, 15) + + +@pytest.mark.parametrize( + "kernel", + ( + linear_kernel, + polynomial_kernel, + rbf_kernel, + laplacian_kernel, + sigmoid_kernel, + cosine_similarity, + ), +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_kernel_sparse(kernel, csr_container): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + X_sparse = csr_container(X) + K = kernel(X, X) + K2 = kernel(X_sparse, X_sparse) + assert_allclose(K, K2) + + +def test_linear_kernel(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + K = linear_kernel(X, X) + # the diagonal elements of a linear kernel are their squared norm + assert_allclose(K.flat[::6], [linalg.norm(x) ** 2 for x in X]) + + +def test_rbf_kernel(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + K = rbf_kernel(X, X) + # the diagonal elements of a rbf kernel are 1 + assert_allclose(K.flat[::6], np.ones(5)) + + +def test_laplacian_kernel(): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + K = laplacian_kernel(X, X) + # the diagonal elements of a laplacian kernel are 1 + assert_allclose(np.diag(K), np.ones(5)) + + # off-diagonal elements are < 1 but > 0: + assert np.all(K > 0) + assert np.all(K - np.diag(np.diag(K)) < 1) + + +@pytest.mark.parametrize( + "metric, pairwise_func", + [("linear", linear_kernel), ("cosine", cosine_similarity)], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_similarity_sparse_output(metric, pairwise_func, csr_container): + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((3, 4)) + Xcsr = csr_container(X) + Ycsr = csr_container(Y) + + # should be sparse + K1 = pairwise_func(Xcsr, Ycsr, dense_output=False) + assert issparse(K1) + + # should be dense, and equal to K1 + K2 = pairwise_func(X, Y, dense_output=True) + assert not issparse(K2) + assert_allclose(K1.toarray(), K2) + + # show the kernel output equal to the sparse.toarray() + K3 = pairwise_kernels(X, Y=Y, metric=metric) + assert_allclose(K1.toarray(), K3) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_cosine_similarity(csr_container): + # Test the cosine_similarity. + + rng = np.random.RandomState(0) + X = rng.random_sample((5, 4)) + Y = rng.random_sample((3, 4)) + Xcsr = csr_container(X) + Ycsr = csr_container(Y) + + for X_, Y_ in ((X, None), (X, Y), (Xcsr, None), (Xcsr, Ycsr)): + # Test that the cosine is kernel is equal to a linear kernel when data + # has been previously normalized by L2-norm. + K1 = pairwise_kernels(X_, Y=Y_, metric="cosine") + X_ = normalize(X_) + if Y_ is not None: + Y_ = normalize(Y_) + K2 = pairwise_kernels(X_, Y=Y_, metric="linear") + assert_allclose(K1, K2) + + +def test_check_dense_matrices(): + # Ensure that pairwise array check works for dense matrices. + # Check that if XB is None, XB is returned as reference to XA + XA = np.resize(np.arange(40), (5, 8)) + XA_checked, XB_checked = check_pairwise_arrays(XA, None) + assert XA_checked is XB_checked + assert_array_equal(XA, XA_checked) + + +def test_check_XB_returned(): + # Ensure that if XA and XB are given correctly, they return as equal. + # Check that if XB is not None, it is returned equal. + # Note that the second dimension of XB is the same as XA. + XA = np.resize(np.arange(40), (5, 8)) + XB = np.resize(np.arange(32), (4, 8)) + XA_checked, XB_checked = check_pairwise_arrays(XA, XB) + assert_array_equal(XA, XA_checked) + assert_array_equal(XB, XB_checked) + + XB = np.resize(np.arange(40), (5, 8)) + XA_checked, XB_checked = check_paired_arrays(XA, XB) + assert_array_equal(XA, XA_checked) + assert_array_equal(XB, XB_checked) + + +def test_check_different_dimensions(): + # Ensure an error is raised if the dimensions are different. + XA = np.resize(np.arange(45), (5, 9)) + XB = np.resize(np.arange(32), (4, 8)) + with pytest.raises(ValueError): + check_pairwise_arrays(XA, XB) + + XB = np.resize(np.arange(4 * 9), (4, 9)) + with pytest.raises(ValueError): + check_paired_arrays(XA, XB) + + +def test_check_invalid_dimensions(): + # Ensure an error is raised on 1D input arrays. + # The modified tests are not 1D. In the old test, the array was internally + # converted to 2D anyways + XA = np.arange(45).reshape(9, 5) + XB = np.arange(32).reshape(4, 8) + with pytest.raises(ValueError): + check_pairwise_arrays(XA, XB) + XA = np.arange(45).reshape(9, 5) + XB = np.arange(32).reshape(4, 8) + with pytest.raises(ValueError): + check_pairwise_arrays(XA, XB) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_check_sparse_arrays(csr_container): + # Ensures that checks return valid sparse matrices. + rng = np.random.RandomState(0) + XA = rng.random_sample((5, 4)) + XA_sparse = csr_container(XA) + XB = rng.random_sample((5, 4)) + XB_sparse = csr_container(XB) + XA_checked, XB_checked = check_pairwise_arrays(XA_sparse, XB_sparse) + # compare their difference because testing csr matrices for + # equality with '==' does not work as expected. + assert issparse(XA_checked) + assert abs(XA_sparse - XA_checked).sum() == 0 + assert issparse(XB_checked) + assert abs(XB_sparse - XB_checked).sum() == 0 + + XA_checked, XA_2_checked = check_pairwise_arrays(XA_sparse, XA_sparse) + assert issparse(XA_checked) + assert abs(XA_sparse - XA_checked).sum() == 0 + assert issparse(XA_2_checked) + assert abs(XA_2_checked - XA_checked).sum() == 0 + + +def tuplify(X): + # Turns a numpy matrix (any n-dimensional array) into tuples. + s = X.shape + if len(s) > 1: + # Tuplify each sub-array in the input. + return tuple(tuplify(row) for row in X) + else: + # Single dimension input, just return tuple of contents. + return tuple(r for r in X) + + +def test_check_tuple_input(): + # Ensures that checks return valid tuples. + rng = np.random.RandomState(0) + XA = rng.random_sample((5, 4)) + XA_tuples = tuplify(XA) + XB = rng.random_sample((5, 4)) + XB_tuples = tuplify(XB) + XA_checked, XB_checked = check_pairwise_arrays(XA_tuples, XB_tuples) + assert_array_equal(XA_tuples, XA_checked) + assert_array_equal(XB_tuples, XB_checked) + + +def test_check_preserve_type(): + # Ensures that type float32 is preserved. + XA = np.resize(np.arange(40), (5, 8)).astype(np.float32) + XB = np.resize(np.arange(40), (5, 8)).astype(np.float32) + + XA_checked, XB_checked = check_pairwise_arrays(XA, None) + assert XA_checked.dtype == np.float32 + + # both float32 + XA_checked, XB_checked = check_pairwise_arrays(XA, XB) + assert XA_checked.dtype == np.float32 + assert XB_checked.dtype == np.float32 + + # mismatched A + XA_checked, XB_checked = check_pairwise_arrays(XA.astype(float), XB) + assert XA_checked.dtype == float + assert XB_checked.dtype == float + + # mismatched B + XA_checked, XB_checked = check_pairwise_arrays(XA, XB.astype(float)) + assert XA_checked.dtype == float + assert XB_checked.dtype == float + + +@pytest.mark.parametrize("n_jobs", [1, 2]) +@pytest.mark.parametrize("metric", ["seuclidean", "mahalanobis"]) +@pytest.mark.parametrize( + "dist_function", [pairwise_distances, pairwise_distances_chunked] +) +def test_pairwise_distances_data_derived_params(n_jobs, metric, dist_function): + # check that pairwise_distances give the same result in sequential and + # parallel, when metric has data-derived parameters. + with config_context(working_memory=0.1): # to have more than 1 chunk + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)) + + expected_dist = squareform(pdist(X, metric=metric)) + dist = np.vstack(tuple(dist_function(X, metric=metric, n_jobs=n_jobs))) + + assert_allclose(dist, expected_dist) + + +@pytest.mark.parametrize("metric", ["seuclidean", "mahalanobis"]) +def test_pairwise_distances_data_derived_params_error(metric): + # check that pairwise_distances raises an error when Y is passed but + # metric has data-derived params that are not provided by the user. + rng = np.random.RandomState(0) + X = rng.random_sample((100, 10)) + Y = rng.random_sample((100, 10)) + + with pytest.raises( + ValueError, + match=rf"The '(V|VI)' parameter is required for the {metric} metric", + ): + pairwise_distances(X, Y, metric=metric) + + +@pytest.mark.parametrize( + "metric", + [ + "braycurtis", + "canberra", + "chebyshev", + "correlation", + "hamming", + "mahalanobis", + "minkowski", + "seuclidean", + "sqeuclidean", + "cityblock", + "cosine", + "euclidean", + ], +) +@pytest.mark.parametrize("y_is_x", [True, False], ids=["Y is X", "Y is not X"]) +def test_numeric_pairwise_distances_datatypes(metric, global_dtype, y_is_x): + # Check that pairwise distances gives the same result as pdist and cdist + # regardless of input datatype when using any scipy metric for comparing + # numeric vectors + # + # This test is necessary because pairwise_distances used to throw an + # error when using metric='seuclidean' and the input data was not + # of type np.float64 (#15730) + + rng = np.random.RandomState(0) + + X = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + + params = {} + if y_is_x: + Y = X + expected_dist = squareform(pdist(X, metric=metric)) + else: + Y = rng.random_sample((5, 4)).astype(global_dtype, copy=False) + expected_dist = cdist(X, Y, metric=metric) + # precompute parameters for seuclidean & mahalanobis when x is not y + if metric == "seuclidean": + params = {"V": np.var(np.vstack([X, Y]), axis=0, ddof=1, dtype=np.float64)} + elif metric == "mahalanobis": + params = {"VI": np.linalg.inv(np.cov(np.vstack([X, Y]).T)).T} + + dist = pairwise_distances(X, Y, metric=metric, **params) + + assert_allclose(dist, expected_dist) + + +@pytest.mark.parametrize( + "pairwise_distances_func", + [pairwise_distances, pairwise_distances_argmin, pairwise_distances_argmin_min], +) +def test_nan_euclidean_support(pairwise_distances_func): + """Check that `nan_euclidean` is lenient with `nan` values.""" + + X = [[0, 1], [1, np.nan], [2, 3], [3, 5]] + output = pairwise_distances_func(X, X, metric="nan_euclidean") + + assert not np.isnan(output).any() + + +def test_nan_euclidean_constant_input_argmin(): + """Check that the behavior of constant input is the same in the case of + full of nan vector and full of zero vector. + """ + + X_nan = [[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan]] + argmin_nan = pairwise_distances_argmin(X_nan, X_nan, metric="nan_euclidean") + + X_const = [[0, 0], [0, 0], [0, 0]] + argmin_const = pairwise_distances_argmin(X_const, X_const, metric="nan_euclidean") + + assert_allclose(argmin_nan, argmin_const) + + +@pytest.mark.parametrize( + "X,Y,expected_distance", + [ + ( + ["a", "ab", "abc"], + None, + [[0.0, 1.0, 2.0], [1.0, 0.0, 1.0], [2.0, 1.0, 0.0]], + ), + ( + ["a", "ab", "abc"], + ["a", "ab"], + [[0.0, 1.0], [1.0, 0.0], [2.0, 1.0]], + ), + ], +) +def test_pairwise_dist_custom_metric_for_string(X, Y, expected_distance): + """Check pairwise_distances with lists of strings as input.""" + + def dummy_string_similarity(x, y): + return np.abs(len(x) - len(y)) + + actual_distance = pairwise_distances(X=X, Y=Y, metric=dummy_string_similarity) + assert_allclose(actual_distance, expected_distance) + + +def test_pairwise_dist_custom_metric_for_bool(): + """Check that pairwise_distances does not convert boolean input to float + when using a custom metric. + """ + + def dummy_bool_dist(v1, v2): + # dummy distance func using `&` and thus relying on the input data being boolean + return 1 - (v1 & v2).sum() / (v1 | v2).sum() + + X = np.array([[1, 0, 0, 0], [1, 0, 1, 0], [1, 1, 1, 1]], dtype=bool) + + expected_distance = np.array( + [ + [0.0, 0.5, 0.75], + [0.5, 0.0, 0.5], + [0.75, 0.5, 0.0], + ] + ) + + actual_distance = pairwise_distances(X=X, metric=dummy_bool_dist) + assert_allclose(actual_distance, expected_distance) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sparse_manhattan_readonly_dataset(csr_container): + # Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/7981 + matrices1 = [csr_container(np.ones((5, 5)))] + matrices2 = [csr_container(np.ones((5, 5)))] + # Joblib memory maps datasets which makes them read-only. + # The following call was reporting as failing in #7981, but this must pass. + Parallel(n_jobs=2, max_nbytes=0)( + delayed(manhattan_distances)(m1, m2) for m1, m2 in zip(matrices1, matrices2) + ) + + +# TODO(1.8): remove +def test_force_all_finite_rename_warning(): + X = np.random.uniform(size=(10, 10)) + Y = np.random.uniform(size=(10, 10)) + + msg = "'force_all_finite' was renamed to 'ensure_all_finite'" + + with pytest.warns(FutureWarning, match=msg): + check_pairwise_arrays(X, Y, force_all_finite=True) + + with pytest.warns(FutureWarning, match=msg): + pairwise_distances(X, Y, force_all_finite=True) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..0ea6d5d094d5602ce4e3d4161b398d42c65677e6 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py @@ -0,0 +1,1643 @@ +import itertools +import re +import warnings +from functools import partial + +import numpy as np +import pytest +from scipy.spatial.distance import cdist + +from sklearn.metrics import euclidean_distances, pairwise_distances +from sklearn.metrics._pairwise_distances_reduction import ( + ArgKmin, + ArgKminClassMode, + BaseDistancesReductionDispatcher, + RadiusNeighbors, + RadiusNeighborsClassMode, + sqeuclidean_row_norms, +) +from sklearn.utils._testing import ( + assert_allclose, + assert_array_equal, + create_memmap_backed_data, +) +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.parallel import _get_threadpool_controller + +# Common supported metric between scipy.spatial.distance.cdist +# and BaseDistanceReductionDispatcher. +# This allows constructing tests to check consistency of results +# of concrete BaseDistanceReductionDispatcher on some metrics using APIs +# from scipy and numpy. +CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS = [ + "braycurtis", + "canberra", + "chebyshev", + "cityblock", + "euclidean", + "minkowski", + "seuclidean", +] + + +def _get_metric_params_list(metric: str, n_features: int, seed: int = 1): + """Return list of dummy DistanceMetric kwargs for tests.""" + + # Distinguishing on cases not to compute unneeded datastructures. + rng = np.random.RandomState(seed) + + if metric == "minkowski": + minkowski_kwargs = [ + dict(p=1.5), + dict(p=2), + dict(p=3), + dict(p=np.inf), + dict(p=3, w=rng.rand(n_features)), + ] + + return minkowski_kwargs + + if metric == "seuclidean": + return [dict(V=rng.rand(n_features))] + + # Case of: "euclidean", "manhattan", "chebyshev", "haversine" or any other metric. + # In those cases, no kwargs is needed. + return [{}] + + +def assert_same_distances_for_common_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + rtol, + atol, +): + """Check that the distances of common neighbors are equal up to tolerance. + + This does not check if there are missing neighbors in either result set. + Missingness is handled by assert_no_missing_neighbors. + """ + # Compute a mapping from indices to distances for each result set and + # check that the computed neighbors with matching indices are within + # the expected distance tolerance. + indices_to_dist_a = dict(zip(indices_row_a, dist_row_a)) + indices_to_dist_b = dict(zip(indices_row_b, dist_row_b)) + + common_indices = set(indices_row_a).intersection(set(indices_row_b)) + for idx in common_indices: + dist_a = indices_to_dist_a[idx] + dist_b = indices_to_dist_b[idx] + try: + assert_allclose(dist_a, dist_b, rtol=rtol, atol=atol) + except AssertionError as e: + # Wrap exception to provide more context while also including + # the original exception with the computed absolute and + # relative differences. + raise AssertionError( + f"Query vector with index {query_idx} lead to different distances" + f" for common neighbor with index {idx}:" + f" dist_a={dist_a} vs dist_b={dist_b} (with atol={atol} and" + f" rtol={rtol})" + ) from e + + +def assert_no_missing_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + threshold, +): + """Compare the indices of neighbors in two results sets. + + Any neighbor index with a distance below the precision threshold should + match one in the other result set. We ignore the last few neighbors beyond + the threshold as those can typically be missing due to rounding errors. + + For radius queries, the threshold is just the radius minus the expected + precision level. + + For k-NN queries, it is the maximum distance to the k-th neighbor minus the + expected precision level. + """ + mask_a = dist_row_a < threshold + mask_b = dist_row_b < threshold + missing_from_b = np.setdiff1d(indices_row_a[mask_a], indices_row_b) + missing_from_a = np.setdiff1d(indices_row_b[mask_b], indices_row_a) + if len(missing_from_a) > 0 or len(missing_from_b) > 0: + raise AssertionError( + f"Query vector with index {query_idx} lead to mismatched result indices:\n" + f"neighbors in b missing from a: {missing_from_a}\n" + f"neighbors in a missing from b: {missing_from_b}\n" + f"dist_row_a={dist_row_a}\n" + f"dist_row_b={dist_row_b}\n" + f"indices_row_a={indices_row_a}\n" + f"indices_row_b={indices_row_b}\n" + ) + + +def assert_compatible_argkmin_results( + neighbors_dists_a, + neighbors_dists_b, + neighbors_indices_a, + neighbors_indices_b, + rtol=1e-5, + atol=1e-6, +): + """Assert that argkmin results are valid up to rounding errors. + + This function asserts that the results of argkmin queries are valid up to: + - rounding error tolerance on distance values; + - permutations of indices for distances values that differ up to the + expected precision level. + + Furthermore, the distances must be sorted. + + To be used for testing neighbors queries on float32 datasets: we accept + neighbors rank swaps only if they are caused by small rounding errors on + the distance computations. + """ + is_sorted = lambda a: np.all(a[:-1] <= a[1:]) + + assert ( + neighbors_dists_a.shape + == neighbors_dists_b.shape + == neighbors_indices_a.shape + == neighbors_indices_b.shape + ), "Arrays of results have incompatible shapes." + + n_queries, _ = neighbors_dists_a.shape + + # Asserting equality results one row at a time + for query_idx in range(n_queries): + dist_row_a = neighbors_dists_a[query_idx] + dist_row_b = neighbors_dists_b[query_idx] + indices_row_a = neighbors_indices_a[query_idx] + indices_row_b = neighbors_indices_b[query_idx] + + assert is_sorted(dist_row_a), f"Distances aren't sorted on row {query_idx}" + assert is_sorted(dist_row_b), f"Distances aren't sorted on row {query_idx}" + + assert_same_distances_for_common_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + rtol, + atol, + ) + + # Check that any neighbor with distances below the rounding error + # threshold have matching indices. The threshold is the distance to the + # k-th neighbors minus the expected precision level: + # + # (1 - rtol) * dist_k - atol + # + # Where dist_k is defined as the maximum distance to the kth-neighbor + # among the two result sets. This way of defining the threshold is + # stricter than taking the minimum of the two. + threshold = (1 - rtol) * np.maximum( + np.max(dist_row_a), np.max(dist_row_b) + ) - atol + assert_no_missing_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + threshold, + ) + + +def _non_trivial_radius( + *, + X=None, + Y=None, + metric=None, + precomputed_dists=None, + expected_n_neighbors=10, + n_subsampled_queries=10, + **metric_kwargs, +): + # Find a non-trivial radius using a small subsample of the pairwise + # distances between X and Y: we want to return around expected_n_neighbors + # on average. Yielding too many results would make the test slow (because + # checking the results is expensive for large result sets), yielding 0 most + # of the time would make the test useless. + assert precomputed_dists is not None or metric is not None, ( + "Either metric or precomputed_dists must be provided." + ) + + if precomputed_dists is None: + assert X is not None + assert Y is not None + sampled_dists = pairwise_distances(X, Y, metric=metric, **metric_kwargs) + else: + sampled_dists = precomputed_dists[:n_subsampled_queries].copy() + sampled_dists.sort(axis=1) + return sampled_dists[:, expected_n_neighbors].mean() + + +def assert_compatible_radius_results( + neighbors_dists_a, + neighbors_dists_b, + neighbors_indices_a, + neighbors_indices_b, + radius, + check_sorted=True, + rtol=1e-5, + atol=1e-6, +): + """Assert that radius neighborhood results are valid up to: + + - relative and absolute tolerance on computed distance values + - permutations of indices for distances values that differ up to + a precision level + - missing or extra last elements if their distance is + close to the radius + + To be used for testing neighbors queries on float32 datasets: we + accept neighbors rank swaps only if they are caused by small + rounding errors on the distance computations. + + Input arrays must be sorted w.r.t distances. + """ + is_sorted = lambda a: np.all(a[:-1] <= a[1:]) + + assert ( + len(neighbors_dists_a) + == len(neighbors_dists_b) + == len(neighbors_indices_a) + == len(neighbors_indices_b) + ) + + n_queries = len(neighbors_dists_a) + + # Asserting equality of results one vector at a time + for query_idx in range(n_queries): + dist_row_a = neighbors_dists_a[query_idx] + dist_row_b = neighbors_dists_b[query_idx] + indices_row_a = neighbors_indices_a[query_idx] + indices_row_b = neighbors_indices_b[query_idx] + + if check_sorted: + assert is_sorted(dist_row_a), f"Distances aren't sorted on row {query_idx}" + assert is_sorted(dist_row_b), f"Distances aren't sorted on row {query_idx}" + + assert len(dist_row_a) == len(indices_row_a) + assert len(dist_row_b) == len(indices_row_b) + + # Check that all distances are within the requested radius + if len(dist_row_a) > 0: + max_dist_a = np.max(dist_row_a) + assert max_dist_a <= radius, ( + f"Largest returned distance {max_dist_a} not within requested" + f" radius {radius} on row {query_idx}" + ) + if len(dist_row_b) > 0: + max_dist_b = np.max(dist_row_b) + assert max_dist_b <= radius, ( + f"Largest returned distance {max_dist_b} not within requested" + f" radius {radius} on row {query_idx}" + ) + + assert_same_distances_for_common_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + rtol, + atol, + ) + + threshold = (1 - rtol) * radius - atol + assert_no_missing_neighbors( + query_idx, + dist_row_a, + dist_row_b, + indices_row_a, + indices_row_b, + threshold, + ) + + +FLOAT32_TOLS = { + "atol": 1e-7, + "rtol": 1e-5, +} +FLOAT64_TOLS = { + "atol": 1e-9, + "rtol": 1e-7, +} +ASSERT_RESULT = { + (ArgKmin, np.float64): partial(assert_compatible_argkmin_results, **FLOAT64_TOLS), + (ArgKmin, np.float32): partial(assert_compatible_argkmin_results, **FLOAT32_TOLS), + ( + RadiusNeighbors, + np.float64, + ): partial(assert_compatible_radius_results, **FLOAT64_TOLS), + ( + RadiusNeighbors, + np.float32, + ): partial(assert_compatible_radius_results, **FLOAT32_TOLS), +} + + +def test_assert_compatible_argkmin_results(): + atol = 1e-7 + rtol = 0.0 + tols = dict(atol=atol, rtol=rtol) + + eps = atol / 3 + _1m = 1.0 - eps + _1p = 1.0 + eps + + _6_1m = 6.1 - eps + _6_1p = 6.1 + eps + + ref_dist = np.array( + [ + [1.2, 2.5, _6_1m, 6.1, _6_1p], + [_1m, _1m, 1, _1p, _1p], + ] + ) + ref_indices = np.array( + [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + ] + ) + + # Sanity check: compare the reference results to themselves. + assert_compatible_argkmin_results( + ref_dist, ref_dist, ref_indices, ref_indices, rtol + ) + + # Apply valid permutation on indices: the last 3 points are all very close + # to one another so we accept any permutation on their rankings. + assert_compatible_argkmin_results( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[1, 2, 5, 4, 3]]), + **tols, + ) + + # The last few indices do not necessarily have to match because of the rounding + # errors on the distances: there could be tied results at the boundary. + assert_compatible_argkmin_results( + np.array([[1.2, 2.5, 3.0, 6.1, _6_1p]]), + np.array([[1.2, 2.5, 3.0, _6_1m, 6.1]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[1, 2, 3, 6, 7]]), + **tols, + ) + + # All points have close distances so any ranking permutation + # is valid for this query result. + assert_compatible_argkmin_results( + np.array([[_1m, 1, _1p, _1p, _1p]]), + np.array([[1, 1, 1, 1, _1p]]), + np.array([[7, 6, 8, 10, 9]]), + np.array([[6, 9, 7, 8, 10]]), + **tols, + ) + + # They could also be nearly truncation of very large nearly tied result + # sets hence all indices can also be distinct in this case: + assert_compatible_argkmin_results( + np.array([[_1m, 1, _1p, _1p, _1p]]), + np.array([[_1m, 1, 1, 1, _1p]]), + np.array([[34, 30, 8, 12, 24]]), + np.array([[42, 1, 21, 13, 3]]), + **tols, + ) + + # Apply invalid permutation on indices: permuting the ranks of the 2 + # nearest neighbors is invalid because the distance values are too + # different. + msg = re.escape( + "Query vector with index 0 lead to different distances for common neighbor with" + " index 1: dist_a=1.2 vs dist_b=2.5" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_argkmin_results( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 3, 4, 5]]), + **tols, + ) + + # Detect missing indices within the expected precision level, even when the + # distances match exactly. + msg = re.escape( + "neighbors in b missing from a: [12]\nneighbors in a missing from b: [1]" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_argkmin_results( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[12, 2, 4, 11, 3]]), + **tols, + ) + + # Detect missing indices outside the expected precision level. + msg = re.escape( + "neighbors in b missing from a: []\nneighbors in a missing from b: [3]" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_argkmin_results( + np.array([[_1m, 1.0, _6_1m, 6.1, _6_1p]]), + np.array([[1.0, 1.0, _6_1m, 6.1, 7]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 4, 5, 12]]), + **tols, + ) + + # Detect missing indices outside the expected precision level, in the other + # direction: + msg = re.escape( + "neighbors in b missing from a: [5]\nneighbors in a missing from b: []" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_argkmin_results( + np.array([[_1m, 1.0, _6_1m, 6.1, 7]]), + np.array([[1.0, 1.0, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 12]]), + np.array([[2, 1, 5, 3, 4]]), + **tols, + ) + + # Distances aren't properly sorted + msg = "Distances aren't sorted on row 0" + with pytest.raises(AssertionError, match=msg): + assert_compatible_argkmin_results( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[2.5, 1.2, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 4, 5, 3]]), + **tols, + ) + + +@pytest.mark.parametrize("check_sorted", [True, False]) +def test_assert_compatible_radius_results(check_sorted): + atol = 1e-7 + rtol = 0.0 + tols = dict(atol=atol, rtol=rtol) + + eps = atol / 3 + _1m = 1.0 - eps + _1p = 1.0 + eps + _6_1m = 6.1 - eps + _6_1p = 6.1 + eps + + ref_dist = [ + np.array([1.2, 2.5, _6_1m, 6.1, _6_1p]), + np.array([_1m, 1, _1p, _1p]), + ] + + ref_indices = [ + np.array([1, 2, 3, 4, 5]), + np.array([6, 7, 8, 9]), + ] + + # Sanity check: compare the reference results to themselves. + assert_compatible_radius_results( + ref_dist, + ref_dist, + ref_indices, + ref_indices, + radius=7.0, + check_sorted=check_sorted, + **tols, + ) + + # Apply valid permutation on indices + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([1, 2, 4, 5, 3])]), + radius=7.0, + check_sorted=check_sorted, + **tols, + ) + assert_compatible_radius_results( + np.array([np.array([_1m, _1m, 1, _1p, _1p])]), + np.array([np.array([_1m, _1m, 1, _1p, _1p])]), + np.array([np.array([6, 7, 8, 9, 10])]), + np.array([np.array([6, 9, 7, 8, 10])]), + radius=7.0, + check_sorted=check_sorted, + **tols, + ) + + # Apply invalid permutation on indices + msg = re.escape( + "Query vector with index 0 lead to different distances for common neighbor with" + " index 1: dist_a=1.2 vs dist_b=2.5" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 3, 4, 5])]), + radius=7.0, + check_sorted=check_sorted, + **tols, + ) + + # Having extra last or missing elements is valid if they are in the + # tolerated rounding error range: [(1 - rtol) * radius - atol, radius] + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1])]), + np.array([np.array([1, 2, 3, 4, 5, 7])]), + np.array([np.array([1, 2, 3, 6])]), + radius=_6_1p, + check_sorted=check_sorted, + **tols, + ) + + # Any discrepancy outside the tolerated rounding error range is invalid and + # indicates a missing neighbor in one of the result sets. + msg = re.escape( + "Query vector with index 0 lead to mismatched result indices:\nneighbors in b" + " missing from a: []\nneighbors in a missing from b: [3]" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, 6])]), + np.array([np.array([1.2, 2.5])]), + np.array([np.array([1, 2, 3])]), + np.array([np.array([1, 2])]), + radius=6.1, + check_sorted=check_sorted, + **tols, + ) + msg = re.escape( + "Query vector with index 0 lead to mismatched result indices:\nneighbors in b" + " missing from a: [4]\nneighbors in a missing from b: [2]" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.1, 2.5])]), + np.array([np.array([1.2, 2, 2.5])]), + np.array([np.array([1, 2, 3])]), + np.array([np.array([1, 4, 3])]), + radius=6.1, + check_sorted=check_sorted, + **tols, + ) + + # Radius upper bound is strictly checked + msg = re.escape( + "Largest returned distance 6.100000033333333 not within requested radius 6.1 on" + " row 0" + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, 6.1])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=6.1, + check_sorted=check_sorted, + **tols, + ) + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, 6.1])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=6.1, + check_sorted=check_sorted, + **tols, + ) + + if check_sorted: + # Distances aren't properly sorted + msg = "Distances aren't sorted on row 0" + with pytest.raises(AssertionError, match=msg): + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([2.5, 1.2, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=_6_1p, + check_sorted=True, + **tols, + ) + else: + assert_compatible_radius_results( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([2.5, 1.2, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=_6_1p, + check_sorted=False, + **tols, + ) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_distances_reduction_is_usable_for(csr_container): + rng = np.random.RandomState(0) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + X_csr = csr_container(X) + Y_csr = csr_container(Y) + metric = "manhattan" + + # Must be usable for all possible pair of {dense, sparse} datasets + assert BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y_csr, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X, Y_csr, metric) + + assert BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float64), Y.astype(np.float64), metric + ) + + assert BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float32), Y.astype(np.float32), metric + ) + + assert not BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.int64), Y.astype(np.int64), metric + ) + + assert not BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric="pyfunc") + assert not BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float32), Y, metric + ) + assert not BaseDistancesReductionDispatcher.is_usable_for( + X, Y.astype(np.int32), metric + ) + + # F-ordered arrays are not supported + assert not BaseDistancesReductionDispatcher.is_usable_for( + np.asfortranarray(X), Y, metric + ) + + assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y, metric="euclidean") + assert BaseDistancesReductionDispatcher.is_usable_for( + X, Y_csr, metric="sqeuclidean" + ) + + # FIXME: the current Cython implementation is too slow for a large number of + # features. We temporarily disable it to fallback on SciPy's implementation. + # See: https://github.com/scikit-learn/scikit-learn/issues/28191 + assert not BaseDistancesReductionDispatcher.is_usable_for( + X_csr, Y_csr, metric="sqeuclidean" + ) + assert not BaseDistancesReductionDispatcher.is_usable_for( + X_csr, Y_csr, metric="euclidean" + ) + + # CSR matrices without non-zeros elements aren't currently supported + # TODO: support CSR matrices without non-zeros elements + X_csr_0_nnz = csr_container(X * 0) + assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_0_nnz, Y, metric) + + # CSR matrices with int64 indices and indptr (e.g. large nnz, or large n_features) + # aren't supported as of now. + # See: https://github.com/scikit-learn/scikit-learn/issues/23653 + # TODO: support CSR matrices with int64 indices and indptr + X_csr_int64 = csr_container(X) + X_csr_int64.indices = X_csr_int64.indices.astype(np.int64) + assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_int64, Y, metric) + + +def test_argkmin_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + k = 5 + metric = "euclidean" + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises(ValueError, match=msg): + ArgKmin.compute(X=X.astype(np.float32), Y=Y, k=k, metric=metric) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises(ValueError, match=msg): + ArgKmin.compute(X=X, Y=Y.astype(np.int32), k=k, metric=metric) + + with pytest.raises(ValueError, match="k == -1, must be >= 1."): + ArgKmin.compute(X=X, Y=Y, k=-1, metric=metric) + + with pytest.raises(ValueError, match="k == 0, must be >= 1."): + ArgKmin.compute(X=X, Y=Y, k=0, metric=metric) + + with pytest.raises(ValueError, match="Unrecognized metric"): + ArgKmin.compute(X=X, Y=Y, k=k, metric="wrong metric") + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + ArgKmin.compute(X=np.array([1.0, 2.0]), Y=Y, k=k, metric=metric) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + ArgKmin.compute(X=np.asfortranarray(X), Y=Y, k=k, metric=metric) + + # A UserWarning must be raised in this case. + unused_metric_kwargs = {"p": 3} + + message = r"Some metric_kwargs have been passed \({'p': 3}\) but" + + with pytest.warns(UserWarning, match=message): + ArgKmin.compute( + X=X, Y=Y, k=k, metric=metric, metric_kwargs=unused_metric_kwargs + ) + + # A UserWarning must be raised in this case. + metric_kwargs = { + "p": 3, # unused + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + + message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'" + + with pytest.warns(UserWarning, match=message): + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + +def test_argkmin_classmode_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + k = 5 + metric = "manhattan" + + weights = "uniform" + Y_labels = rng.randint(low=0, high=10, size=100) + unique_Y_labels = np.unique(Y_labels) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises(ValueError, match=msg): + ArgKminClassMode.compute( + X=X.astype(np.float32), + Y=Y, + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises(ValueError, match=msg): + ArgKminClassMode.compute( + X=X, + Y=Y.astype(np.int32), + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + with pytest.raises(ValueError, match="k == -1, must be >= 1."): + ArgKminClassMode.compute( + X=X, + Y=Y, + k=-1, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + with pytest.raises(ValueError, match="k == 0, must be >= 1."): + ArgKminClassMode.compute( + X=X, + Y=Y, + k=0, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + with pytest.raises(ValueError, match="Unrecognized metric"): + ArgKminClassMode.compute( + X=X, + Y=Y, + k=k, + metric="wrong metric", + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + ArgKminClassMode.compute( + X=np.array([1.0, 2.0]), + Y=Y, + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + ArgKminClassMode.compute( + X=np.asfortranarray(X), + Y=Y, + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + non_existent_weights_strategy = "non_existent_weights_strategy" + message = ( + "Only the 'uniform' or 'distance' weights options are supported at this time. " + f"Got: weights='{non_existent_weights_strategy}'." + ) + with pytest.raises(ValueError, match=message): + ArgKminClassMode.compute( + X=X, + Y=Y, + k=k, + metric=metric, + weights=non_existent_weights_strategy, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + ) + + # TODO: introduce assertions on UserWarnings once the Euclidean specialisation + # of ArgKminClassMode is supported. + + +def test_radius_neighbors_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + radius = 5 + metric = "euclidean" + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises( + ValueError, + match=msg, + ): + RadiusNeighbors.compute( + X=X.astype(np.float32), Y=Y, radius=radius, metric=metric + ) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises( + ValueError, + match=msg, + ): + RadiusNeighbors.compute(X=X, Y=Y.astype(np.int32), radius=radius, metric=metric) + + with pytest.raises(ValueError, match="radius == -1.0, must be >= 0."): + RadiusNeighbors.compute(X=X, Y=Y, radius=-1, metric=metric) + + with pytest.raises(ValueError, match="Unrecognized metric"): + RadiusNeighbors.compute(X=X, Y=Y, radius=radius, metric="wrong metric") + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + RadiusNeighbors.compute( + X=np.array([1.0, 2.0]), Y=Y, radius=radius, metric=metric + ) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + RadiusNeighbors.compute( + X=np.asfortranarray(X), Y=Y, radius=radius, metric=metric + ) + + unused_metric_kwargs = {"p": 3} + + # A UserWarning must be raised in this case. + message = r"Some metric_kwargs have been passed \({'p': 3}\) but" + + with pytest.warns(UserWarning, match=message): + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=unused_metric_kwargs + ) + + # A UserWarning must be raised in this case. + metric_kwargs = { + "p": 3, # unused + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + + message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'" + + with pytest.warns(UserWarning, match=message): + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + +def test_radius_neighbors_classmode_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + radius = 5 + metric = "manhattan" + weights = "uniform" + Y_labels = rng.randint(low=0, high=10, size=100) + unique_Y_labels = np.unique(Y_labels) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises(ValueError, match=msg): + RadiusNeighborsClassMode.compute( + X=X.astype(np.float32), + Y=Y, + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises(ValueError, match=msg): + RadiusNeighborsClassMode.compute( + X=X, + Y=Y.astype(np.int32), + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + with pytest.raises(ValueError, match="radius == -1.0, must be >= 0."): + RadiusNeighborsClassMode.compute( + X=X, + Y=Y, + radius=-1, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + with pytest.raises(ValueError, match="Unrecognized metric"): + RadiusNeighborsClassMode.compute( + X=X, + Y=Y, + radius=-1, + metric="wrong_metric", + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + RadiusNeighborsClassMode.compute( + X=np.array([1.0, 2.0]), + Y=Y, + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + RadiusNeighborsClassMode.compute( + X=np.asfortranarray(X), + Y=Y, + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + non_existent_weights_strategy = "non_existent_weights_strategy" + msg = ( + "Only the 'uniform' or 'distance' weights options are supported at this time. " + f"Got: weights='{non_existent_weights_strategy}'." + ) + with pytest.raises(ValueError, match=msg): + RadiusNeighborsClassMode.compute( + X=X, + Y=Y, + radius=radius, + metric="wrong_metric", + weights=non_existent_weights_strategy, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=None, + ) + + +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_chunk_size_agnosticism( + global_random_seed, + Dispatcher, + dtype, + n_features=100, +): + """Check that results do not depend on the chunk size.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=False) + X = rng.rand(n_samples_X, n_features).astype(dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + radius = _non_trivial_radius(X=X, Y=Y, metric="euclidean") + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=256, # default + metric="manhattan", + return_distance=True, + **compute_parameters, + ) + + dist, indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=41, + metric="manhattan", + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist, ref_indices, indices, **check_parameters + ) + + +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_n_threads_agnosticism( + global_random_seed, + Dispatcher, + dtype, + n_features=100, +): + """Check that results do not depend on the number of threads.""" + rng = np.random.RandomState(global_random_seed) + n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=False) + spread = 100 + X = rng.rand(n_samples_X, n_features).astype(dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + radius = _non_trivial_radius(X=X, Y=Y, metric="euclidean") + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=25, # make sure we use multiple threads + return_distance=True, + **compute_parameters, + ) + + with _get_threadpool_controller().limit(limits=1, user_api="openmp"): + dist, indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=25, + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist, ref_indices, indices, **check_parameters + ) + + +@pytest.mark.parametrize( + "Dispatcher, dtype", + [ + (ArgKmin, np.float64), + (RadiusNeighbors, np.float32), + (ArgKmin, np.float32), + (RadiusNeighbors, np.float64), + ], +) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_format_agnosticism( + global_random_seed, + Dispatcher, + dtype, + csr_container, +): + """Check that results do not depend on the format (dense, sparse) of the input.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + n_samples, n_features = 100, 100 + + X = rng.rand(n_samples, n_features).astype(dtype) * spread + Y = rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_container(X) + Y_csr = csr_container(Y) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Adjusting the radius to ensure that the expected results is neither + # trivially empty nor too large. + radius = _non_trivial_radius(X=X, Y=Y, metric="euclidean") + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + dist_dense, indices_dense = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=50, + return_distance=True, + **compute_parameters, + ) + + for _X, _Y in itertools.product((X, X_csr), (Y, Y_csr)): + if _X is X and _Y is Y: + continue + dist, indices = Dispatcher.compute( + _X, + _Y, + parameter, + chunk_size=50, + return_distance=True, + **compute_parameters, + ) + ASSERT_RESULT[(Dispatcher, dtype)]( + dist_dense, + dist, + indices_dense, + indices, + **check_parameters, + ) + + +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +def test_strategies_consistency( + global_random_seed, + global_dtype, + Dispatcher, + n_features=10, +): + """Check that the results do not depend on the strategy used.""" + rng = np.random.RandomState(global_random_seed) + metric = rng.choice( + np.array( + [ + "euclidean", + "minkowski", + "manhattan", + "haversine", + ], + dtype=object, + ) + ) + n_samples_X, n_samples_Y = rng.choice([97, 100, 101, 500], size=2, replace=False) + spread = 100 + X = rng.rand(n_samples_X, n_features).astype(global_dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(global_dtype) * spread + + # Haversine distance only accepts 2D data + if metric == "haversine": + X = np.ascontiguousarray(X[:, :2]) + Y = np.ascontiguousarray(Y[:, :2]) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + radius = _non_trivial_radius(X=X, Y=Y, metric=metric) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + dist_par_X, indices_par_X = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + # Taking the first + metric_kwargs=_get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0], + # To be sure to use parallelization + chunk_size=n_samples_X // 4, + strategy="parallel_on_X", + return_distance=True, + **compute_parameters, + ) + + dist_par_Y, indices_par_Y = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + # Taking the first + metric_kwargs=_get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0], + # To be sure to use parallelization + chunk_size=n_samples_Y // 4, + strategy="parallel_on_Y", + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, global_dtype)]( + dist_par_X, dist_par_Y, indices_par_X, indices_par_Y, **check_parameters + ) + + +# "Concrete Dispatchers"-specific tests + + +@pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS) +@pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y")) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_pairwise_distances_argkmin( + global_random_seed, + metric, + strategy, + dtype, + csr_container, + n_queries=5, + n_samples=100, + k=10, +): + rng = np.random.RandomState(global_random_seed) + n_features = rng.choice([50, 500]) + translation = rng.choice([0, 1e6]) + spread = 1000 + X = translation + rng.rand(n_queries, n_features).astype(dtype) * spread + Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_container(X) + Y_csr = csr_container(Y) + + # Haversine distance only accepts 2D data + if metric == "haversine": + X = np.ascontiguousarray(X[:, :2]) + Y = np.ascontiguousarray(Y[:, :2]) + + metric_kwargs = _get_metric_params_list(metric, n_features)[0] + + # Reference for argkmin results + if metric == "euclidean": + # Compare to scikit-learn GEMM optimized implementation + dist_matrix = euclidean_distances(X, Y) + else: + dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs) + # Taking argkmin (indices of the k smallest values) + argkmin_indices_ref = np.argsort(dist_matrix, axis=1)[:, :k] + # Getting the associated distances + argkmin_distances_ref = np.zeros(argkmin_indices_ref.shape, dtype=np.float64) + for row_idx in range(argkmin_indices_ref.shape[0]): + argkmin_distances_ref[row_idx] = dist_matrix[ + row_idx, argkmin_indices_ref[row_idx] + ] + + for _X, _Y in itertools.product((X, X_csr), (Y, Y_csr)): + argkmin_distances, argkmin_indices = ArgKmin.compute( + _X, + _Y, + k, + metric=metric, + metric_kwargs=metric_kwargs, + return_distance=True, + # So as to have more than a chunk, forcing parallelism. + chunk_size=n_samples // 4, + strategy=strategy, + ) + + ASSERT_RESULT[(ArgKmin, dtype)]( + argkmin_distances, + argkmin_distances_ref, + argkmin_indices, + argkmin_indices_ref, + ) + + +@pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS) +@pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y")) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_pairwise_distances_radius_neighbors( + global_random_seed, + metric, + strategy, + dtype, + n_queries=5, + n_samples=100, +): + rng = np.random.RandomState(global_random_seed) + n_features = rng.choice([50, 500]) + translation = rng.choice([0, 1e6]) + spread = 1000 + X = translation + rng.rand(n_queries, n_features).astype(dtype) * spread + Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + + metric_kwargs = _get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0] + + # Reference for argkmin results + if metric == "euclidean": + # Compare to scikit-learn GEMM optimized implementation + dist_matrix = euclidean_distances(X, Y) + else: + dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs) + + radius = _non_trivial_radius(precomputed_dists=dist_matrix) + + # Getting the neighbors for a given radius + neigh_indices_ref = [] + neigh_distances_ref = [] + + for row in dist_matrix: + ind = np.arange(row.shape[0])[row <= radius] + dist = row[ind] + + sort = np.argsort(dist) + ind, dist = ind[sort], dist[sort] + + neigh_indices_ref.append(ind) + neigh_distances_ref.append(dist) + + neigh_distances, neigh_indices = RadiusNeighbors.compute( + X, + Y, + radius, + metric=metric, + metric_kwargs=metric_kwargs, + return_distance=True, + # So as to have more than a chunk, forcing parallelism. + chunk_size=n_samples // 4, + strategy=strategy, + sort_results=True, + ) + + ASSERT_RESULT[(RadiusNeighbors, dtype)]( + neigh_distances, neigh_distances_ref, neigh_indices, neigh_indices_ref, radius + ) + + +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("metric", ["manhattan", "euclidean"]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_memmap_backed_data( + metric, + Dispatcher, + dtype, +): + """Check that the results do not depend on the datasets writability.""" + rng = np.random.RandomState(0) + spread = 100 + n_samples, n_features = 128, 10 + X = rng.rand(n_samples, n_features).astype(dtype) * spread + Y = rng.rand(n_samples, n_features).astype(dtype) * spread + + # Create read only datasets + X_mm, Y_mm = create_memmap_backed_data([X, Y]) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + return_distance=True, + **compute_parameters, + ) + + dist_mm, indices_mm = Dispatcher.compute( + X_mm, + Y_mm, + parameter, + metric=metric, + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist_mm, ref_indices, indices_mm, **check_parameters + ) + + +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_sqeuclidean_row_norms( + global_random_seed, + dtype, + csr_container, +): + rng = np.random.RandomState(global_random_seed) + spread = 100 + n_samples = rng.choice([97, 100, 101, 1000]) + n_features = rng.choice([5, 10, 100]) + num_threads = rng.choice([1, 2, 8]) + X = rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_container(X) + + sq_row_norm_reference = np.linalg.norm(X, axis=1) ** 2 + sq_row_norm = sqeuclidean_row_norms(X, num_threads=num_threads) + + sq_row_norm_csr = sqeuclidean_row_norms(X_csr, num_threads=num_threads) + + assert_allclose(sq_row_norm_reference, sq_row_norm) + assert_allclose(sq_row_norm_reference, sq_row_norm_csr) + + with pytest.raises(ValueError): + X = np.asfortranarray(X) + sqeuclidean_row_norms(X, num_threads=num_threads) + + +def test_argkmin_classmode_strategy_consistent(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + k = 5 + metric = "manhattan" + + weights = "uniform" + Y_labels = rng.randint(low=0, high=10, size=100) + unique_Y_labels = np.unique(Y_labels) + results_X = ArgKminClassMode.compute( + X=X, + Y=Y, + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + strategy="parallel_on_X", + ) + results_Y = ArgKminClassMode.compute( + X=X, + Y=Y, + k=k, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + strategy="parallel_on_Y", + ) + assert_array_equal(results_X, results_Y) + + +@pytest.mark.parametrize("outlier_label", [None, 0, 3, 6, 9]) +def test_radius_neighbors_classmode_strategy_consistent(outlier_label): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + radius = 5 + metric = "manhattan" + + weights = "uniform" + Y_labels = rng.randint(low=0, high=10, size=100) + unique_Y_labels = np.unique(Y_labels) + results_X = RadiusNeighborsClassMode.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=outlier_label, + strategy="parallel_on_X", + ) + results_Y = RadiusNeighborsClassMode.compute( + X=X, + Y=Y, + radius=radius, + metric=metric, + weights=weights, + Y_labels=Y_labels, + unique_Y_labels=unique_Y_labels, + outlier_label=outlier_label, + strategy="parallel_on_Y", + ) + assert_allclose(results_X, results_Y) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py new file mode 100644 index 0000000000000000000000000000000000000000..7d740249f8aba4d5a87ecd2d6a16087557335d9a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_ranking.py @@ -0,0 +1,2270 @@ +import math +import re + +import numpy as np +import pytest +from scipy import stats + +from sklearn import datasets, svm +from sklearn.datasets import make_multilabel_classification +from sklearn.exceptions import UndefinedMetricWarning +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ( + accuracy_score, + auc, + average_precision_score, + coverage_error, + dcg_score, + det_curve, + label_ranking_average_precision_score, + label_ranking_loss, + ndcg_score, + precision_recall_curve, + roc_auc_score, + roc_curve, + top_k_accuracy_score, +) +from sklearn.metrics._ranking import _dcg_sample_scores, _ndcg_sample_scores +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import label_binarize +from sklearn.random_projection import _sparse_random_matrix +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.extmath import softmax +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.validation import ( + check_array, + check_consistent_length, + check_random_state, +) + +############################################################################### +# Utilities for testing + +CURVE_FUNCS = [ + det_curve, + precision_recall_curve, + roc_curve, +] + + +def make_prediction(dataset=None, binary=False): + """Make some classification predictions on a toy dataset using a SVC + + If binary is True restrict to a binary classification problem instead of a + multiclass classification problem + """ + + if dataset is None: + # import some data to play with + dataset = datasets.load_iris() + + X = dataset.data + y = dataset.target + + if binary: + # restrict to a binary classification task + X, y = X[y < 2], y[y < 2] + + n_samples, n_features = X.shape + p = np.arange(n_samples) + + rng = check_random_state(37) + rng.shuffle(p) + X, y = X[p], y[p] + half = int(n_samples / 2) + + # add noisy features to make the problem harder and avoid perfect results + rng = np.random.RandomState(0) + X = np.c_[X, rng.randn(n_samples, 200 * n_features)] + + # run classifier, get class probabilities and label predictions + clf = svm.SVC(kernel="linear", probability=True, random_state=0) + y_score = clf.fit(X[:half], y[:half]).predict_proba(X[half:]) + + if binary: + # only interested in probabilities of the positive case + # XXX: do we really want a special API for the binary case? + y_score = y_score[:, 1] + + y_pred = clf.predict(X[half:]) + y_true = y[half:] + return y_true, y_pred, y_score + + +############################################################################### +# Tests + + +def _auc(y_true, y_score): + """Alternative implementation to check for correctness of + `roc_auc_score`.""" + pos_label = np.unique(y_true)[1] + + # Count the number of times positive samples are correctly ranked above + # negative samples. + pos = y_score[y_true == pos_label] + neg = y_score[y_true != pos_label] + diff_matrix = pos.reshape(1, -1) - neg.reshape(-1, 1) + n_correct = np.sum(diff_matrix > 0) + + return n_correct / float(len(pos) * len(neg)) + + +def _average_precision(y_true, y_score): + """Alternative implementation to check for correctness of + `average_precision_score`. + + Note that this implementation fails on some edge cases. + For example, for constant predictions e.g. [0.5, 0.5, 0.5], + y_true = [1, 0, 0] returns an average precision of 0.33... + but y_true = [0, 0, 1] returns 1.0. + """ + pos_label = np.unique(y_true)[1] + n_pos = np.sum(y_true == pos_label) + order = np.argsort(y_score)[::-1] + y_score = y_score[order] + y_true = y_true[order] + + score = 0 + for i in range(len(y_score)): + if y_true[i] == pos_label: + # Compute precision up to document i + # i.e, percentage of relevant documents up to document i. + prec = 0 + for j in range(0, i + 1): + if y_true[j] == pos_label: + prec += 1.0 + prec /= i + 1.0 + score += prec + + return score / n_pos + + +def _average_precision_slow(y_true, y_score): + """A second alternative implementation of average precision that closely + follows the Wikipedia article's definition (see References). This should + give identical results as `average_precision_score` for all inputs. + + References + ---------- + .. [1] `Wikipedia entry for the Average precision + `_ + """ + precision, recall, threshold = precision_recall_curve(y_true, y_score) + precision = list(reversed(precision)) + recall = list(reversed(recall)) + average_precision = 0 + for i in range(1, len(precision)): + average_precision += precision[i] * (recall[i] - recall[i - 1]) + return average_precision + + +def _partial_roc_auc_score(y_true, y_predict, max_fpr): + """Alternative implementation to check for correctness of `roc_auc_score` + with `max_fpr` set. + """ + + def _partial_roc(y_true, y_predict, max_fpr): + fpr, tpr, _ = roc_curve(y_true, y_predict) + new_fpr = fpr[fpr <= max_fpr] + new_fpr = np.append(new_fpr, max_fpr) + new_tpr = tpr[fpr <= max_fpr] + idx_out = np.argmax(fpr > max_fpr) + idx_in = idx_out - 1 + x_interp = [fpr[idx_in], fpr[idx_out]] + y_interp = [tpr[idx_in], tpr[idx_out]] + new_tpr = np.append(new_tpr, np.interp(max_fpr, x_interp, y_interp)) + return (new_fpr, new_tpr) + + new_fpr, new_tpr = _partial_roc(y_true, y_predict, max_fpr) + partial_auc = auc(new_fpr, new_tpr) + + # Formula (5) from McClish 1989 + fpr1 = 0 + fpr2 = max_fpr + min_area = 0.5 * (fpr2 - fpr1) * (fpr2 + fpr1) + max_area = fpr2 - fpr1 + return 0.5 * (1 + (partial_auc - min_area) / (max_area - min_area)) + + +@pytest.mark.parametrize("drop", [True, False]) +def test_roc_curve(drop): + # Test Area under Receiver Operating Characteristic (ROC) curve + y_true, _, y_score = make_prediction(binary=True) + expected_auc = _auc(y_true, y_score) + + fpr, tpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=drop) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, expected_auc, decimal=2) + assert_almost_equal(roc_auc, roc_auc_score(y_true, y_score)) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + +def test_roc_curve_end_points(): + # Make sure that roc_curve returns a curve start at 0 and ending and + # 1 even in corner cases + rng = np.random.RandomState(0) + y_true = np.array([0] * 50 + [1] * 50) + y_pred = rng.randint(3, size=100) + fpr, tpr, thr = roc_curve(y_true, y_pred, drop_intermediate=True) + assert fpr[0] == 0 + assert fpr[-1] == 1 + assert fpr.shape == tpr.shape + assert fpr.shape == thr.shape + + +def test_roc_returns_consistency(): + # Test whether the returned threshold matches up with tpr + # make small toy dataset + y_true, _, y_score = make_prediction(binary=True) + fpr, tpr, thresholds = roc_curve(y_true, y_score) + + # use the given thresholds to determine the tpr + tpr_correct = [] + for t in thresholds: + tp = np.sum((y_score >= t) & y_true) + p = np.sum(y_true) + tpr_correct.append(1.0 * tp / p) + + # compare tpr and tpr_correct to see if the thresholds' order was correct + assert_array_almost_equal(tpr, tpr_correct, decimal=2) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + +def test_roc_curve_multi(): + # roc_curve not applicable for multi-class problems + y_true, _, y_score = make_prediction(binary=False) + + with pytest.raises(ValueError): + roc_curve(y_true, y_score) + + +def test_roc_curve_confidence(): + # roc_curve for confidence scores + y_true, _, y_score = make_prediction(binary=True) + + fpr, tpr, thresholds = roc_curve(y_true, y_score - 0.5) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.90, decimal=2) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + +def test_roc_curve_hard(): + # roc_curve for hard decisions + y_true, pred, y_score = make_prediction(binary=True) + + # always predict one + trivial_pred = np.ones(y_true.shape) + fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.50, decimal=2) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + # always predict zero + trivial_pred = np.zeros(y_true.shape) + fpr, tpr, thresholds = roc_curve(y_true, trivial_pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.50, decimal=2) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + # hard decisions + fpr, tpr, thresholds = roc_curve(y_true, pred) + roc_auc = auc(fpr, tpr) + assert_array_almost_equal(roc_auc, 0.78, decimal=2) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + +def test_roc_curve_one_label(): + y_true = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + y_pred = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + # assert there are warnings + expected_message = ( + "No negative samples in y_true, false positive value should be meaningless" + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + fpr, tpr, thresholds = roc_curve(y_true, y_pred) + + # all true labels, all fpr should be nan + assert_array_equal(fpr, np.full(len(thresholds), np.nan)) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + # assert there are warnings + expected_message = ( + "No positive samples in y_true, true positive value should be meaningless" + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + fpr, tpr, thresholds = roc_curve([1 - x for x in y_true], y_pred) + # all negative labels, all tpr should be nan + assert_array_equal(tpr, np.full(len(thresholds), np.nan)) + assert fpr.shape == tpr.shape + assert fpr.shape == thresholds.shape + + +def test_roc_curve_toydata(): + # Binary classification + y_true = [0, 1] + y_score = [0, 1] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 0, 1]) + assert_array_almost_equal(fpr, [0, 1, 1]) + assert_almost_equal(roc_auc, 1.0) + + y_true = [0, 1] + y_score = [1, 0] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1, 1]) + assert_array_almost_equal(fpr, [0, 0, 1]) + assert_almost_equal(roc_auc, 0.0) + + y_true = [1, 0] + y_score = [1, 1] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [0, 1]) + assert_almost_equal(roc_auc, 0.5) + + y_true = [1, 0] + y_score = [1, 0] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 0, 1]) + assert_array_almost_equal(fpr, [0, 1, 1]) + assert_almost_equal(roc_auc, 1.0) + + y_true = [1, 0] + y_score = [0.5, 0.5] + tpr, fpr, _ = roc_curve(y_true, y_score) + roc_auc = roc_auc_score(y_true, y_score) + assert_array_almost_equal(tpr, [0, 1]) + assert_array_almost_equal(fpr, [0, 1]) + assert_almost_equal(roc_auc, 0.5) + + # case with no positive samples + y_true = [0, 0] + y_score = [0.25, 0.75] + # assert UndefinedMetricWarning because of no positive sample in y_true + expected_message = ( + "No positive samples in y_true, true positive value should be meaningless" + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + tpr, fpr, _ = roc_curve(y_true, y_score) + assert_array_almost_equal(tpr, [0.0, 0.5, 1.0]) + assert_array_almost_equal(fpr, [np.nan, np.nan, np.nan]) + expected_message = ( + "Only one class is present in y_true. " + "ROC AUC score is not defined in that case." + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + auc = roc_auc_score(y_true, y_score) + assert math.isnan(auc) + + # case with no negative samples + y_true = [1, 1] + y_score = [0.25, 0.75] + # assert UndefinedMetricWarning because of no negative sample in y_true + expected_message = ( + "No negative samples in y_true, false positive value should be meaningless" + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + tpr, fpr, _ = roc_curve(y_true, y_score) + assert_array_almost_equal(tpr, [np.nan, np.nan, np.nan]) + assert_array_almost_equal(fpr, [0.0, 0.5, 1.0]) + expected_message = ( + "Only one class is present in y_true. " + "ROC AUC score is not defined in that case." + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + auc = roc_auc_score(y_true, y_score) + assert math.isnan(auc) + + # Multi-label classification task + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [0, 1]]) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + roc_auc_score(y_true, y_score, average="macro") + with pytest.warns(UndefinedMetricWarning, match=expected_message): + roc_auc_score(y_true, y_score, average="weighted") + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 1.0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 1.0) + + y_true = np.array([[0, 1], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + roc_auc_score(y_true, y_score, average="macro") + with pytest.warns(UndefinedMetricWarning, match=expected_message): + roc_auc_score(y_true, y_score, average="weighted") + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0, 1], [1, 0]]) + assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0) + + y_true = np.array([[1, 0], [0, 1]]) + y_score = np.array([[0.5, 0.5], [0.5, 0.5]]) + assert_almost_equal(roc_auc_score(y_true, y_score, average="macro"), 0.5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="weighted"), 0.5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="samples"), 0.5) + assert_almost_equal(roc_auc_score(y_true, y_score, average="micro"), 0.5) + + +def test_roc_curve_drop_intermediate(): + # Test that drop_intermediate drops the correct thresholds + y_true = [0, 0, 0, 0, 1, 1] + y_score = [0.0, 0.2, 0.5, 0.6, 0.7, 1.0] + tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) + assert_array_almost_equal(thresholds, [np.inf, 1.0, 0.7, 0.0]) + + # Test dropping thresholds with repeating scores + y_true = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1] + y_score = [0.0, 0.1, 0.6, 0.6, 0.7, 0.8, 0.9, 0.6, 0.7, 0.8, 0.9, 0.9, 1.0] + tpr, fpr, thresholds = roc_curve(y_true, y_score, drop_intermediate=True) + assert_array_almost_equal(thresholds, [np.inf, 1.0, 0.9, 0.7, 0.6, 0.0]) + + +def test_roc_curve_fpr_tpr_increasing(): + # Ensure that fpr and tpr returned by roc_curve are increasing. + # Construct an edge case with float y_score and sample_weight + # when some adjacent values of fpr and tpr are actually the same. + y_true = [0, 0, 1, 1, 1] + y_score = [0.1, 0.7, 0.3, 0.4, 0.5] + sample_weight = np.repeat(0.2, 5) + fpr, tpr, _ = roc_curve(y_true, y_score, sample_weight=sample_weight) + assert (np.diff(fpr) < 0).sum() == 0 + assert (np.diff(tpr) < 0).sum() == 0 + + +def test_auc(): + # Test Area Under Curve (AUC) computation + x = [0, 1] + y = [0, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [1, 0] + y = [0, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [1, 0, 0] + y = [0, 1, 1] + assert_array_almost_equal(auc(x, y), 0.5) + x = [0, 1] + y = [1, 1] + assert_array_almost_equal(auc(x, y), 1) + x = [0, 0.5, 1] + y = [0, 0.5, 1] + assert_array_almost_equal(auc(x, y), 0.5) + + +def test_auc_errors(): + # Incompatible shapes + with pytest.raises(ValueError): + auc([0.0, 0.5, 1.0], [0.1, 0.2]) + + # Too few x values + with pytest.raises(ValueError): + auc([0.0], [0.1]) + + # x is not in order + x = [2, 1, 3, 4] + y = [5, 6, 7, 8] + error_message = "x is neither increasing nor decreasing : {}".format(np.array(x)) + with pytest.raises(ValueError, match=re.escape(error_message)): + auc(x, y) + + +@pytest.mark.parametrize( + "y_true, labels", + [ + (np.array([0, 1, 0, 2]), [0, 1, 2]), + (np.array([0, 1, 0, 2]), None), + (["a", "b", "a", "c"], ["a", "b", "c"]), + (["a", "b", "a", "c"], None), + ], +) +def test_multiclass_ovo_roc_auc_toydata(y_true, labels): + # Tests the one-vs-one multiclass ROC AUC algorithm + # on a small example, representative of an expected use case. + y_scores = np.array( + [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]] + ) + + # Used to compute the expected output. + # Consider labels 0 and 1: + # positive label is 0, negative label is 1 + score_01 = roc_auc_score([1, 0, 1], [0.1, 0.3, 0.35]) + # positive label is 1, negative label is 0 + score_10 = roc_auc_score([0, 1, 0], [0.8, 0.4, 0.5]) + average_score_01 = (score_01 + score_10) / 2 + + # Consider labels 0 and 2: + score_02 = roc_auc_score([1, 1, 0], [0.1, 0.35, 0]) + score_20 = roc_auc_score([0, 0, 1], [0.1, 0.15, 0.8]) + average_score_02 = (score_02 + score_20) / 2 + + # Consider labels 1 and 2: + score_12 = roc_auc_score([1, 0], [0.4, 0.2]) + score_21 = roc_auc_score([0, 1], [0.3, 0.8]) + average_score_12 = (score_12 + score_21) / 2 + + # Unweighted, one-vs-one multiclass ROC AUC algorithm + ovo_unweighted_score = (average_score_01 + average_score_02 + average_score_12) / 3 + assert_almost_equal( + roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo"), + ovo_unweighted_score, + ) + + # Weighted, one-vs-one multiclass ROC AUC algorithm + # Each term is weighted by the prevalence for the positive label. + pair_scores = [average_score_01, average_score_02, average_score_12] + prevalence = [0.75, 0.75, 0.50] + ovo_weighted_score = np.average(pair_scores, weights=prevalence) + assert_almost_equal( + roc_auc_score( + y_true, y_scores, labels=labels, multi_class="ovo", average="weighted" + ), + 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", + [ + (np.array([0, 2, 0, 2]), [0, 1, 2]), + (np.array(["a", "d", "a", "d"]), ["a", "b", "d"]), + ], +) +def test_multiclass_ovo_roc_auc_toydata_binary(y_true, labels): + # Tests the one-vs-one multiclass ROC AUC algorithm for binary y_true + # + # on a small example, representative of an expected use case. + y_scores = np.array( + [[0.2, 0.0, 0.8], [0.6, 0.0, 0.4], [0.55, 0.0, 0.45], [0.4, 0.0, 0.6]] + ) + + # Used to compute the expected output. + # Consider labels 0 and 1: + # positive label is 0, negative label is 1 + score_01 = roc_auc_score([1, 0, 1, 0], [0.2, 0.6, 0.55, 0.4]) + # positive label is 1, negative label is 0 + score_10 = roc_auc_score([0, 1, 0, 1], [0.8, 0.4, 0.45, 0.6]) + ovo_score = (score_01 + score_10) / 2 + + assert_almost_equal( + roc_auc_score(y_true, y_scores, labels=labels, multi_class="ovo"), ovo_score + ) + + # Weighted, one-vs-one multiclass ROC AUC algorithm + assert_almost_equal( + roc_auc_score( + y_true, y_scores, labels=labels, multi_class="ovo", average="weighted" + ), + ovo_score, + ) + + +@pytest.mark.parametrize( + "y_true, labels", + [ + (np.array([0, 1, 2, 2]), None), + (["a", "b", "c", "c"], None), + ([0, 1, 2, 2], [0, 1, 2]), + (["a", "b", "c", "c"], ["a", "b", "c"]), + ], +) +def test_multiclass_ovr_roc_auc_toydata(y_true, labels): + # Tests the unweighted, one-vs-rest multiclass ROC AUC algorithm + # on a small example, representative of an expected use case. + y_scores = np.array( + [[1.0, 0.0, 0.0], [0.1, 0.5, 0.4], [0.1, 0.1, 0.8], [0.3, 0.3, 0.4]] + ) + # Compute the expected result by individually computing the 'one-vs-rest' + # ROC AUC scores for classes 0, 1, and 2. + 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]) + 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 is average="macro") + 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, + ) + + # Tests the weighted, one-vs-rest multiclass ROC AUC algorithm + # on the same input (Provost & Domingos, 2000) + result_weighted = out_0 * 0.25 + out_1 * 0.25 + out_2 * 0.5 + assert_almost_equal( + roc_auc_score( + y_true, y_scores, multi_class="ovr", labels=labels, average="weighted" + ), + result_weighted, + ) + + +@pytest.mark.parametrize( + "multi_class, average", + [ + ("ovr", "macro"), + ("ovr", "micro"), + ("ovo", "macro"), + ], +) +def test_perfect_imperfect_chance_multiclass_roc_auc(multi_class, average): + y_true = np.array([3, 1, 2, 0]) + + # Perfect classifier (from a ranking point of view) has roc_auc_score = 1.0 + y_perfect = [ + [0.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.75, 0.05, 0.05, 0.15], + ] + assert_almost_equal( + roc_auc_score(y_true, y_perfect, multi_class=multi_class, average=average), + 1.0, + ) + + # Imperfect classifier has roc_auc_score < 1.0 + y_imperfect = [ + [0.0, 0.0, 0.0, 1.0], + [0.0, 1.0, 0.0, 0.0], + [0.0, 0.0, 1.0, 0.0], + [0.0, 0.0, 0.0, 1.0], + ] + assert ( + roc_auc_score(y_true, y_imperfect, multi_class=multi_class, average=average) + < 1.0 + ) + + # Chance level classifier has roc_auc_score = 5.0 + y_chance = 0.25 * np.ones((4, 4)) + assert roc_auc_score( + y_true, y_chance, multi_class=multi_class, average=average + ) == pytest.approx(0.5) + + +def test_micro_averaged_ovr_roc_auc(global_random_seed): + seed = global_random_seed + # Let's generate a set of random predictions and matching true labels such + # that the predictions are not perfect. To make the problem more interesting, + # we use an imbalanced class distribution (by using different parameters + # in the Dirichlet prior (conjugate prior of the multinomial distribution). + y_pred = stats.dirichlet.rvs([2.0, 1.0, 0.5], size=1000, random_state=seed) + y_true = np.asarray( + [ + stats.multinomial.rvs(n=1, p=y_pred_i, random_state=seed).argmax() + for y_pred_i in y_pred + ] + ) + y_onehot = label_binarize(y_true, classes=[0, 1, 2]) + fpr, tpr, _ = roc_curve(y_onehot.ravel(), y_pred.ravel()) + roc_auc_by_hand = auc(fpr, tpr) + roc_auc_auto = roc_auc_score(y_true, y_pred, multi_class="ovr", average="micro") + assert roc_auc_by_hand == pytest.approx(roc_auc_auto) + + +@pytest.mark.parametrize( + "msg, y_true, labels", + [ + ("Parameter 'labels' must be unique", np.array([0, 1, 2, 2]), [0, 2, 0]), + ( + "Parameter 'labels' must be unique", + np.array(["a", "b", "c", "c"]), + ["a", "a", "b"], + ), + ( + ( + "Number of classes in y_true not equal to the number of columns " + "in 'y_score'" + ), + np.array([0, 2, 0, 2]), + None, + ), + ( + "Parameter 'labels' must be ordered", + np.array(["a", "b", "c", "c"]), + ["a", "c", "b"], + ), + ( + ( + "Number of given labels, 2, not equal to the number of columns in " + "'y_score', 3" + ), + np.array([0, 1, 2, 2]), + [0, 1], + ), + ( + ( + "Number of given labels, 2, not equal to the number of columns in " + "'y_score', 3" + ), + np.array(["a", "b", "c", "c"]), + ["a", "b"], + ), + ( + ( + "Number of given labels, 4, not equal to the number of columns in " + "'y_score', 3" + ), + np.array([0, 1, 2, 2]), + [0, 1, 2, 3], + ), + ( + ( + "Number of given labels, 4, not equal to the number of columns in " + "'y_score', 3" + ), + np.array(["a", "b", "c", "c"]), + ["a", "b", "c", "d"], + ), + ( + "'y_true' contains labels not in parameter 'labels'", + np.array(["a", "b", "c", "e"]), + ["a", "b", "c"], + ), + ( + "'y_true' contains labels not in parameter 'labels'", + np.array(["a", "b", "c", "d"]), + ["a", "b", "c"], + ), + ( + "'y_true' contains labels not in parameter 'labels'", + np.array([0, 1, 2, 3]), + [0, 1, 2], + ), + ], +) +@pytest.mark.parametrize("multi_class", ["ovo", "ovr"]) +def test_roc_auc_score_multiclass_labels_error(msg, y_true, labels, multi_class): + y_scores = np.array( + [[0.1, 0.8, 0.1], [0.3, 0.4, 0.3], [0.35, 0.5, 0.15], [0, 0.2, 0.8]] + ) + + with pytest.raises(ValueError, match=msg): + roc_auc_score(y_true, y_scores, labels=labels, multi_class=multi_class) + + +@pytest.mark.parametrize( + "msg, kwargs", + [ + ( + ( + r"average must be one of \('macro', 'weighted', None\) for " + r"multiclass problems" + ), + {"average": "samples", "multi_class": "ovo"}, + ), + ( + ( + r"average must be one of \('micro', 'macro', 'weighted', None\) for " + r"multiclass problems" + ), + {"average": "samples", "multi_class": "ovr"}, + ), + ( + ( + r"sample_weight is not supported for multiclass one-vs-one " + r"ROC AUC, 'sample_weight' must be None in this case" + ), + {"multi_class": "ovo", "sample_weight": []}, + ), + ( + ( + r"Partial AUC computation not available in multiclass setting, " + r"'max_fpr' must be set to `None`, received `max_fpr=0.5` " + r"instead" + ), + {"multi_class": "ovo", "max_fpr": 0.5}, + ), + (r"multi_class must be in \('ovo', 'ovr'\)", {}), + ], +) +def test_roc_auc_score_multiclass_error(msg, kwargs): + # Test that roc_auc_score function returns an error when trying + # to compute multiclass AUC for parameters where an output + # is not defined. + rng = check_random_state(404) + y_score = rng.rand(20, 3) + y_prob = softmax(y_score) + y_true = rng.randint(0, 3, size=20) + with pytest.raises(ValueError, match=msg): + roc_auc_score(y_true, y_prob, **kwargs) + + +def test_auc_score_non_binary_class(): + # Test that roc_auc_score function returns an error when trying + # to compute AUC for non-binary class values. + rng = check_random_state(404) + y_pred = rng.rand(10) + # y_true contains only one class value + y_true = np.zeros(10, dtype="int") + warn_message = ( + "Only one class is present in y_true. " + "ROC AUC score is not defined in that case." + ) + with pytest.warns(UndefinedMetricWarning, match=warn_message): + roc_auc_score(y_true, y_pred) + y_true = np.ones(10, dtype="int") + with pytest.warns(UndefinedMetricWarning, match=warn_message): + roc_auc_score(y_true, y_pred) + y_true = np.full(10, -1, dtype="int") + with pytest.warns(UndefinedMetricWarning, match=warn_message): + roc_auc_score(y_true, y_pred) + + +@pytest.mark.parametrize("curve_func", CURVE_FUNCS) +def test_binary_clf_curve_multiclass_error(curve_func): + rng = check_random_state(404) + y_true = rng.randint(0, 3, size=10) + y_pred = rng.rand(10) + msg = "multiclass format is not supported" + with pytest.raises(ValueError, match=msg): + curve_func(y_true, y_pred) + + +@pytest.mark.parametrize("curve_func", CURVE_FUNCS) +def test_binary_clf_curve_implicit_pos_label(curve_func): + # Check that using string class labels raises an informative + # error for any supported string dtype: + msg = ( + "y_true takes value in {'a', 'b'} and pos_label is " + "not specified: either make y_true take " + "value in {0, 1} or {-1, 1} or pass pos_label " + "explicitly." + ) + with pytest.raises(ValueError, match=msg): + curve_func(np.array(["a", "b"], dtype="= 0 and y_score.max() <= 1 else 0 + y_pred = (y_score > threshold).astype(np.int64) 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) + + +@pytest.mark.parametrize( + "y_true, true_score, labels", + [ + (np.array([0, 1, 1, 2]), 0.75, [0, 1, 2, 3]), + (np.array([0, 1, 1, 1]), 0.5, [0, 1, 2, 3]), + (np.array([1, 1, 1, 1]), 0.5, [0, 1, 2, 3]), + (np.array(["a", "e", "e", "a"]), 0.75, ["a", "b", "d", "e"]), + ], +) +@pytest.mark.parametrize("labels_as_ndarray", [True, False]) +def test_top_k_accuracy_score_multiclass_with_labels( + y_true, true_score, labels, labels_as_ndarray +): + """Test when labels and y_score are multiclass.""" + if labels_as_ndarray: + labels = np.asarray(labels) + 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=2, labels=labels) + assert score == 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) + + +@pytest.mark.parametrize( + "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) + + +@pytest.mark.parametrize( + "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], + ] + ) + expected_message = ( + r"'k' \(\d+\) greater than or equal to 'n_classes' \(\d+\) will result in a " + "perfect score and is therefore meaningless." + ) + with pytest.warns(UndefinedMetricWarning, match=expected_message): + score = top_k_accuracy_score(y_true, y_score, k=k) + assert score == 1 + + +@pytest.mark.parametrize( + "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"], + [ + [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, y_score, labels, msg): + with pytest.raises(ValueError, match=msg): + top_k_accuracy_score(y_true, y_score, k=2, labels=labels) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_label_ranking_avg_precision_score_should_allow_csr_matrix_for_y_true_input( + csr_container, +): + # Test that label_ranking_avg_precision_score accept sparse y_true. + # Non-regression test for #22575 + y_true = csr_container([[1, 0, 0], [0, 0, 1]]) + y_score = np.array([[0.5, 0.9, 0.6], [0, 0, 1]]) + result = label_ranking_average_precision_score(y_true, y_score) + assert result == pytest.approx(2 / 3) + + +@pytest.mark.parametrize( + "metric", [average_precision_score, det_curve, precision_recall_curve, roc_curve] +) +@pytest.mark.parametrize( + "classes", [(False, True), (0, 1), (0.0, 1.0), ("zero", "one")] +) +def test_ranking_metric_pos_label_types(metric, classes): + """Check that the metric works with different types of `pos_label`. + + We can expect `pos_label` to be a bool, an integer, a float, a string. + No error should be raised for those types. + """ + rng = np.random.RandomState(42) + n_samples, pos_label = 10, classes[-1] + y_true = rng.choice(classes, size=n_samples, replace=True) + y_proba = rng.rand(n_samples) + result = metric(y_true, y_proba, pos_label=pos_label) + if isinstance(result, float): + assert not np.isnan(result) + else: + metric_1, metric_2, thresholds = result + assert not np.isnan(metric_1).any() + assert not np.isnan(metric_2).any() + assert not np.isnan(thresholds).any() + + +def test_roc_curve_with_probablity_estimates(global_random_seed): + """Check that thresholds do not exceed 1.0 when `y_score` is a probability + estimate. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/26193 + """ + rng = np.random.RandomState(global_random_seed) + y_true = rng.randint(0, 2, size=10) + y_score = rng.rand(10) + _, _, thresholds = roc_curve(y_true, y_score) + assert np.isinf(thresholds[0]) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..396ae5d0ffae143e333f14861dc839931326a030 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py @@ -0,0 +1,636 @@ +from itertools import product + +import numpy as np +import pytest +from numpy.testing import assert_allclose +from scipy import optimize +from scipy.special import factorial, xlogy + +from sklearn.dummy import DummyRegressor +from sklearn.exceptions import UndefinedMetricWarning +from sklearn.metrics import ( + d2_absolute_error_score, + d2_pinball_score, + d2_tweedie_score, + explained_variance_score, + make_scorer, + max_error, + mean_absolute_error, + mean_absolute_percentage_error, + mean_pinball_loss, + mean_squared_error, + mean_squared_log_error, + mean_tweedie_deviance, + median_absolute_error, + r2_score, + root_mean_squared_error, + root_mean_squared_log_error, +) +from sklearn.metrics._regression import _check_reg_targets +from sklearn.model_selection import GridSearchCV +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) + + +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.0) + 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.0) + 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.0) + mape = mean_absolute_percentage_error(y_true, y_pred) + assert np.isfinite(mape) + 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), + ) + 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 + # results evaluated by sympy + y_true = np.arange(1, 1 + n_samples) + y_pred = 2 * y_true + n = n_samples + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=-1), + 5 / 12 * n * (n**2 + 2 * n + 1), + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=1), (n + 1) * (1 - np.log(2)) + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=2), 2 * np.log(2) - 1 + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=3 / 2), + ((6 * np.sqrt(2) - 8) / n) * np.sqrt(y_true).sum(), + ) + assert_almost_equal( + 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_root_mean_squared_error_multioutput_raw_value(): + # non-regression test for + # https://github.com/scikit-learn/scikit-learn/pull/16323 + mse = mean_squared_error([[1]], [[10]], multioutput="raw_values") + rmse = root_mean_squared_error([[1]], [[10]], multioutput="raw_values") + assert np.sqrt(mse) == pytest.approx(rmse) + + +def test_multioutput_regression(): + y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) + y_pred = np.array([[0, 0, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]) + + error = mean_squared_error(y_true, y_pred) + assert_almost_equal(error, (1.0 / 3 + 2.0 / 3 + 2.0 / 3) / 4.0) + + error = root_mean_squared_error(y_true, y_pred) + assert_almost_equal(error, 0.454, decimal=2) + + error = mean_squared_log_error(y_true, y_pred) + assert_almost_equal(error, 0.200, decimal=2) + + error = root_mean_squared_log_error(y_true, y_pred) + assert_almost_equal(error, 0.315, decimal=2) + + # mean_absolute_error and mean_squared_error are equal because + # it is a binary problem. + error = mean_absolute_error(y_true, y_pred) + assert_almost_equal(error, (1.0 + 2.0 / 3) / 4.0) + + error = mean_pinball_loss(y_true, y_pred) + assert_almost_equal(error, (1.0 + 2.0 / 3) / 8.0) + + error = np.around(mean_absolute_percentage_error(y_true, y_pred), decimals=2) + assert np.isfinite(error) + assert error > 1e6 + error = median_absolute_error(y_true, y_pred) + assert_almost_equal(error, (1.0 + 1.0) / 4.0) + + error = r2_score(y_true, y_pred, multioutput="variance_weighted") + assert_almost_equal(error, 1.0 - 5.0 / 2) + 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 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") + 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(root_mean_squared_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_squared_log_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_absolute_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_pinball_loss([0.0], [0.0]), 0.0) + assert_almost_equal(mean_absolute_percentage_error([0.0], [0.0]), 0.0) + 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) + 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 + 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 values less than or equal to -1." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([-1.0], [-1.0]) + msg = ( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([1.0, 2.0, 3.0], [1.0, -2.0, 3.0]) + msg = ( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([1.0, -2.0, 3.0], [1.0, 2.0, 3.0]) + msg = ( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + with pytest.raises(ValueError, match=msg): + root_mean_squared_log_error([1.0, -2.0, 3.0], [1.0, 2.0, 3.0]) + msg = ( + "Root Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + # Tweedie deviance error + power = -1.2 + assert_allclose( + mean_tweedie_deviance([0], [1.0], power=power), 2 / (2 - power), rtol=1e-3 + ) + 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) + 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=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) + + +def test__check_reg_targets(): + # All of length 3 + EXAMPLES = [ + ("continuous", [1, 2, 3], 1), + ("continuous", [[1], [2], [3]], 1), + ("continuous-multioutput", [[1, 1], [2, 2], [3, 1]], 2), + ("continuous-multioutput", [[5, 1], [4, 2], [3, 1]], 2), + ("continuous-multioutput", [[1, 3, 4], [2, 2, 2], [3, 1, 1]], 3), + ] + + for (type1, y1, n_out1), (type2, y2, n_out2) in product(EXAMPLES, repeat=2): + if type1 == type2 and n_out1 == n_out2: + y_type, y_check1, y_check2, _, _ = _check_reg_targets( + y1, y2, sample_weight=None, multioutput=None + ) + assert type1 == y_type + if type1 == "continuous": + assert_array_equal(y_check1, np.reshape(y1, (-1, 1))) + assert_array_equal(y_check2, np.reshape(y2, (-1, 1))) + else: + assert_array_equal(y_check1, y1) + assert_array_equal(y_check2, y2) + else: + with pytest.raises(ValueError): + _check_reg_targets(y1, y2, sample_weight=None, multioutput=None) + + +def test__check_reg_targets_exception(): + invalid_multioutput = "this_value_is_not_valid" + expected_message = ( + "Allowed 'multioutput' string values are.+You provided multioutput={!r}".format( + invalid_multioutput + ) + ) + with pytest.raises(ValueError, match=expected_message): + _check_reg_targets([1, 2, 3], [[1], [2], [3]], None, invalid_multioutput) + + +def test_regression_multioutput_array(): + y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] + y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] + + 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") + 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 + ) + + 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) + 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 + # it is a binary problem. + y_true = [[0, 0]] * 4 + 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") + 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) + assert np.mean(r) == r2_score( + [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="uniform_average" + ) + evs = explained_variance_score( + [[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]] + 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) + 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 + ) + 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]]) + y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]]) + msle = mean_squared_log_error(y_true, y_pred, multioutput="raw_values") + msle2 = mean_squared_error( + np.log(1 + y_true), np.log(1 + y_pred), multioutput="raw_values" + ) + assert_array_almost_equal(msle, msle2, decimal=2) + + +def test_regression_custom_weights(): + y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] + y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] + + msew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6]) + rmsew = root_mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6]) + maew = mean_absolute_error(y_true, y_pred, multioutput=[0.4, 0.6]) + 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 + ) + + assert_almost_equal(msew, 0.39, decimal=2) + assert_almost_equal(rmsew, 0.59, decimal=2) + assert_almost_equal(maew, 0.475, decimal=3) + 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. + y_true = np.array([[0.5, 1], [1, 2], [7, 6]]) + y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]]) + msle = mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) + msle2 = mean_squared_error( + np.log(1 + y_true), np.log(1 + y_pred), multioutput=[0.3, 0.7] + ) + assert_almost_equal(msle, msle2, decimal=2) + + +@pytest.mark.parametrize("metric", [r2_score, d2_tweedie_score, d2_pinball_score]) +def test_regression_single_sample(metric): + y_true = [0] + y_pred = [1] + warning_msg = "not well-defined with less than two samples." + + # Trigger the warning + with pytest.warns(UndefinedMetricWarning, match=warning_msg): + score = metric(y_true, y_pred) + assert np.isnan(score) + + +def test_tweedie_deviance_continuity(global_random_seed): + n_samples = 100 + + rng = np.random.RandomState(global_random_seed) + + y_true = rng.rand(n_samples) + 0.1 + y_pred = rng.rand(n_samples) + 0.1 + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=0 - 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=0), + ) + + # Ws we get closer to the limit, with 1e-12 difference the + # tolerance to pass the below check increases. There are likely + # numerical precision issues on the edges of different definition + # regions. + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=1 + 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=1), + rtol=1e-5, + ) + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=2 - 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=2), + rtol=1e-5, + ) + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=2 + 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=2), + rtol=1e-5, + ) + + +def test_mean_absolute_percentage_error(global_random_seed): + random_number_generator = np.random.RandomState(global_random_seed) + 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) + + +@pytest.mark.parametrize( + "distribution", ["normal", "lognormal", "exponential", "uniform"] +) +@pytest.mark.parametrize("target_quantile", [0.05, 0.5, 0.75]) +def test_mean_pinball_loss_on_constant_predictions( + distribution, target_quantile, global_random_seed +): + 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(global_random_seed) + 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(np.float64).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()) + assert result.success + # The minimum is not unique with limited data, hence the large tolerance. + # For the normal distribution and the 0.5 quantile, the expected result is close to + # 0, hence the additional use of absolute tolerance. + assert_allclose(result.x, best_pred, rtol=1e-1, atol=1e-3) + assert result.fun == pytest.approx(best_pbl) + + +def test_dummy_quantile_parameter_tuning(global_random_seed): + # 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(global_random_seed) + 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) + + +def test_pinball_loss_relation_with_mae(global_random_seed): + # Test that mean_pinball loss with alpha=0.5 if half of mean absolute error + rng = np.random.RandomState(global_random_seed) + n = 100 + y_true = rng.normal(size=n) + y_pred = y_true.copy() + rng.uniform(n) + assert ( + mean_absolute_error(y_true, y_pred) + == mean_pinball_loss(y_true, y_pred, alpha=0.5) * 2 + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py new file mode 100644 index 0000000000000000000000000000000000000000..672ed8ae7eecc593e0aa02e76e7158c9f01e67e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/metrics/tests/test_score_objects.py @@ -0,0 +1,1665 @@ +import numbers +import pickle +import warnings +from copy import deepcopy +from functools import partial + +import joblib +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from sklearn import config_context +from sklearn.base import BaseEstimator, ClassifierMixin +from sklearn.cluster import KMeans +from sklearn.datasets import ( + load_diabetes, + make_blobs, + make_classification, + make_multilabel_classification, + make_regression, +) +from sklearn.linear_model import LogisticRegression, Perceptron, Ridge +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + balanced_accuracy_score, + brier_score_loss, + check_scoring, + f1_score, + fbeta_score, + get_scorer, + get_scorer_names, + jaccard_score, + log_loss, + make_scorer, + matthews_corrcoef, + precision_score, + r2_score, + recall_score, + roc_auc_score, + top_k_accuracy_score, +) +from sklearn.metrics import cluster as cluster_module +from sklearn.metrics._scorer import ( + _check_multimetric_scoring, + _CurveScorer, + _MultimetricScorer, + _PassthroughScorer, + _Scorer, +) +from sklearn.model_selection import GridSearchCV, cross_val_score, train_test_split +from sklearn.multiclass import OneVsRestClassifier +from sklearn.neighbors import KNeighborsClassifier +from sklearn.pipeline import make_pipeline +from sklearn.svm import LinearSVC +from sklearn.tests.metadata_routing_common import ( + assert_request_is_empty, +) +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_equal, + ignore_warnings, +) +from sklearn.utils.metadata_routing import MetadataRouter, MethodMapping + +REGRESSION_SCORERS = [ + "d2_absolute_error_score", + "explained_variance", + "r2", + "neg_mean_absolute_error", + "neg_mean_squared_error", + "neg_mean_absolute_percentage_error", + "neg_mean_squared_log_error", + "neg_median_absolute_error", + "neg_root_mean_squared_error", + "neg_root_mean_squared_log_error", + "mean_absolute_error", + "mean_absolute_percentage_error", + "mean_squared_error", + "median_absolute_error", + "neg_max_error", + "neg_mean_poisson_deviance", + "neg_mean_gamma_deviance", +] + +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", + "recall", + "recall_weighted", + "recall_macro", + "recall_micro", + "neg_log_loss", + "neg_brier_score", + "jaccard", + "jaccard_weighted", + "jaccard_macro", + "jaccard_micro", + "roc_auc_ovr", + "roc_auc_ovo", + "roc_auc_ovr_weighted", + "roc_auc_ovo_weighted", + "matthews_corrcoef", + "positive_likelihood_ratio", + "neg_negative_likelihood_ratio", +] + +# All supervised cluster scorers (They behave like classification metric) +CLUSTER_SCORERS = [ + "adjusted_rand_score", + "rand_score", + "homogeneity_score", + "completeness_score", + "v_measure_score", + "mutual_info_score", + "adjusted_mutual_info_score", + "normalized_mutual_info_score", + "fowlkes_mallows_score", +] + +MULTILABEL_ONLY_SCORERS = [ + "precision_samples", + "recall_samples", + "f1_samples", + "jaccard_samples", +] + +REQUIRE_POSITIVE_Y_SCORERS = ["neg_mean_poisson_deviance", "neg_mean_gamma_deviance"] + + +def _require_positive_y(y): + """Make targets strictly positive""" + offset = abs(y.min()) + 1 + y = y + offset + return y + + +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, _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) + sensible_ml_clf.fit(X_train, y_ml_train) + return dict( + [(name, sensible_regr) for name in REGRESSION_SCORERS] + + [(name, sensible_clf) for name in CLF_SCORERS] + + [(name, sensible_clf) for name in CLUSTER_SCORERS] + + [(name, sensible_ml_clf) for name in MULTILABEL_ONLY_SCORERS] + ) + + +@pytest.fixture(scope="module") +def memmap_data_and_estimators(tmp_path_factory): + temp_folder = tmp_path_factory.mktemp("sklearn_test_score_objects") + X, y = make_classification(n_samples=30, n_features=5, random_state=0) + _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) + filename = temp_folder / "test_data.pkl" + joblib.dump((X, y, y_ml), filename) + X_mm, y_mm, y_ml_mm = joblib.load(filename, mmap_mode="r") + estimators = _make_estimators(X_mm, y_mm, y_ml_mm) + + yield X_mm, y_mm, y_ml_mm, estimators + + +class EstimatorWithFit(BaseEstimator): + """Dummy estimator to test scoring validators""" + + def fit(self, X, y): + return self + + +class EstimatorWithFitAndScore(BaseEstimator): + """Dummy estimator to test scoring validators""" + + def fit(self, X, y): + return self + + def score(self, X, y): + return 1.0 + + +class EstimatorWithFitAndPredict(BaseEstimator): + """Dummy estimator to test scoring validators""" + + def fit(self, X, y): + self.y = y + return self + + def predict(self, X): + return self.y + + +class DummyScorer: + """Dummy scorer that always returns 1.""" + + def __call__(self, est, X, y): + return 1 + + +def test_all_scorers_repr(): + # Test that all scorers have a working repr + for name in get_scorer_names(): + repr(get_scorer(name)) + + +def check_scoring_validator_for_single_metric_usecases(scoring_validator): + # Test all branches of single metric usecases + estimator = EstimatorWithFitAndScore() + estimator.fit([[1]], [1]) + scorer = scoring_validator(estimator) + assert isinstance(scorer, _PassthroughScorer) + assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) + + estimator = EstimatorWithFitAndPredict() + estimator.fit([[1]], [1]) + pattern = ( + r"If no scoring is specified, the estimator passed should have" + r" a 'score' method\. The estimator .* does not\." + ) + with pytest.raises(TypeError, match=pattern): + scoring_validator(estimator) + + scorer = scoring_validator(estimator, scoring="accuracy") + assert_almost_equal(scorer(estimator, [[1]], [1]), 1.0) + + estimator = EstimatorWithFit() + scorer = scoring_validator(estimator, scoring="accuracy") + assert isinstance(scorer, _Scorer) + assert scorer._response_method == "predict" + + # Test the allow_none parameter for check_scoring alone + if scoring_validator is check_scoring: + estimator = EstimatorWithFit() + scorer = scoring_validator(estimator, allow_none=True) + assert scorer is None + + +@pytest.mark.parametrize( + "scoring", + ( + ("accuracy",), + ["precision"], + {"acc": "accuracy", "precision": "precision"}, + ("accuracy", "precision"), + ["precision", "accuracy"], + { + "accuracy": make_scorer(accuracy_score), + "precision": make_scorer(precision_score), + }, + ), + ids=[ + "single_tuple", + "single_list", + "dict_str", + "multi_tuple", + "multi_list", + "dict_callable", + ], +) +def test_check_scoring_and_check_multimetric_scoring(scoring): + check_scoring_validator_for_single_metric_usecases(check_scoring) + # To make sure the check_scoring is correctly applied to the constituent + # scorers + + estimator = LinearSVC(random_state=0) + estimator.fit([[1], [2], [3]], [1, 1, 0]) + + scorers = _check_multimetric_scoring(estimator, scoring) + assert isinstance(scorers, dict) + assert sorted(scorers.keys()) == sorted(list(scoring)) + assert all([isinstance(scorer, _Scorer) for scorer in list(scorers.values())]) + assert all(scorer._response_method == "predict" for scorer in scorers.values()) + + if "acc" in scoring: + assert_almost_equal( + scorers["acc"](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0 + ) + if "accuracy" in scoring: + assert_almost_equal( + scorers["accuracy"](estimator, [[1], [2], [3]], [1, 0, 0]), 2.0 / 3.0 + ) + if "precision" in scoring: + assert_almost_equal( + scorers["precision"](estimator, [[1], [2], [3]], [1, 0, 0]), 0.5 + ) + + +@pytest.mark.parametrize( + "scoring, msg", + [ + ( + (make_scorer(precision_score), make_scorer(accuracy_score)), + "One or more of the elements were callables", + ), + ([5], "Non-string types were found"), + ((make_scorer(precision_score),), "One or more of the elements were callables"), + ((), "Empty list was given"), + (("f1", "f1"), "Duplicate elements were found"), + ({4: "accuracy"}, "Non-string types were found in the keys"), + ({}, "An empty dict was passed"), + ], + ids=[ + "tuple of callables", + "list of int", + "tuple of one callable", + "empty tuple", + "non-unique str", + "non-string key dict", + "empty dict", + ], +) +def test_check_scoring_and_check_multimetric_scoring_errors(scoring, msg): + # Make sure it raises errors when scoring parameter is not valid. + # More weird corner cases are tested at test_validation.py + estimator = EstimatorWithFitAndPredict() + estimator.fit([[1]], [1]) + + with pytest.raises(ValueError, match=msg): + _check_multimetric_scoring(estimator, scoring=scoring) + + +def test_check_scoring_gridsearchcv(): + # test that check_scoring works on GridSearchCV and pipeline. + # slightly redundant non-regression test. + + grid = GridSearchCV(LinearSVC(), param_grid={"C": [0.1, 1]}, cv=3) + scorer = check_scoring(grid, scoring="f1") + assert isinstance(scorer, _Scorer) + assert scorer._response_method == "predict" + + pipe = make_pipeline(LinearSVC()) + scorer = check_scoring(pipe, scoring="f1") + assert isinstance(scorer, _Scorer) + assert scorer._response_method == "predict" + + # check that cross_val_score definitely calls the scorer + # and doesn't make any assumptions about the estimator apart from having a + # fit. + scores = cross_val_score( + EstimatorWithFit(), [[1], [2], [3]], [1, 0, 1], scoring=DummyScorer(), cv=3 + ) + assert_array_equal(scores, 1) + + +@pytest.mark.parametrize( + "scorer_name, metric", + [ + ("f1", f1_score), + ("f1_weighted", partial(f1_score, average="weighted")), + ("f1_macro", partial(f1_score, average="macro")), + ("f1_micro", partial(f1_score, average="micro")), + ("precision", precision_score), + ("precision_weighted", partial(precision_score, average="weighted")), + ("precision_macro", partial(precision_score, average="macro")), + ("precision_micro", partial(precision_score, average="micro")), + ("recall", recall_score), + ("recall_weighted", partial(recall_score, average="weighted")), + ("recall_macro", partial(recall_score, average="macro")), + ("recall_micro", partial(recall_score, average="micro")), + ("jaccard", jaccard_score), + ("jaccard_weighted", partial(jaccard_score, average="weighted")), + ("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): + # check consistency between score and scorer for scores supporting + # binary classification. + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = LinearSVC(random_state=0) + clf.fit(X_train, y_train) + + score = get_scorer(scorer_name)(clf, X_test, y_test) + expected_score = metric(y_test, clf.predict(X_test)) + assert_almost_equal(score, expected_score) + + +@pytest.mark.parametrize( + "scorer_name, metric", + [ + ("accuracy", accuracy_score), + ("balanced_accuracy", balanced_accuracy_score), + ("f1_weighted", partial(f1_score, average="weighted")), + ("f1_macro", partial(f1_score, average="macro")), + ("f1_micro", partial(f1_score, average="micro")), + ("precision_weighted", partial(precision_score, average="weighted")), + ("precision_macro", partial(precision_score, average="macro")), + ("precision_micro", partial(precision_score, average="micro")), + ("recall_weighted", partial(recall_score, average="weighted")), + ("recall_macro", partial(recall_score, average="macro")), + ("recall_micro", partial(recall_score, average="micro")), + ("jaccard_weighted", partial(jaccard_score, average="weighted")), + ("jaccard_macro", partial(jaccard_score, average="macro")), + ("jaccard_micro", partial(jaccard_score, average="micro")), + ], +) +def test_classification_multiclass_scores(scorer_name, metric): + # check consistency between score and scorer for scores supporting + # multiclass classification. + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=30, random_state=0 + ) + + # use `stratify` = y to ensure train and test sets capture all classes + X_train, X_test, y_train, y_test = train_test_split( + X, y, random_state=0, stratify=y + ) + + clf = DecisionTreeClassifier(random_state=0) + clf.fit(X_train, y_train) + score = get_scorer(scorer_name)(clf, X_test, y_test) + expected_score = metric(y_test, clf.predict(X_test)) + assert score == pytest.approx(expected_score) + + +def test_custom_scorer_pickling(): + # test that custom scorer can be pickled + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = LinearSVC(random_state=0) + clf.fit(X_train, y_train) + + scorer = make_scorer(fbeta_score, beta=2) + score1 = scorer(clf, X_test, y_test) + unpickled_scorer = pickle.loads(pickle.dumps(scorer)) + score2 = unpickled_scorer(clf, X_test, y_test) + assert score1 == pytest.approx(score2) + + # smoke test the repr: + repr(fbeta_score) + + +def test_regression_scorers(): + # Test regression scorers. + diabetes = load_diabetes() + X, y = diabetes.data, diabetes.target + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = Ridge() + clf.fit(X_train, y_train) + score1 = get_scorer("r2")(clf, X_test, y_test) + score2 = r2_score(y_test, clf.predict(X_test)) + assert_almost_equal(score1, score2) + + +def test_thresholded_scorers(): + # Test scorers that take thresholds. + X, y = make_blobs(random_state=0, centers=2) + 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) + score1 = get_scorer("roc_auc")(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.decision_function(X_test)) + score3 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) + assert_almost_equal(score1, score2) + assert_almost_equal(score1, score3) + + logscore = get_scorer("neg_log_loss")(clf, X_test, y_test) + logloss = log_loss(y_test, clf.predict_proba(X_test)) + assert_almost_equal(-logscore, logloss) + + # same for an estimator without decision_function + clf = DecisionTreeClassifier() + clf.fit(X_train, y_train) + score1 = get_scorer("roc_auc")(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.predict_proba(X_test)[:, 1]) + assert_almost_equal(score1, score2) + + # test with a regressor (no decision_function) + reg = DecisionTreeRegressor() + reg.fit(X_train, y_train) + err_msg = "DecisionTreeRegressor has none of the following attributes" + with pytest.raises(AttributeError, match=err_msg): + get_scorer("roc_auc")(reg, X_test, y_test) + + # Test that an exception is raised on more than two classes + X, y = make_blobs(random_state=0, centers=3) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf.fit(X_train, y_train) + with pytest.raises(ValueError, match="multi_class must be in \\('ovo', 'ovr'\\)"): + get_scorer("roc_auc")(clf, X_test, y_test) + + # test error is raised with a single class present in model + # (predict_proba shape is not suitable for binary auc) + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = DecisionTreeClassifier() + clf.fit(X_train, np.zeros_like(y_train)) + with pytest.raises(ValueError, match="need classifier with two classes"): + get_scorer("roc_auc")(clf, X_test, y_test) + + # for proba scorers + with pytest.raises(ValueError, match="need classifier with two classes"): + get_scorer("neg_log_loss")(clf, X_test, y_test) + + +def test_thresholded_scorers_multilabel_indicator_data(): + # Test that the scorer work with multilabel-indicator format + # for multilabel and multi-output multi-class classifier + X, y = make_multilabel_classification(allow_unlabeled=False, random_state=0) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + + # Multi-output multi-class predict_proba + clf = DecisionTreeClassifier() + clf.fit(X_train, y_train) + y_proba = clf.predict_proba(X_test) + score1 = get_scorer("roc_auc")(clf, X_test, y_test) + score2 = roc_auc_score(y_test, np.vstack([p[:, -1] for p in y_proba]).T) + assert_almost_equal(score1, score2) + + # Multilabel predict_proba + clf = OneVsRestClassifier(DecisionTreeClassifier()) + clf.fit(X_train, y_train) + score1 = get_scorer("roc_auc")(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.predict_proba(X_test)) + assert_almost_equal(score1, score2) + + # Multilabel decision function + clf = OneVsRestClassifier(LinearSVC(random_state=0)) + clf.fit(X_train, y_train) + score1 = get_scorer("roc_auc")(clf, X_test, y_test) + score2 = roc_auc_score(y_test, clf.decision_function(X_test)) + assert_almost_equal(score1, score2) + + +def test_supervised_cluster_scorers(): + # Test clustering scorers against gold standard labeling. + X, y = make_blobs(random_state=0, centers=2) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + km = KMeans(n_clusters=3, n_init="auto") + km.fit(X_train) + for name in CLUSTER_SCORERS: + score1 = get_scorer(name)(km, X_test, y_test) + score2 = getattr(cluster_module, name)(y_test, km.predict(X_test)) + assert_almost_equal(score1, score2) + + +def test_raises_on_score_list(): + # Test that when a list of scores is returned, we raise proper errors. + X, y = make_blobs(random_state=0) + f1_scorer_no_average = make_scorer(f1_score, average=None) + clf = DecisionTreeClassifier() + with pytest.raises(ValueError): + cross_val_score(clf, X, y, scoring=f1_scorer_no_average) + grid_search = GridSearchCV( + clf, scoring=f1_scorer_no_average, param_grid={"max_depth": [1, 2]} + ) + with pytest.raises(ValueError): + grid_search.fit(X, y) + + +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 + # scores really should be unequal. + X, y = make_classification(random_state=0) + _, y_ml = make_multilabel_classification(n_samples=X.shape[0], random_state=0) + split = train_test_split(X, y, y_ml, random_state=0) + X_train, X_test, y_train, y_test, y_ml_train, y_ml_test = split + + sample_weight = np.ones_like(y_test) + sample_weight[:10] = 0 + + # get sensible estimators for each metric + estimator = _make_estimators(X_train, y_train, y_ml_train) + + for name in get_scorer_names(): + scorer = get_scorer(name) + 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: + target = y_test + 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) + # this should not raise. sample_weight should be ignored if None. + _ = scorer(estimator[name], X_test[:10], target[:10], sample_weight=None) + 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 " + "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: {e}" + ) + + +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 in get_scorer_names(): + scorer = get_scorer(name) + 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 " + "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: {e}" + ) + + +@pytest.mark.parametrize("name", get_scorer_names()) +def test_scorer_memmap_input(name, memmap_data_and_estimators): + # Non-regression test for #6147: some score functions would + # return singleton memmap when computed on memmap data instead of scalar + # float values. + X_mm, y_mm, y_ml_mm, estimators = memmap_data_and_estimators + + if name in REQUIRE_POSITIVE_Y_SCORERS: + y_mm_1 = _require_positive_y(y_mm) + y_ml_mm_1 = _require_positive_y(y_ml_mm) + else: + y_mm_1, y_ml_mm_1 = y_mm, y_ml_mm + + # UndefinedMetricWarning for P / R scores + with ignore_warnings(): + scorer, estimator = get_scorer(name), estimators[name] + if name in MULTILABEL_ONLY_SCORERS: + score = scorer(estimator, X_mm, y_ml_mm_1) + else: + score = scorer(estimator, X_mm, y_mm_1) + assert isinstance(score, numbers.Number), name + + +def test_scoring_is_not_metric(): + with pytest.raises(ValueError, match="make_scorer"): + check_scoring(LogisticRegression(), scoring=f1_score) + with pytest.raises(ValueError, match="make_scorer"): + check_scoring(LogisticRegression(), scoring=roc_auc_score) + with pytest.raises(ValueError, match="make_scorer"): + check_scoring(Ridge(), scoring=r2_score) + with pytest.raises(ValueError, match="make_scorer"): + check_scoring(KMeans(), scoring=cluster_module.adjusted_rand_score) + with pytest.raises(ValueError, match="make_scorer"): + check_scoring(KMeans(), scoring=cluster_module.rand_score) + + +def test_deprecated_scorer(): + X, y = make_regression(n_samples=10, n_features=1, random_state=0) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + reg = DecisionTreeRegressor() + reg.fit(X_train, y_train) + deprecated_scorer = get_scorer("max_error") + with pytest.warns(DeprecationWarning): + deprecated_scorer(reg, X_test, y_test) + + +@pytest.mark.parametrize( + ( + "scorers,expected_predict_count," + "expected_predict_proba_count,expected_decision_func_count" + ), + [ + ( + { + "a1": "accuracy", + "a2": "accuracy", + "ll1": "neg_log_loss", + "ll2": "neg_log_loss", + "ra1": "roc_auc", + "ra2": "roc_auc", + }, + 1, + 1, + 1, + ), + (["roc_auc", "accuracy"], 1, 0, 1), + (["neg_log_loss", "accuracy"], 1, 1, 0), + ], +) +def test_multimetric_scorer_calls_method_once( + scorers, + expected_predict_count, + expected_predict_proba_count, + expected_decision_func_count, +): + X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0]) + pos_proba = np.random.rand(X.shape[0]) + proba = np.c_[1 - pos_proba, pos_proba] + + class MyClassifier(ClassifierMixin, BaseEstimator): + def __init__(self): + self._expected_predict_count = 0 + self._expected_predict_proba_count = 0 + self._expected_decision_function_count = 0 + + def fit(self, X, y): + self.classes_ = np.unique(y) + return self + + def predict(self, X): + self._expected_predict_count += 1 + return y + + def predict_proba(self, X): + self._expected_predict_proba_count += 1 + return proba + + def decision_function(self, X): + self._expected_decision_function_count += 1 + return pos_proba + + mock_est = MyClassifier().fit(X, y) + scorer_dict = _check_multimetric_scoring(LogisticRegression(), scorers) + multi_scorer = _MultimetricScorer(scorers=scorer_dict) + results = multi_scorer(mock_est, X, y) + + assert set(scorers) == set(results) # compare dict keys + + assert mock_est._expected_predict_count == expected_predict_count + assert mock_est._expected_predict_proba_count == expected_predict_proba_count + assert mock_est._expected_decision_function_count == expected_decision_func_count + + +@pytest.mark.parametrize( + "scorers", + [ + (["roc_auc", "neg_log_loss"]), + ( + { + "roc_auc": make_scorer( + roc_auc_score, + response_method=["predict_proba", "decision_function"], + ), + "neg_log_loss": make_scorer(log_loss, response_method="predict_proba"), + } + ), + ], +) +def test_multimetric_scorer_calls_method_once_classifier_no_decision(scorers): + predict_proba_call_cnt = 0 + + class MockKNeighborsClassifier(KNeighborsClassifier): + def predict_proba(self, X): + nonlocal predict_proba_call_cnt + predict_proba_call_cnt += 1 + return super().predict_proba(X) + + X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0]) + + # no decision function + clf = MockKNeighborsClassifier(n_neighbors=1) + clf.fit(X, y) + + scorer_dict = _check_multimetric_scoring(clf, scorers) + scorer = _MultimetricScorer(scorers=scorer_dict) + scorer(clf, X, y) + + assert predict_proba_call_cnt == 1 + + +def test_multimetric_scorer_calls_method_once_regressor_threshold(): + predict_called_cnt = 0 + + class MockDecisionTreeRegressor(DecisionTreeRegressor): + def predict(self, X): + nonlocal predict_called_cnt + predict_called_cnt += 1 + return super().predict(X) + + X, y = np.array([[1], [1], [0], [0], [0]]), np.array([0, 1, 1, 1, 0]) + + # no decision function + clf = MockDecisionTreeRegressor() + clf.fit(X, y) + + scorers = {"neg_mse": "neg_mean_squared_error", "r2": "r2"} + scorer_dict = _check_multimetric_scoring(clf, scorers) + scorer = _MultimetricScorer(scorers=scorer_dict) + scorer(clf, X, y) + + assert predict_called_cnt == 1 + + +def test_multimetric_scorer_sanity_check(): + # scoring dictionary returned is the same as calling each scorer separately + scorers = { + "a1": "accuracy", + "a2": "accuracy", + "ll1": "neg_log_loss", + "ll2": "neg_log_loss", + "ra1": "roc_auc", + "ra2": "roc_auc", + } + + X, y = make_classification(random_state=0) + + clf = DecisionTreeClassifier() + clf.fit(X, y) + + scorer_dict = _check_multimetric_scoring(clf, scorers) + multi_scorer = _MultimetricScorer(scorers=scorer_dict) + + result = multi_scorer(clf, X, y) + + separate_scores = { + name: get_scorer(name)(clf, X, y) + for name in ["accuracy", "neg_log_loss", "roc_auc"] + } + + for key, value in result.items(): + score_name = scorers[key] + assert_allclose(value, separate_scores[score_name]) + + +@pytest.mark.parametrize("raise_exc", [True, False]) +def test_multimetric_scorer_exception_handling(raise_exc): + """Check that the calling of the `_MultimetricScorer` returns + exception messages in the result dict for the failing scorers + in case of `raise_exc` is `False` and if `raise_exc` is `True`, + then the proper exception is raised. + """ + scorers = { + "failing_1": "neg_mean_squared_log_error", + "non_failing": "neg_median_absolute_error", + "failing_2": "neg_mean_squared_log_error", + } + + X, y = make_classification( + n_samples=50, n_features=2, n_redundant=0, random_state=0 + ) + # neg_mean_squared_log_error fails if y contains values less than or equal to -1 + y *= -1 + + clf = DecisionTreeClassifier().fit(X, y) + + scorer_dict = _check_multimetric_scoring(clf, scorers) + multi_scorer = _MultimetricScorer(scorers=scorer_dict, raise_exc=raise_exc) + + error_msg = ( + "Mean Squared Logarithmic Error cannot be used when " + "targets contain values less than or equal to -1." + ) + + if raise_exc: + with pytest.raises(ValueError, match=error_msg): + multi_scorer(clf, X, y) + else: + result = multi_scorer(clf, X, y) + + exception_message_1 = result["failing_1"] + score = result["non_failing"] + exception_message_2 = result["failing_2"] + + assert isinstance(exception_message_1, str) and error_msg in exception_message_1 + assert isinstance(score, float) + assert isinstance(exception_message_2, str) and error_msg in exception_message_2 + + +@pytest.mark.parametrize( + "scorer_name, metric", + [ + ("roc_auc_ovr", partial(roc_auc_score, multi_class="ovr")), + ("roc_auc_ovo", partial(roc_auc_score, multi_class="ovo")), + ( + "roc_auc_ovr_weighted", + partial(roc_auc_score, multi_class="ovr", average="weighted"), + ), + ( + "roc_auc_ovo_weighted", + partial(roc_auc_score, multi_class="ovo", average="weighted"), + ), + ], +) +def test_multiclass_roc_proba_scorer(scorer_name, metric): + scorer = get_scorer(scorer_name) + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=20, random_state=0 + ) + lr = LogisticRegression().fit(X, y) + y_proba = lr.predict_proba(X) + expected_score = metric(y, y_proba) + + assert scorer(lr, X, y) == pytest.approx(expected_score) + + +def test_multiclass_roc_proba_scorer_label(): + scorer = make_scorer( + roc_auc_score, + multi_class="ovo", + labels=[0, 1, 2], + response_method="predict_proba", + ) + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=20, random_state=0 + ) + lr = LogisticRegression().fit(X, y) + y_proba = lr.predict_proba(X) + + y_binary = y == 0 + expected_score = roc_auc_score( + y_binary, y_proba, multi_class="ovo", labels=[0, 1, 2] + ) + + assert scorer(lr, X, y_binary) == pytest.approx(expected_score) + + +@pytest.mark.parametrize( + "scorer_name", + ["roc_auc_ovr", "roc_auc_ovo", "roc_auc_ovr_weighted", "roc_auc_ovo_weighted"], +) +def test_multiclass_roc_no_proba_scorer_errors(scorer_name): + # Perceptron has no predict_proba + scorer = get_scorer(scorer_name) + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=20, random_state=0 + ) + lr = Perceptron().fit(X, y) + msg = "Perceptron has none of the following attributes: predict_proba." + with pytest.raises(AttributeError, match=msg): + scorer(lr, X, y) + + +@pytest.fixture +def string_labeled_classification_problem(): + """Train a classifier on binary problem with string target. + + The classifier is trained on a binary classification problem where the + minority class of interest has a string label that is intentionally not the + greatest class label using the lexicographic order. In this case, "cancer" + is the positive label, and `classifier.classes_` is + `["cancer", "not cancer"]`. + + In addition, the dataset is imbalanced to better identify problems when + using non-symmetric performance metrics such as f1-score, average precision + and so on. + + Returns + ------- + classifier : estimator object + Trained classifier on the binary problem. + X_test : ndarray of shape (n_samples, n_features) + Data to be used as testing set in tests. + y_test : ndarray of shape (n_samples,), dtype=object + Binary target where labels are strings. + y_pred : ndarray of shape (n_samples,), dtype=object + Prediction of `classifier` when predicting for `X_test`. + y_pred_proba : ndarray of shape (n_samples, 2), dtype=np.float64 + Probabilities of `classifier` when predicting for `X_test`. + y_pred_decision : ndarray of shape (n_samples,), dtype=np.float64 + Decision function values of `classifier` when predicting on `X_test`. + """ + from sklearn.datasets import load_breast_cancer + from sklearn.utils import shuffle + + X, y = load_breast_cancer(return_X_y=True) + # create an highly imbalanced classification task + idx_positive = np.flatnonzero(y == 1) + idx_negative = np.flatnonzero(y == 0) + idx_selected = np.hstack([idx_negative, idx_positive[:25]]) + X, y = X[idx_selected], y[idx_selected] + X, y = shuffle(X, y, random_state=42) + # only use 2 features to make the problem even harder + X = X[:, :2] + y = np.array(["cancer" if c == 1 else "not cancer" for c in y], dtype=object) + X_train, X_test, y_train, y_test = train_test_split( + X, + y, + stratify=y, + random_state=0, + ) + classifier = LogisticRegression().fit(X_train, y_train) + y_pred = classifier.predict(X_test) + y_pred_proba = classifier.predict_proba(X_test) + y_pred_decision = classifier.decision_function(X_test) + + return classifier, X_test, y_test, y_pred, y_pred_proba, y_pred_decision + + +def test_average_precision_pos_label(string_labeled_classification_problem): + # check that _Scorer will lead to the right score when passing + # `pos_label`. Currently, only `average_precision_score` is defined to + # be such a scorer. + ( + clf, + X_test, + y_test, + _, + y_pred_proba, + y_pred_decision, + ) = string_labeled_classification_problem + + pos_label = "cancer" + # we need to select the positive column or reverse the decision values + y_pred_proba = y_pred_proba[:, 0] + y_pred_decision = y_pred_decision * -1 + assert clf.classes_[0] == pos_label + + # check that when calling the scoring function, probability estimates and + # decision values lead to the same results + ap_proba = average_precision_score(y_test, y_pred_proba, pos_label=pos_label) + ap_decision_function = average_precision_score( + y_test, y_pred_decision, pos_label=pos_label + ) + assert ap_proba == pytest.approx(ap_decision_function) + + # create a scorer which would require to pass a `pos_label` + # check that it fails if `pos_label` is not provided + average_precision_scorer = make_scorer( + average_precision_score, + response_method=("decision_function", "predict_proba"), + ) + err_msg = "pos_label=1 is not a valid label. It should be one of " + with pytest.raises(ValueError, match=err_msg): + average_precision_scorer(clf, X_test, y_test) + + # otherwise, the scorer should give the same results than calling the + # scoring function + average_precision_scorer = make_scorer( + average_precision_score, + response_method=("decision_function", "predict_proba"), + pos_label=pos_label, + ) + ap_scorer = average_precision_scorer(clf, X_test, y_test) + + assert ap_scorer == pytest.approx(ap_proba) + + # The above scorer call is using `clf.decision_function`. We will force + # it to use `clf.predict_proba`. + clf_without_predict_proba = deepcopy(clf) + + def _predict_proba(self, X): + raise NotImplementedError + + clf_without_predict_proba.predict_proba = partial( + _predict_proba, clf_without_predict_proba + ) + # sanity check + with pytest.raises(NotImplementedError): + clf_without_predict_proba.predict_proba(X_test) + + ap_scorer = average_precision_scorer(clf_without_predict_proba, X_test, y_test) + assert ap_scorer == pytest.approx(ap_proba) + + +def test_brier_score_loss_pos_label(string_labeled_classification_problem): + # check that _Scorer leads to the right score when `pos_label` is + # provided. Currently only the `brier_score_loss` is defined to be such + # a scorer. + clf, X_test, y_test, _, y_pred_proba, _ = string_labeled_classification_problem + + pos_label = "cancer" + assert clf.classes_[0] == pos_label + + # brier score loss is symmetric + brier_pos_cancer = brier_score_loss(y_test, y_pred_proba[:, 0], pos_label="cancer") + brier_pos_not_cancer = brier_score_loss( + y_test, y_pred_proba[:, 1], pos_label="not cancer" + ) + assert brier_pos_cancer == pytest.approx(brier_pos_not_cancer) + + brier_scorer = make_scorer( + brier_score_loss, + response_method="predict_proba", + pos_label=pos_label, + ) + assert brier_scorer(clf, X_test, y_test) == pytest.approx(brier_pos_cancer) + + +@pytest.mark.parametrize( + "score_func", [f1_score, precision_score, recall_score, jaccard_score] +) +def test_non_symmetric_metric_pos_label( + score_func, string_labeled_classification_problem +): + # check that _Scorer leads to the right score when `pos_label` is + # provided. We check for all possible metric supported. + # Note: At some point we may end up having "scorer tags". + clf, X_test, y_test, y_pred, _, _ = string_labeled_classification_problem + + pos_label = "cancer" + assert clf.classes_[0] == pos_label + + score_pos_cancer = score_func(y_test, y_pred, pos_label="cancer") + score_pos_not_cancer = score_func(y_test, y_pred, pos_label="not cancer") + + assert score_pos_cancer != pytest.approx(score_pos_not_cancer) + + scorer = make_scorer(score_func, pos_label=pos_label) + assert scorer(clf, X_test, y_test) == pytest.approx(score_pos_cancer) + + +@pytest.mark.parametrize( + "scorer", + [ + make_scorer( + average_precision_score, + response_method=("decision_function", "predict_proba"), + pos_label="xxx", + ), + make_scorer(brier_score_loss, response_method="predict_proba", pos_label="xxx"), + make_scorer(f1_score, pos_label="xxx"), + ], + ids=["non-thresholded scorer", "probability scorer", "thresholded scorer"], +) +def test_scorer_select_proba_error(scorer): + # check that we raise the proper error when passing an unknown + # pos_label + X, y = make_classification( + n_classes=2, n_informative=3, n_samples=20, random_state=0 + ) + lr = LogisticRegression().fit(X, y) + assert scorer._kwargs["pos_label"] not in np.unique(y).tolist() + + err_msg = "is not a valid label" + with pytest.raises(ValueError, match=err_msg): + scorer(lr, X, y) + + +def test_get_scorer_return_copy(): + # test that get_scorer returns a copy + assert get_scorer("roc_auc") is not get_scorer("roc_auc") + + +def test_scorer_no_op_multiclass_select_proba(): + # check that calling a _Scorer on a multiclass problem do not raise + # even if `y_true` would be binary during the scoring. + # `_select_proba_binary` should not be called in this case. + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=20, random_state=0 + ) + lr = LogisticRegression().fit(X, y) + + mask_last_class = y == lr.classes_[-1] + X_test, y_test = X[~mask_last_class], y[~mask_last_class] + assert_array_equal(np.unique(y_test), lr.classes_[:-1]) + + scorer = make_scorer( + roc_auc_score, + response_method="predict_proba", + multi_class="ovo", + labels=lr.classes_, + ) + scorer(lr, X_test, y_test) + + +@pytest.mark.parametrize("name", get_scorer_names()) +def test_scorer_set_score_request_raises(name): + """Test that set_score_request is only available when feature flag is on.""" + # Make sure they expose the routing methods. + scorer = get_scorer(name) + with pytest.raises(RuntimeError, match="This method is only available"): + scorer.set_score_request() + + +@pytest.mark.parametrize("name", get_scorer_names(), ids=get_scorer_names()) +@config_context(enable_metadata_routing=True) +def test_scorer_metadata_request(name): + """Testing metadata requests for scorers. + + This test checks many small things in a large test, to reduce the + boilerplate required for each section. + """ + # Make sure they expose the routing methods. + scorer = get_scorer(name) + assert hasattr(scorer, "set_score_request") + assert hasattr(scorer, "get_metadata_routing") + + # Check that by default no metadata is requested. + assert_request_is_empty(scorer.get_metadata_routing()) + + weighted_scorer = scorer.set_score_request(sample_weight=True) + # set_score_request should mutate the instance, rather than returning a + # new instance + assert weighted_scorer is scorer + + # make sure the scorer doesn't request anything on methods other than + # `score`, and that the requested value on `score` is correct. + assert_request_is_empty(weighted_scorer.get_metadata_routing(), exclude="score") + assert ( + weighted_scorer.get_metadata_routing().score.requests["sample_weight"] is True + ) + + # make sure putting the scorer in a router doesn't request anything by + # default + router = MetadataRouter(owner="test").add( + scorer=get_scorer(name), + method_mapping=MethodMapping().add(caller="score", callee="score"), + ) + # make sure `sample_weight` is refused if passed. + with pytest.raises(TypeError, match="got unexpected argument"): + router.validate_metadata(params={"sample_weight": 1}, method="score") + # make sure `sample_weight` is not routed even if passed. + routed_params = router.route_params(params={"sample_weight": 1}, caller="score") + assert not routed_params.scorer.score + + # make sure putting weighted_scorer in a router requests sample_weight + router = MetadataRouter(owner="test").add( + scorer=weighted_scorer, + method_mapping=MethodMapping().add(caller="score", callee="score"), + ) + router.validate_metadata(params={"sample_weight": 1}, method="score") + routed_params = router.route_params(params={"sample_weight": 1}, caller="score") + assert list(routed_params.scorer.score.keys()) == ["sample_weight"] + + +@config_context(enable_metadata_routing=True) +def test_metadata_kwarg_conflict(): + """This test makes sure the right warning is raised if the user passes + some metadata both as a constructor to make_scorer, and during __call__. + """ + X, y = make_classification( + n_classes=3, n_informative=3, n_samples=20, random_state=0 + ) + lr = LogisticRegression().fit(X, y) + + scorer = make_scorer( + roc_auc_score, + response_method="predict_proba", + multi_class="ovo", + labels=lr.classes_, + ) + with pytest.warns(UserWarning, match="already set as kwargs"): + scorer.set_score_request(labels=True) + + with pytest.warns(UserWarning, match="There is an overlap"): + scorer(lr, X, y, labels=lr.classes_) + + +@config_context(enable_metadata_routing=True) +def test_PassthroughScorer_set_score_request(): + """Test that _PassthroughScorer.set_score_request adds the correct metadata request + on itself and doesn't change its estimator's routing.""" + est = LogisticRegression().set_score_request(sample_weight="estimator_weights") + # make a `_PassthroughScorer` with `check_scoring`: + scorer = check_scoring(est, None) + assert ( + scorer.get_metadata_routing().score.requests["sample_weight"] + == "estimator_weights" + ) + + scorer.set_score_request(sample_weight="scorer_weights") + assert ( + scorer.get_metadata_routing().score.requests["sample_weight"] + == "scorer_weights" + ) + + # making sure changing the passthrough object doesn't affect the estimator. + assert ( + est.get_metadata_routing().score.requests["sample_weight"] + == "estimator_weights" + ) + + +def test_PassthroughScorer_set_score_request_raises_without_routing_enabled(): + """Test that _PassthroughScorer.set_score_request raises if metadata routing is + disabled.""" + scorer = check_scoring(LogisticRegression(), None) + msg = "This method is only available when metadata routing is enabled." + + with pytest.raises(RuntimeError, match=msg): + scorer.set_score_request(sample_weight="my_weights") + + +@config_context(enable_metadata_routing=True) +def test_multimetric_scoring_metadata_routing(): + # Test that _MultimetricScorer properly routes metadata. + def score1(y_true, y_pred): + return 1 + + def score2(y_true, y_pred, sample_weight="test"): + # make sure sample_weight is not passed + assert sample_weight == "test" + return 1 + + def score3(y_true, y_pred, sample_weight=None): + # make sure sample_weight is passed + assert sample_weight is not None + return 1 + + scorers = { + "score1": make_scorer(score1), + "score2": make_scorer(score2).set_score_request(sample_weight=False), + "score3": make_scorer(score3).set_score_request(sample_weight=True), + } + + X, y = make_classification( + n_samples=50, n_features=2, n_redundant=0, random_state=0 + ) + + clf = DecisionTreeClassifier().fit(X, y) + + scorer_dict = _check_multimetric_scoring(clf, scorers) + multi_scorer = _MultimetricScorer(scorers=scorer_dict) + # This passes since routing is done. + multi_scorer(clf, X, y, sample_weight=1) + + +@config_context(enable_metadata_routing=False) +def test_multimetric_scoring_kwargs(): + # Test that _MultimetricScorer correctly forwards kwargs + # to the scorers when metadata routing is disabled. + # `sample_weight` is only forwarded to the scorers that accept it. + # Other arguments are forwarded to all scorers. + def score1(y_true, y_pred, common_arg=None): + # make sure common_arg is passed + assert common_arg is not None + return 1 + + def score2(y_true, y_pred, common_arg=None, sample_weight=None): + # make sure common_arg is passed + assert common_arg is not None + # make sure sample_weight is passed + assert sample_weight is not None + return 1 + + scorers = { + "score1": make_scorer(score1), + "score2": make_scorer(score2), + } + + X, y = make_classification( + n_samples=50, n_features=2, n_redundant=0, random_state=0 + ) + + clf = DecisionTreeClassifier().fit(X, y) + + scorer_dict = _check_multimetric_scoring(clf, scorers) + multi_scorer = _MultimetricScorer(scorers=scorer_dict) + multi_scorer(clf, X, y, common_arg=1, sample_weight=1) + + +def test_kwargs_without_metadata_routing_error(): + # Test that kwargs are not supported in scorers if metadata routing is not + # enabled. + # TODO: remove when enable_metadata_routing is deprecated + def score(y_true, y_pred, param=None): + return 1 # pragma: no cover + + X, y = make_classification( + n_samples=50, n_features=2, n_redundant=0, random_state=0 + ) + + clf = DecisionTreeClassifier().fit(X, y) + scorer = make_scorer(score) + with config_context(enable_metadata_routing=False): + with pytest.raises( + ValueError, match="is only supported if enable_metadata_routing=True" + ): + scorer(clf, X, y, param="blah") + + +def test_get_scorer_multilabel_indicator(): + """Check that our scorer deal with multi-label indicator matrices. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/26817 + """ + X, Y = make_multilabel_classification(n_samples=72, n_classes=3, random_state=0) + X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0) + + estimator = KNeighborsClassifier().fit(X_train, Y_train) + + score = get_scorer("average_precision")(estimator, X_test, Y_test) + assert score > 0.8 + + +@pytest.mark.parametrize( + "scorer, expected_repr", + [ + ( + get_scorer("accuracy"), + "make_scorer(accuracy_score, response_method='predict')", + ), + ( + get_scorer("neg_log_loss"), + ( + "make_scorer(log_loss, greater_is_better=False," + " response_method='predict_proba')" + ), + ), + ( + get_scorer("roc_auc"), + ( + "make_scorer(roc_auc_score, response_method=" + "('decision_function', 'predict_proba'))" + ), + ), + ( + make_scorer(fbeta_score, beta=2), + "make_scorer(fbeta_score, response_method='predict', beta=2)", + ), + ], +) +def test_make_scorer_repr(scorer, expected_repr): + """Check the representation of the scorer.""" + assert repr(scorer) == expected_repr + + +@pytest.mark.parametrize("pass_estimator", [True, False]) +def test_get_scorer_multimetric(pass_estimator): + """Check that check_scoring is compatible with multi-metric configurations.""" + X, y = make_classification(n_samples=150, n_features=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) + + if pass_estimator: + check_scoring_ = check_scoring + else: + check_scoring_ = partial(check_scoring, clf) + + clf.fit(X_train, y_train) + + y_pred = clf.predict(X_test) + y_proba = clf.predict_proba(X_test) + + expected_results = { + "r2": r2_score(y_test, y_pred), + "roc_auc": roc_auc_score(y_test, y_proba[:, 1]), + "accuracy": accuracy_score(y_test, y_pred), + } + + for container in [set, list, tuple]: + scoring = check_scoring_(scoring=container(["r2", "roc_auc", "accuracy"])) + result = scoring(clf, X_test, y_test) + + assert result.keys() == expected_results.keys() + for name in result: + assert result[name] == pytest.approx(expected_results[name]) + + def double_accuracy(y_true, y_pred): + return 2 * accuracy_score(y_true, y_pred) + + custom_scorer = make_scorer(double_accuracy, response_method="predict") + + # dict with different names + dict_scoring = check_scoring_( + scoring={ + "my_r2": "r2", + "my_roc_auc": "roc_auc", + "double_accuracy": custom_scorer, + } + ) + dict_result = dict_scoring(clf, X_test, y_test) + assert len(dict_result) == 3 + assert dict_result["my_r2"] == pytest.approx(expected_results["r2"]) + assert dict_result["my_roc_auc"] == pytest.approx(expected_results["roc_auc"]) + assert dict_result["double_accuracy"] == pytest.approx( + 2 * expected_results["accuracy"] + ) + + +def test_multimetric_scorer_repr(): + """Check repr for multimetric scorer""" + multi_metric_scorer = check_scoring(scoring=["accuracy", "r2"]) + + assert str(multi_metric_scorer) == 'MultiMetricScorer("accuracy", "r2")' + + +def test_check_scoring_multimetric_raise_exc(): + """Test that check_scoring returns error code for a subset of scorers in + multimetric scoring if raise_exc=False and raises otherwise.""" + + def raising_scorer(estimator, X, y): + raise ValueError("That doesn't work.") + + X, y = make_classification(n_samples=150, n_features=10, random_state=0) + X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) + clf = LogisticRegression().fit(X_train, y_train) + + # "raising_scorer" is raising ValueError and should return an string representation + # of the error of the last scorer: + scoring = { + "accuracy": make_scorer(accuracy_score), + "raising_scorer": raising_scorer, + } + scoring_call = check_scoring(estimator=clf, scoring=scoring, raise_exc=False) + scores = scoring_call(clf, X_test, y_test) + assert "That doesn't work." in scores["raising_scorer"] + + # should raise an error + scoring_call = check_scoring(estimator=clf, scoring=scoring, raise_exc=True) + err_msg = "That doesn't work." + with pytest.raises(ValueError, match=err_msg): + scores = scoring_call(clf, X_test, y_test) + + +@pytest.mark.parametrize("enable_metadata_routing", [True, False]) +def test_metadata_routing_multimetric_metadata_routing(enable_metadata_routing): + """Test multimetric scorer works with and without metadata routing enabled when + there is no actual metadata to pass. + + Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/28256 + """ + X, y = make_classification(n_samples=50, n_features=10, random_state=0) + estimator = EstimatorWithFitAndPredict().fit(X, y) + + multimetric_scorer = _MultimetricScorer(scorers={"acc": get_scorer("accuracy")}) + with config_context(enable_metadata_routing=enable_metadata_routing): + multimetric_scorer(estimator, X, y) + + +def test_curve_scorer(): + """Check the behaviour of the `_CurveScorer` class.""" + X, y = make_classification(random_state=0) + estimator = LogisticRegression().fit(X, y) + curve_scorer = _CurveScorer( + balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + scores, thresholds = curve_scorer(estimator, X, y) + + assert thresholds.shape == scores.shape + # check that the thresholds are probabilities with extreme values close to 0 and 1. + # they are not exactly 0 and 1 because they are the extremum of the + # `estimator.predict_proba(X)` values. + assert 0 <= thresholds.min() <= 0.01 + assert 0.99 <= thresholds.max() <= 1 + # balanced accuracy should be between 0.5 and 1 when it is not adjusted + assert 0.5 <= scores.min() <= 1 + + # check that passing kwargs to the scorer works + curve_scorer = _CurveScorer( + balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={"adjusted": True}, + ) + scores, thresholds = curve_scorer(estimator, X, y) + + # balanced accuracy should be between 0.5 and 1 when it is not adjusted + assert 0 <= scores.min() <= 0.5 + + # check that we can inverse the sign of the score when dealing with `neg_*` scorer + curve_scorer = _CurveScorer( + balanced_accuracy_score, + sign=-1, + response_method="predict_proba", + thresholds=10, + kwargs={"adjusted": True}, + ) + scores, thresholds = curve_scorer(estimator, X, y) + + assert all(scores <= 0) + + +def test_curve_scorer_pos_label(global_random_seed): + """Check that we propagate properly the `pos_label` parameter to the scorer.""" + n_samples = 30 + X, y = make_classification( + n_samples=n_samples, weights=[0.9, 0.1], random_state=global_random_seed + ) + estimator = LogisticRegression().fit(X, y) + + curve_scorer = _CurveScorer( + recall_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={"pos_label": 1}, + ) + scores_pos_label_1, thresholds_pos_label_1 = curve_scorer(estimator, X, y) + + curve_scorer = _CurveScorer( + recall_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={"pos_label": 0}, + ) + scores_pos_label_0, thresholds_pos_label_0 = curve_scorer(estimator, X, y) + + # Since `pos_label` is forwarded to the curve_scorer, the thresholds are not equal. + assert not (thresholds_pos_label_1 == thresholds_pos_label_0).all() + # The min-max range for the thresholds is defined by the probabilities of the + # `pos_label` class (the column of `predict_proba`). + y_pred = estimator.predict_proba(X) + assert thresholds_pos_label_0.min() == pytest.approx(y_pred.min(axis=0)[0]) + assert thresholds_pos_label_0.max() == pytest.approx(y_pred.max(axis=0)[0]) + assert thresholds_pos_label_1.min() == pytest.approx(y_pred.min(axis=0)[1]) + assert thresholds_pos_label_1.max() == pytest.approx(y_pred.max(axis=0)[1]) + + # The recall cannot be negative and `pos_label=1` should have a higher recall + # since there is less samples to be considered. + assert 0.0 < scores_pos_label_0.min() < scores_pos_label_1.min() + assert scores_pos_label_0.max() == pytest.approx(1.0) + assert scores_pos_label_1.max() == pytest.approx(1.0) + + +# TODO(1.8): remove +def test_make_scorer_reponse_method_default_warning(): + with pytest.warns(FutureWarning, match="response_method=None is deprecated"): + make_scorer(accuracy_score, response_method=None) + + # No warning is raised if response_method is left to its default value + # because the future default value has the same effect as the current one. + with warnings.catch_warnings(): + warnings.simplefilter("error", FutureWarning) + make_scorer(accuracy_score) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c27263a0ed74381a7c8dad4d6488eba570eb49b8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/__init__.py @@ -0,0 +1,9 @@ +"""Mixture modeling algorithms.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._bayesian_mixture import BayesianGaussianMixture +from ._gaussian_mixture import GaussianMixture + +__all__ = ["BayesianGaussianMixture", "GaussianMixture"] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..f66344a2847533629f52ddb10a4e819144cc8cfe --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_base.py @@ -0,0 +1,571 @@ +"""Base class for mixture models.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABCMeta, abstractmethod +from numbers import Integral, Real +from time import time + +import numpy as np +from scipy.special import logsumexp + +from .. import cluster +from ..base import BaseEstimator, DensityMixin, _fit_context +from ..cluster import kmeans_plusplus +from ..exceptions import ConvergenceWarning +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.validation import check_is_fitted, validate_data + + +def _check_shape(param, param_shape, name): + """Validate the shape of the input parameter 'param'. + + Parameters + ---------- + param : array + + param_shape : tuple + + name : str + """ + param = np.array(param) + if param.shape != param_shape: + raise ValueError( + "The parameter '%s' should have the shape of %s, but got %s" + % (name, param_shape, param.shape) + ) + + +class BaseMixture(DensityMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for mixture models. + + This abstract class specifies an interface for all mixture classes and + provides basic common methods for mixture models. + """ + + _parameter_constraints: dict = { + "n_components": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0.0, None, closed="left")], + "reg_covar": [Interval(Real, 0.0, None, closed="left")], + "max_iter": [Interval(Integral, 0, None, closed="left")], + "n_init": [Interval(Integral, 1, None, closed="left")], + "init_params": [ + StrOptions({"kmeans", "random", "random_from_data", "k-means++"}) + ], + "random_state": ["random_state"], + "warm_start": ["boolean"], + "verbose": ["verbose"], + "verbose_interval": [Interval(Integral, 1, None, closed="left")], + } + + def __init__( + self, + n_components, + tol, + reg_covar, + max_iter, + n_init, + init_params, + random_state, + warm_start, + verbose, + verbose_interval, + ): + self.n_components = n_components + self.tol = tol + self.reg_covar = reg_covar + self.max_iter = max_iter + self.n_init = n_init + self.init_params = init_params + self.random_state = random_state + self.warm_start = warm_start + self.verbose = verbose + self.verbose_interval = verbose_interval + + @abstractmethod + def _check_parameters(self, X): + """Check initial parameters of the derived class. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + """ + pass + + def _initialize_parameters(self, X, random_state): + """Initialize the model parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + random_state : RandomState + A random number generator instance that controls the random seed + used for the method chosen to initialize the parameters. + """ + n_samples, _ = X.shape + + if self.init_params == "kmeans": + resp = np.zeros((n_samples, self.n_components), dtype=X.dtype) + label = ( + cluster.KMeans( + n_clusters=self.n_components, n_init=1, random_state=random_state + ) + .fit(X) + .labels_ + ) + resp[np.arange(n_samples), label] = 1 + elif self.init_params == "random": + resp = np.asarray( + random_state.uniform(size=(n_samples, self.n_components)), dtype=X.dtype + ) + resp /= resp.sum(axis=1)[:, np.newaxis] + elif self.init_params == "random_from_data": + resp = np.zeros((n_samples, self.n_components), dtype=X.dtype) + 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), dtype=X.dtype) + _, indices = kmeans_plusplus( + X, + self.n_components, + random_state=random_state, + ) + resp[indices, np.arange(self.n_components)] = 1 + + self._initialize(X, resp) + + @abstractmethod + def _initialize(self, X, resp): + """Initialize the model parameters of the derived class. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + resp : array-like of shape (n_samples, n_components) + """ + pass + + def fit(self, X, y=None): + """Estimate model parameters with the EM algorithm. + + The method fits the model ``n_init`` times and sets the parameters with + which the model has the largest likelihood or lower bound. Within each + trial, the method iterates between E-step and M-step for ``max_iter`` + times until the change of likelihood or lower bound is less than + ``tol``, otherwise, a ``ConvergenceWarning`` is raised. + If ``warm_start`` is ``True``, then ``n_init`` is ignored and a single + initialization is performed upon the first call. Upon consecutive + calls, training starts where it left off. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : object + The fitted mixture. + """ + # parameters are validated in fit_predict + self.fit_predict(X, y) + return self + + @_fit_context(prefer_skip_nested_validation=True) + def fit_predict(self, X, y=None): + """Estimate model parameters using X and predict the labels for X. + + The method fits the model n_init times and sets the parameters with + which the model has the largest likelihood or lower bound. Within each + trial, the method iterates between E-step and M-step for `max_iter` + times until the change of likelihood or lower bound is less than + `tol`, otherwise, a :class:`~sklearn.exceptions.ConvergenceWarning` is + raised. After fitting, it predicts the most probable label for the + input data points. + + .. versionadded:: 0.20 + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + labels : array, shape (n_samples,) + Component labels. + """ + X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2) + if X.shape[0] < self.n_components: + raise ValueError( + "Expected n_samples >= n_components " + f"but got n_components = {self.n_components}, " + f"n_samples = {X.shape[0]}" + ) + self._check_parameters(X) + + # if we enable warm_start, we will have a unique initialisation + do_init = not (self.warm_start and hasattr(self, "converged_")) + n_init = self.n_init if do_init else 1 + + max_lower_bound = -np.inf + best_lower_bounds = [] + self.converged_ = False + + random_state = check_random_state(self.random_state) + + n_samples, _ = X.shape + for init in range(n_init): + self._print_verbose_msg_init_beg(init) + + if do_init: + self._initialize_parameters(X, random_state) + + lower_bound = -np.inf if do_init else self.lower_bound_ + current_lower_bounds = [] + + if self.max_iter == 0: + best_params = self._get_parameters() + best_n_iter = 0 + else: + converged = False + 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) + current_lower_bounds.append(lower_bound) + + change = lower_bound - prev_lower_bound + self._print_verbose_msg_iter_end(n_iter, change) + + if abs(change) < self.tol: + converged = True + break + + self._print_verbose_msg_init_end(lower_bound, converged) + + 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 + best_lower_bounds = current_lower_bounds + self.converged_ = 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( + ( + "Best performing initialization did not converge. " + "Try different init parameters, or increase max_iter, " + "tol, or check for degenerate data." + ), + ConvergenceWarning, + ) + + self._set_parameters(best_params) + self.n_iter_ = best_n_iter + self.lower_bound_ = max_lower_bound + self.lower_bounds_ = best_lower_bounds + + # Always do a final e-step to guarantee that the labels returned by + # fit_predict(X) are always consistent with fit(X).predict(X) + # for any value of max_iter and tol (and any random_state). + _, log_resp = self._e_step(X) + + return log_resp.argmax(axis=1) + + def _e_step(self, X): + """E step. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + Returns + ------- + log_prob_norm : float + Mean of the logarithms of the probabilities of each sample in X + + log_responsibility : array, shape (n_samples, n_components) + Logarithm of the posterior probabilities (or responsibilities) of + the point of each sample in X. + """ + log_prob_norm, log_resp = self._estimate_log_prob_resp(X) + return np.mean(log_prob_norm), log_resp + + @abstractmethod + def _m_step(self, X, log_resp): + """M step. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + log_resp : array-like of shape (n_samples, n_components) + Logarithm of the posterior probabilities (or responsibilities) of + the point of each sample in X. + """ + pass + + @abstractmethod + def _get_parameters(self): + pass + + @abstractmethod + def _set_parameters(self, params): + pass + + def score_samples(self, X): + """Compute the log-likelihood of each sample. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + Returns + ------- + log_prob : array, shape (n_samples,) + Log-likelihood of each sample in `X` under the current model. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False) + + return logsumexp(self._estimate_weighted_log_prob(X), axis=1) + + def score(self, X, y=None): + """Compute the per-sample average log-likelihood of the given data X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_dimensions) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + log_likelihood : float + Log-likelihood of `X` under the Gaussian mixture model. + """ + return self.score_samples(X).mean() + + def predict(self, X): + """Predict the labels for the data samples in X using trained model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + Returns + ------- + labels : array, shape (n_samples,) + Component labels. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False) + return self._estimate_weighted_log_prob(X).argmax(axis=1) + + def predict_proba(self, X): + """Evaluate the components' density for each sample. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + Returns + ------- + resp : array, shape (n_samples, n_components) + Density of each Gaussian component for each sample in X. + """ + check_is_fitted(self) + X = validate_data(self, X, reset=False) + _, log_resp = self._estimate_log_prob_resp(X) + return np.exp(log_resp) + + def sample(self, n_samples=1): + """Generate random samples from the fitted Gaussian distribution. + + Parameters + ---------- + n_samples : int, default=1 + Number of samples to generate. + + Returns + ------- + X : array, shape (n_samples, n_features) + Randomly generated sample. + + y : array, shape (nsamples,) + Component labels. + """ + check_is_fitted(self) + + if n_samples < 1: + raise ValueError( + "Invalid value for 'n_samples': %d . The sampling requires at " + "least one sample." % (self.n_components) + ) + + _, n_features = self.means_.shape + rng = check_random_state(self.random_state) + n_samples_comp = rng.multinomial(n_samples, self.weights_) + + if self.covariance_type == "full": + X = np.vstack( + [ + rng.multivariate_normal(mean, covariance, int(sample)) + for (mean, covariance, sample) in zip( + self.means_, self.covariances_, n_samples_comp + ) + ] + ) + elif self.covariance_type == "tied": + X = np.vstack( + [ + rng.multivariate_normal(mean, self.covariances_, int(sample)) + for (mean, sample) in zip(self.means_, n_samples_comp) + ] + ) + else: + X = np.vstack( + [ + mean + + rng.standard_normal(size=(sample, n_features)) + * np.sqrt(covariance) + for (mean, covariance, sample) in zip( + self.means_, self.covariances_, n_samples_comp + ) + ] + ) + + y = np.concatenate( + [np.full(sample, j, dtype=int) for j, sample in enumerate(n_samples_comp)] + ) + + return (X, y) + + def _estimate_weighted_log_prob(self, X): + """Estimate the weighted log-probabilities, log P(X | Z) + log weights. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + Returns + ------- + weighted_log_prob : array, shape (n_samples, n_component) + """ + return self._estimate_log_prob(X) + self._estimate_log_weights() + + @abstractmethod + def _estimate_log_weights(self): + """Estimate log-weights in EM algorithm, E[ log pi ] in VB algorithm. + + Returns + ------- + log_weight : array, shape (n_components, ) + """ + pass + + @abstractmethod + def _estimate_log_prob(self, X): + """Estimate the log-probabilities log P(X | Z). + + Compute the log-probabilities per each component for each sample. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + Returns + ------- + log_prob : array, shape (n_samples, n_component) + """ + pass + + def _estimate_log_prob_resp(self, X): + """Estimate log probabilities and responsibilities for each sample. + + Compute the log probabilities, weighted log probabilities per + component and responsibilities for each sample in X with respect to + the current state of the model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + Returns + ------- + log_prob_norm : array, shape (n_samples,) + log p(X) + + log_responsibilities : array, shape (n_samples, n_components) + logarithm of the responsibilities + """ + weighted_log_prob = self._estimate_weighted_log_prob(X) + log_prob_norm = logsumexp(weighted_log_prob, axis=1) + with np.errstate(under="ignore"): + # ignore underflow + log_resp = weighted_log_prob - log_prob_norm[:, np.newaxis] + return log_prob_norm, log_resp + + def _print_verbose_msg_init_beg(self, n_init): + """Print verbose message on initialization.""" + if self.verbose == 1: + print("Initialization %d" % n_init) + elif self.verbose >= 2: + print("Initialization %d" % n_init) + self._init_prev_time = time() + self._iter_prev_time = self._init_prev_time + + def _print_verbose_msg_iter_end(self, n_iter, diff_ll): + """Print verbose message on initialization.""" + if n_iter % self.verbose_interval == 0: + if self.verbose == 1: + print(" Iteration %d" % n_iter) + elif self.verbose >= 2: + cur_time = time() + print( + " Iteration %d\t time lapse %.5fs\t ll change %.5f" + % (n_iter, cur_time - self._iter_prev_time, diff_ll) + ) + self._iter_prev_time = cur_time + + def _print_verbose_msg_init_end(self, lb, init_has_converged): + """Print verbose message on the end of iteration.""" + converged_msg = "converged" if init_has_converged else "did not converge" + if self.verbose == 1: + print(f"Initialization {converged_msg}.") + elif self.verbose >= 2: + t = time() - self._init_prev_time + print( + f"Initialization {converged_msg}. time lapse {t:.5f}s\t lower bound" + f" {lb:.5f}." + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_bayesian_mixture.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_bayesian_mixture.py new file mode 100644 index 0000000000000000000000000000000000000000..57220186faf61694f0945a276bc60254ba861bd5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_bayesian_mixture.py @@ -0,0 +1,891 @@ +"""Bayesian Gaussian Mixture Model.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import math +from numbers import Real + +import numpy as np +from scipy.special import betaln, digamma, gammaln + +from ..utils import check_array +from ..utils._param_validation import Interval, StrOptions +from ._base import BaseMixture, _check_shape +from ._gaussian_mixture import ( + _check_precision_matrix, + _check_precision_positivity, + _compute_log_det_cholesky, + _compute_precision_cholesky, + _estimate_gaussian_parameters, + _estimate_log_gaussian_prob, +) + + +def _log_dirichlet_norm(dirichlet_concentration): + """Compute the log of the Dirichlet distribution normalization term. + + Parameters + ---------- + dirichlet_concentration : array-like of shape (n_samples,) + The parameters values of the Dirichlet distribution. + + Returns + ------- + log_dirichlet_norm : float + The log normalization of the Dirichlet distribution. + """ + return gammaln(np.sum(dirichlet_concentration)) - np.sum( + gammaln(dirichlet_concentration) + ) + + +def _log_wishart_norm(degrees_of_freedom, log_det_precisions_chol, n_features): + """Compute the log of the Wishart distribution normalization term. + + Parameters + ---------- + degrees_of_freedom : array-like of shape (n_components,) + The number of degrees of freedom on the covariance Wishart + distributions. + + log_det_precision_chol : array-like of shape (n_components,) + The determinant of the precision matrix for each component. + + n_features : int + The number of features. + + Return + ------ + log_wishart_norm : array-like of shape (n_components,) + The log normalization of the Wishart distribution. + """ + # To simplify the computation we have removed the np.log(np.pi) term + return -( + degrees_of_freedom * log_det_precisions_chol + + degrees_of_freedom * n_features * 0.5 * math.log(2.0) + + np.sum( + gammaln(0.5 * (degrees_of_freedom - np.arange(n_features)[:, np.newaxis])), + 0, + ) + ) + + +class BayesianGaussianMixture(BaseMixture): + """Variational Bayesian estimation of a Gaussian mixture. + + This class allows to infer an approximate posterior distribution over the + parameters of a Gaussian mixture distribution. The effective number of + components can be inferred from the data. + + This class implements two types of prior for the weights distribution: a + finite mixture model with Dirichlet distribution and an infinite mixture + model with the Dirichlet Process. In practice Dirichlet Process inference + algorithm is approximated and uses a truncated distribution with a fixed + maximum number of components (called the Stick-breaking representation). + The number of components actually used almost always depends on the data. + + .. versionadded:: 0.18 + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=1 + The number of mixture components. Depending on the data and the value + of the `weight_concentration_prior` the model can decide to not use + all the components by setting some component `weights_` to values very + close to zero. The number of effective components is therefore smaller + than n_components. + + covariance_type : {'full', 'tied', 'diag', 'spherical'}, default='full' + String describing the type of covariance parameters to use. + Must be one of: + + - 'full' (each component has its own general covariance matrix), + - 'tied' (all components share the same general covariance matrix), + - 'diag' (each component has its own diagonal covariance matrix), + - 'spherical' (each component has its own single variance). + + tol : float, default=1e-3 + The convergence threshold. EM iterations will stop when the + lower bound average gain on the likelihood (of the training data with + respect to the model) is below this threshold. + + reg_covar : float, default=1e-6 + Non-negative regularization added to the diagonal of covariance. + Allows to assure that the covariance matrices are all positive. + + max_iter : int, default=100 + The number of EM iterations to perform. + + n_init : int, default=1 + The number of initializations to perform. The result with the highest + lower bound value on the likelihood is kept. + + init_params : {'kmeans', 'k-means++', 'random', 'random_from_data'}, \ + default='kmeans' + The method used to initialize the weights, the means and the + covariances. 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 : {'dirichlet_process', 'dirichlet_distribution'}, \ + default='dirichlet_process' + String describing the type of the weight concentration prior. + + weight_concentration_prior : float or None, default=None + The dirichlet concentration of each component on the weight + distribution (Dirichlet). This is commonly called gamma in the + literature. The higher concentration puts more mass in + the center and will lead to more components being active, while a lower + concentration parameter will lead to more mass at the edge of the + mixture weights simplex. The value of the parameter must be greater + than 0. If it is None, it's set to ``1. / n_components``. + + mean_precision_prior : float or None, default=None + The precision prior on the mean distribution (Gaussian). + Controls the extent of where means can be placed. Larger + values concentrate the cluster means around `mean_prior`. + The value of the parameter must be greater than 0. + If it is None, it is set to 1. + + mean_prior : array-like, shape (n_features,), default=None + The prior on the mean distribution (Gaussian). + If it is None, it is set to the mean of X. + + degrees_of_freedom_prior : float or None, default=None + The prior of the number of degrees of freedom on the covariance + distributions (Wishart). If it is None, it's set to `n_features`. + + covariance_prior : float or array-like, default=None + The prior on the covariance distribution (Wishart). + If it is None, the emiprical covariance prior is initialized using the + covariance of X. The shape depends on `covariance_type`:: + + (n_features, n_features) if 'full', + (n_features, n_features) if 'tied', + (n_features) if 'diag', + float if 'spherical' + + random_state : int, RandomState instance or None, default=None + Controls the random seed given to the method chosen to initialize the + parameters (see `init_params`). + In addition, it controls the generation of random samples from the + fitted distribution (see the method `sample`). + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + If 'warm_start' is True, the solution of the last fitting is used as + initialization for the next call of fit(). This can speed up + convergence when fit is called several times on similar problems. + See :term:`the Glossary `. + + verbose : int, default=0 + Enable verbose output. If 1 then it prints the current + initialization and each iteration step. If greater than 1 then + it prints also the log probability and the time needed + for each step. + + verbose_interval : int, default=10 + Number of iteration done before the next print. + + Attributes + ---------- + weights_ : array-like of shape (n_components,) + The weights of each mixture components. + + means_ : array-like of shape (n_components, n_features) + The mean of each mixture component. + + covariances_ : array-like + The covariance of each mixture component. + The shape depends on `covariance_type`:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + precisions_ : array-like + The precision matrices for each component in the mixture. A precision + matrix is the inverse of a covariance matrix. A covariance matrix is + symmetric positive definite so the mixture of Gaussian can be + equivalently parameterized by the precision matrices. Storing the + precision matrices instead of the covariance matrices makes it more + efficient to compute the log-likelihood of new samples at test time. + The shape depends on ``covariance_type``:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + precisions_cholesky_ : array-like + The cholesky decomposition of the precision matrices of each mixture + component. A precision matrix is the inverse of a covariance matrix. + A covariance matrix is symmetric positive definite so the mixture of + Gaussian can be equivalently parameterized by the precision matrices. + Storing the precision matrices instead of the covariance matrices makes + it more efficient to compute the log-likelihood of new samples at test + time. The shape depends on ``covariance_type``:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + converged_ : bool + True when convergence of the best fit of inference was reached, False otherwise. + + n_iter_ : int + Number of step used by the best fit of inference to reach the + convergence. + + lower_bound_ : float + Lower bound value on the model evidence (of the training data) of the + best fit of inference. + + lower_bounds_ : array-like of shape (`n_iter_`,) + The list of lower bound values on the model evidence from each iteration + of the best fit of inference. + + weight_concentration_prior_ : tuple or float + The dirichlet concentration of each component on the weight + distribution (Dirichlet). The type depends on + ``weight_concentration_prior_type``:: + + (float, float) if 'dirichlet_process' (Beta parameters), + float if 'dirichlet_distribution' (Dirichlet parameters). + + The higher concentration puts more mass in + the center and will lead to more components being active, while a lower + concentration parameter will lead to more mass at the edge of the + simplex. + + weight_concentration_ : array-like of shape (n_components,) + The dirichlet concentration of each component on the weight + distribution (Dirichlet). + + mean_precision_prior_ : float + The precision prior on the mean distribution (Gaussian). + Controls the extent of where means can be placed. + Larger values concentrate the cluster means around `mean_prior`. + If mean_precision_prior is set to None, `mean_precision_prior_` is set + to 1. + + mean_precision_ : array-like of shape (n_components,) + The precision of each components on the mean distribution (Gaussian). + + mean_prior_ : array-like of shape (n_features,) + The prior on the mean distribution (Gaussian). + + degrees_of_freedom_prior_ : float + The prior of the number of degrees of freedom on the covariance + distributions (Wishart). + + degrees_of_freedom_ : array-like of shape (n_components,) + The number of degrees of freedom of each components in the model. + + covariance_prior_ : float or array-like + The prior on the covariance distribution (Wishart). + The shape depends on `covariance_type`:: + + (n_features, n_features) if 'full', + (n_features, n_features) if 'tied', + (n_features) if 'diag', + float if 'spherical' + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + GaussianMixture : Finite Gaussian mixture fit with EM. + + References + ---------- + + .. [1] `Bishop, Christopher M. (2006). "Pattern recognition and machine + learning". Vol. 4 No. 4. New York: Springer. + `_ + + .. [2] `Hagai Attias. (2000). "A Variational Bayesian Framework for + Graphical Models". In Advances in Neural Information Processing + Systems 12. + `_ + + .. [3] `Blei, David M. and Michael I. Jordan. (2006). "Variational + inference for Dirichlet process mixtures". Bayesian analysis 1.1 + `_ + + Examples + -------- + >>> import numpy as np + >>> from sklearn.mixture import BayesianGaussianMixture + >>> X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [12, 4], [10, 7]]) + >>> bgm = BayesianGaussianMixture(n_components=2, random_state=42).fit(X) + >>> bgm.means_ + array([[2.49 , 2.29], + [8.45, 4.52 ]]) + >>> bgm.predict([[0, 0], [9, 3]]) + array([0, 1]) + """ + + _parameter_constraints: dict = { + **BaseMixture._parameter_constraints, + "covariance_type": [StrOptions({"spherical", "tied", "diag", "full"})], + "weight_concentration_prior_type": [ + StrOptions({"dirichlet_process", "dirichlet_distribution"}) + ], + "weight_concentration_prior": [ + None, + Interval(Real, 0.0, None, closed="neither"), + ], + "mean_precision_prior": [None, Interval(Real, 0.0, None, closed="neither")], + "mean_prior": [None, "array-like"], + "degrees_of_freedom_prior": [None, Interval(Real, 0.0, None, closed="neither")], + "covariance_prior": [ + None, + "array-like", + Interval(Real, 0.0, None, closed="neither"), + ], + } + + def __init__( + self, + *, + n_components=1, + covariance_type="full", + tol=1e-3, + reg_covar=1e-6, + max_iter=100, + n_init=1, + init_params="kmeans", + weight_concentration_prior_type="dirichlet_process", + weight_concentration_prior=None, + mean_precision_prior=None, + mean_prior=None, + degrees_of_freedom_prior=None, + covariance_prior=None, + random_state=None, + warm_start=False, + verbose=0, + verbose_interval=10, + ): + super().__init__( + n_components=n_components, + tol=tol, + reg_covar=reg_covar, + max_iter=max_iter, + n_init=n_init, + init_params=init_params, + random_state=random_state, + warm_start=warm_start, + verbose=verbose, + verbose_interval=verbose_interval, + ) + + self.covariance_type = covariance_type + self.weight_concentration_prior_type = weight_concentration_prior_type + self.weight_concentration_prior = weight_concentration_prior + self.mean_precision_prior = mean_precision_prior + self.mean_prior = mean_prior + self.degrees_of_freedom_prior = degrees_of_freedom_prior + self.covariance_prior = covariance_prior + + def _check_parameters(self, X): + """Check that the parameters are well defined. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + """ + self._check_weights_parameters() + self._check_means_parameters(X) + self._check_precision_parameters(X) + self._checkcovariance_prior_parameter(X) + + def _check_weights_parameters(self): + """Check the parameter of the Dirichlet distribution.""" + if self.weight_concentration_prior is None: + self.weight_concentration_prior_ = 1.0 / self.n_components + else: + self.weight_concentration_prior_ = self.weight_concentration_prior + + def _check_means_parameters(self, X): + """Check the parameters of the Gaussian distribution. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + """ + _, n_features = X.shape + + if self.mean_precision_prior is None: + self.mean_precision_prior_ = 1.0 + else: + self.mean_precision_prior_ = self.mean_precision_prior + + if self.mean_prior is None: + self.mean_prior_ = X.mean(axis=0) + else: + self.mean_prior_ = check_array( + self.mean_prior, dtype=[np.float64, np.float32], ensure_2d=False + ) + _check_shape(self.mean_prior_, (n_features,), "means") + + def _check_precision_parameters(self, X): + """Check the prior parameters of the precision distribution. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + """ + _, n_features = X.shape + + if self.degrees_of_freedom_prior is None: + self.degrees_of_freedom_prior_ = n_features + elif self.degrees_of_freedom_prior > n_features - 1.0: + self.degrees_of_freedom_prior_ = self.degrees_of_freedom_prior + else: + raise ValueError( + "The parameter 'degrees_of_freedom_prior' " + "should be greater than %d, but got %.3f." + % (n_features - 1, self.degrees_of_freedom_prior) + ) + + def _checkcovariance_prior_parameter(self, X): + """Check the `covariance_prior_`. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + """ + _, n_features = X.shape + + if self.covariance_prior is None: + self.covariance_prior_ = { + "full": np.atleast_2d(np.cov(X.T)), + "tied": np.atleast_2d(np.cov(X.T)), + "diag": np.var(X, axis=0, ddof=1), + "spherical": np.var(X, axis=0, ddof=1).mean(), + }[self.covariance_type] + + elif self.covariance_type in ["full", "tied"]: + self.covariance_prior_ = check_array( + self.covariance_prior, dtype=[np.float64, np.float32], ensure_2d=False + ) + _check_shape( + self.covariance_prior_, + (n_features, n_features), + "%s covariance_prior" % self.covariance_type, + ) + _check_precision_matrix(self.covariance_prior_, self.covariance_type) + elif self.covariance_type == "diag": + self.covariance_prior_ = check_array( + self.covariance_prior, dtype=[np.float64, np.float32], ensure_2d=False + ) + _check_shape( + self.covariance_prior_, + (n_features,), + "%s covariance_prior" % self.covariance_type, + ) + _check_precision_positivity(self.covariance_prior_, self.covariance_type) + # spherical case + else: + self.covariance_prior_ = self.covariance_prior + + def _initialize(self, X, resp): + """Initialization of the mixture parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + resp : array-like of shape (n_samples, n_components) + """ + nk, xk, sk = _estimate_gaussian_parameters( + X, resp, self.reg_covar, self.covariance_type + ) + + self._estimate_weights(nk) + self._estimate_means(nk, xk) + self._estimate_precisions(nk, xk, sk) + + def _estimate_weights(self, nk): + """Estimate the parameters of the Dirichlet distribution. + + Parameters + ---------- + nk : array-like of shape (n_components,) + """ + if self.weight_concentration_prior_type == "dirichlet_process": + # For dirichlet process weight_concentration will be a tuple + # containing the two parameters of the beta distribution + self.weight_concentration_ = ( + 1.0 + nk, + ( + self.weight_concentration_prior_ + + np.hstack((np.cumsum(nk[::-1])[-2::-1], 0)) + ), + ) + else: + # case Variational Gaussian mixture with dirichlet distribution + self.weight_concentration_ = self.weight_concentration_prior_ + nk + + def _estimate_means(self, nk, xk): + """Estimate the parameters of the Gaussian distribution. + + Parameters + ---------- + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + """ + self.mean_precision_ = self.mean_precision_prior_ + nk + self.means_ = ( + self.mean_precision_prior_ * self.mean_prior_ + nk[:, np.newaxis] * xk + ) / self.mean_precision_[:, np.newaxis] + + def _estimate_precisions(self, nk, xk, sk): + """Estimate the precisions parameters of the precision distribution. + + Parameters + ---------- + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + + sk : array-like + The shape depends of `covariance_type`: + 'full' : (n_components, n_features, n_features) + 'tied' : (n_features, n_features) + 'diag' : (n_components, n_features) + 'spherical' : (n_components,) + """ + { + "full": self._estimate_wishart_full, + "tied": self._estimate_wishart_tied, + "diag": self._estimate_wishart_diag, + "spherical": self._estimate_wishart_spherical, + }[self.covariance_type](nk, xk, sk) + + self.precisions_cholesky_ = _compute_precision_cholesky( + self.covariances_, self.covariance_type + ) + + def _estimate_wishart_full(self, nk, xk, sk): + """Estimate the full Wishart distribution parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + + sk : array-like of shape (n_components, n_features, n_features) + """ + _, n_features = xk.shape + + # Warning : in some Bishop book, there is a typo on the formula 10.63 + # `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` is + # the correct formula + self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk + + self.covariances_ = np.empty((self.n_components, n_features, n_features)) + + for k in range(self.n_components): + diff = xk[k] - self.mean_prior_ + self.covariances_[k] = ( + self.covariance_prior_ + + nk[k] * sk[k] + + nk[k] + * self.mean_precision_prior_ + / self.mean_precision_[k] + * np.outer(diff, diff) + ) + + # Contrary to the original bishop book, we normalize the covariances + self.covariances_ /= self.degrees_of_freedom_[:, np.newaxis, np.newaxis] + + def _estimate_wishart_tied(self, nk, xk, sk): + """Estimate the tied Wishart distribution parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + + sk : array-like of shape (n_features, n_features) + """ + _, n_features = xk.shape + + # Warning : in some Bishop book, there is a typo on the formula 10.63 + # `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` + # is the correct formula + self.degrees_of_freedom_ = ( + self.degrees_of_freedom_prior_ + nk.sum() / self.n_components + ) + + diff = xk - self.mean_prior_ + self.covariances_ = ( + self.covariance_prior_ + + sk * nk.sum() / self.n_components + + self.mean_precision_prior_ + / self.n_components + * np.dot((nk / self.mean_precision_) * diff.T, diff) + ) + + # Contrary to the original bishop book, we normalize the covariances + self.covariances_ /= self.degrees_of_freedom_ + + def _estimate_wishart_diag(self, nk, xk, sk): + """Estimate the diag Wishart distribution parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + + sk : array-like of shape (n_components, n_features) + """ + _, n_features = xk.shape + + # Warning : in some Bishop book, there is a typo on the formula 10.63 + # `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` + # is the correct formula + self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk + + diff = xk - self.mean_prior_ + self.covariances_ = self.covariance_prior_ + nk[:, np.newaxis] * ( + sk + + (self.mean_precision_prior_ / self.mean_precision_)[:, np.newaxis] + * np.square(diff) + ) + + # Contrary to the original bishop book, we normalize the covariances + self.covariances_ /= self.degrees_of_freedom_[:, np.newaxis] + + def _estimate_wishart_spherical(self, nk, xk, sk): + """Estimate the spherical Wishart distribution parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + xk : array-like of shape (n_components, n_features) + + sk : array-like of shape (n_components,) + """ + _, n_features = xk.shape + + # Warning : in some Bishop book, there is a typo on the formula 10.63 + # `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` + # is the correct formula + self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk + + diff = xk - self.mean_prior_ + self.covariances_ = self.covariance_prior_ + nk * ( + sk + + self.mean_precision_prior_ + / self.mean_precision_ + * np.mean(np.square(diff), 1) + ) + + # Contrary to the original bishop book, we normalize the covariances + self.covariances_ /= self.degrees_of_freedom_ + + def _m_step(self, X, log_resp): + """M step. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + log_resp : array-like of shape (n_samples, n_components) + Logarithm of the posterior probabilities (or responsibilities) of + the point of each sample in X. + """ + n_samples, _ = X.shape + + nk, xk, sk = _estimate_gaussian_parameters( + X, np.exp(log_resp), self.reg_covar, self.covariance_type + ) + self._estimate_weights(nk) + self._estimate_means(nk, xk) + self._estimate_precisions(nk, xk, sk) + + def _estimate_log_weights(self): + if self.weight_concentration_prior_type == "dirichlet_process": + digamma_sum = digamma( + self.weight_concentration_[0] + self.weight_concentration_[1] + ) + digamma_a = digamma(self.weight_concentration_[0]) + digamma_b = digamma(self.weight_concentration_[1]) + return ( + digamma_a + - digamma_sum + + np.hstack((0, np.cumsum(digamma_b - digamma_sum)[:-1])) + ) + else: + # case Variational Gaussian mixture with dirichlet distribution + return digamma(self.weight_concentration_) - digamma( + np.sum(self.weight_concentration_) + ) + + def _estimate_log_prob(self, X): + _, n_features = X.shape + # We remove `n_features * np.log(self.degrees_of_freedom_)` because + # the precision matrix is normalized + log_gauss = _estimate_log_gaussian_prob( + X, self.means_, self.precisions_cholesky_, self.covariance_type + ) - 0.5 * n_features * np.log(self.degrees_of_freedom_) + + log_lambda = n_features * np.log(2.0) + np.sum( + digamma( + 0.5 + * (self.degrees_of_freedom_ - np.arange(0, n_features)[:, np.newaxis]) + ), + 0, + ) + + return log_gauss + 0.5 * (log_lambda - n_features / self.mean_precision_) + + def _compute_lower_bound(self, log_resp, log_prob_norm): + """Estimate the lower bound of the model. + + The lower bound on the likelihood (of the training data with respect to + the model) is used to detect the convergence and has to increase at + each iteration. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + log_resp : array, shape (n_samples, n_components) + Logarithm of the posterior probabilities (or responsibilities) of + the point of each sample in X. + + log_prob_norm : float + Logarithm of the probability of each sample in X. + + Returns + ------- + lower_bound : float + """ + # Contrary to the original formula, we have done some simplification + # and removed all the constant terms. + (n_features,) = self.mean_prior_.shape + + # We removed `.5 * n_features * np.log(self.degrees_of_freedom_)` + # because the precision matrix is normalized. + log_det_precisions_chol = _compute_log_det_cholesky( + self.precisions_cholesky_, self.covariance_type, n_features + ) - 0.5 * n_features * np.log(self.degrees_of_freedom_) + + if self.covariance_type == "tied": + log_wishart = self.n_components * np.float64( + _log_wishart_norm( + self.degrees_of_freedom_, log_det_precisions_chol, n_features + ) + ) + else: + log_wishart = np.sum( + _log_wishart_norm( + self.degrees_of_freedom_, log_det_precisions_chol, n_features + ) + ) + + if self.weight_concentration_prior_type == "dirichlet_process": + log_norm_weight = -np.sum( + betaln(self.weight_concentration_[0], self.weight_concentration_[1]) + ) + else: + log_norm_weight = _log_dirichlet_norm(self.weight_concentration_) + + return ( + -np.sum(np.exp(log_resp) * log_resp) + - log_wishart + - log_norm_weight + - 0.5 * n_features * np.sum(np.log(self.mean_precision_)) + ) + + def _get_parameters(self): + return ( + self.weight_concentration_, + self.mean_precision_, + self.means_, + self.degrees_of_freedom_, + self.covariances_, + self.precisions_cholesky_, + ) + + def _set_parameters(self, params): + ( + self.weight_concentration_, + self.mean_precision_, + self.means_, + self.degrees_of_freedom_, + self.covariances_, + self.precisions_cholesky_, + ) = params + + # Weights computation + if self.weight_concentration_prior_type == "dirichlet_process": + weight_dirichlet_sum = ( + self.weight_concentration_[0] + self.weight_concentration_[1] + ) + tmp = self.weight_concentration_[1] / weight_dirichlet_sum + self.weights_ = ( + self.weight_concentration_[0] + / weight_dirichlet_sum + * np.hstack((1, np.cumprod(tmp[:-1]))) + ) + self.weights_ /= np.sum(self.weights_) + else: + self.weights_ = self.weight_concentration_ / np.sum( + self.weight_concentration_ + ) + + # Precisions matrices computation + if self.covariance_type == "full": + self.precisions_ = np.array( + [ + np.dot(prec_chol, prec_chol.T) + for prec_chol in self.precisions_cholesky_ + ] + ) + + elif self.covariance_type == "tied": + self.precisions_ = np.dot( + self.precisions_cholesky_, self.precisions_cholesky_.T + ) + else: + self.precisions_ = self.precisions_cholesky_**2 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_gaussian_mixture.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_gaussian_mixture.py new file mode 100644 index 0000000000000000000000000000000000000000..c4bdd3a0d68c81c73bcf6d606cf09bdd52aff66c --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/_gaussian_mixture.py @@ -0,0 +1,934 @@ +"""Gaussian Mixture Model.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +from scipy import linalg + +from ..utils import check_array +from ..utils._param_validation import StrOptions +from ..utils.extmath import row_norms +from ._base import BaseMixture, _check_shape + +############################################################################### +# Gaussian mixture shape checkers used by the GaussianMixture class + + +def _check_weights(weights, n_components): + """Check the user provided 'weights'. + + Parameters + ---------- + weights : array-like of shape (n_components,) + The proportions of components of each mixture. + + n_components : int + Number of components. + + Returns + ------- + weights : array, shape (n_components,) + """ + weights = check_array(weights, dtype=[np.float64, np.float32], ensure_2d=False) + _check_shape(weights, (n_components,), "weights") + + # check range + if any(np.less(weights, 0.0)) or any(np.greater(weights, 1.0)): + raise ValueError( + "The parameter 'weights' should be in the range " + "[0, 1], but got max value %.5f, min value %.5f" + % (np.min(weights), np.max(weights)) + ) + + # check normalization + atol = 1e-6 if weights.dtype == np.float32 else 1e-8 + if not np.allclose(np.abs(1.0 - np.sum(weights)), 0.0, atol=atol): + raise ValueError( + "The parameter 'weights' should be normalized, but got sum(weights) = %.5f" + % np.sum(weights) + ) + return weights + + +def _check_means(means, n_components, n_features): + """Validate the provided 'means'. + + Parameters + ---------- + means : array-like of shape (n_components, n_features) + The centers of the current components. + + n_components : int + Number of components. + + n_features : int + Number of features. + + Returns + ------- + means : array, (n_components, n_features) + """ + means = check_array(means, dtype=[np.float64, np.float32], ensure_2d=False) + _check_shape(means, (n_components, n_features), "means") + return means + + +def _check_precision_positivity(precision, covariance_type): + """Check a precision vector is positive-definite.""" + if np.any(np.less_equal(precision, 0.0)): + raise ValueError("'%s precision' should be positive" % covariance_type) + + +def _check_precision_matrix(precision, covariance_type): + """Check a precision matrix is symmetric and positive-definite.""" + if not ( + np.allclose(precision, precision.T) and np.all(linalg.eigvalsh(precision) > 0.0) + ): + raise ValueError( + "'%s precision' should be symmetric, positive-definite" % covariance_type + ) + + +def _check_precisions_full(precisions, covariance_type): + """Check the precision matrices are symmetric and positive-definite.""" + for prec in precisions: + _check_precision_matrix(prec, covariance_type) + + +def _check_precisions(precisions, covariance_type, n_components, n_features): + """Validate user provided precisions. + + Parameters + ---------- + precisions : array-like + 'full' : shape of (n_components, n_features, n_features) + 'tied' : shape of (n_features, n_features) + 'diag' : shape of (n_components, n_features) + 'spherical' : shape of (n_components,) + + covariance_type : str + + n_components : int + Number of components. + + n_features : int + Number of features. + + Returns + ------- + precisions : array + """ + precisions = check_array( + precisions, + dtype=[np.float64, np.float32], + ensure_2d=False, + allow_nd=covariance_type == "full", + ) + + precisions_shape = { + "full": (n_components, n_features, n_features), + "tied": (n_features, n_features), + "diag": (n_components, n_features), + "spherical": (n_components,), + } + _check_shape( + precisions, precisions_shape[covariance_type], "%s precision" % covariance_type + ) + + _check_precisions = { + "full": _check_precisions_full, + "tied": _check_precision_matrix, + "diag": _check_precision_positivity, + "spherical": _check_precision_positivity, + } + _check_precisions[covariance_type](precisions, covariance_type) + return precisions + + +############################################################################### +# Gaussian mixture parameters estimators (used by the M-Step) + + +def _estimate_gaussian_covariances_full(resp, X, nk, means, reg_covar): + """Estimate the full covariance matrices. + + Parameters + ---------- + resp : array-like of shape (n_samples, n_components) + + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + means : array-like of shape (n_components, n_features) + + reg_covar : float + + Returns + ------- + covariances : array, shape (n_components, n_features, n_features) + The covariance matrix of the current components. + """ + n_components, n_features = means.shape + covariances = np.empty((n_components, n_features, n_features), dtype=X.dtype) + for k in range(n_components): + diff = X - means[k] + covariances[k] = np.dot(resp[:, k] * diff.T, diff) / nk[k] + covariances[k].flat[:: n_features + 1] += reg_covar + return covariances + + +def _estimate_gaussian_covariances_tied(resp, X, nk, means, reg_covar): + """Estimate the tied covariance matrix. + + Parameters + ---------- + resp : array-like of shape (n_samples, n_components) + + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + means : array-like of shape (n_components, n_features) + + reg_covar : float + + Returns + ------- + covariance : array, shape (n_features, n_features) + The tied covariance matrix of the components. + """ + avg_X2 = np.dot(X.T, X) + avg_means2 = np.dot(nk * means.T, means) + covariance = avg_X2 - avg_means2 + covariance /= nk.sum() + covariance.flat[:: len(covariance) + 1] += reg_covar + return covariance + + +def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar): + """Estimate the diagonal covariance vectors. + + Parameters + ---------- + responsibilities : array-like of shape (n_samples, n_components) + + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + means : array-like of shape (n_components, n_features) + + reg_covar : float + + Returns + ------- + covariances : array, shape (n_components, n_features) + The covariance vector of the current components. + """ + avg_X2 = np.dot(resp.T, X * X) / nk[:, np.newaxis] + avg_means2 = means**2 + return avg_X2 - avg_means2 + reg_covar + + +def _estimate_gaussian_covariances_spherical(resp, X, nk, means, reg_covar): + """Estimate the spherical variance values. + + Parameters + ---------- + responsibilities : array-like of shape (n_samples, n_components) + + X : array-like of shape (n_samples, n_features) + + nk : array-like of shape (n_components,) + + means : array-like of shape (n_components, n_features) + + reg_covar : float + + Returns + ------- + variances : array, shape (n_components,) + The variance values of each components. + """ + return _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar).mean(1) + + +def _estimate_gaussian_parameters(X, resp, reg_covar, covariance_type): + """Estimate the Gaussian distribution parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The input data array. + + resp : array-like of shape (n_samples, n_components) + The responsibilities for each data sample in X. + + reg_covar : float + The regularization added to the diagonal of the covariance matrices. + + covariance_type : {'full', 'tied', 'diag', 'spherical'} + The type of precision matrices. + + Returns + ------- + nk : array-like of shape (n_components,) + The numbers of data samples in the current components. + + means : array-like of shape (n_components, n_features) + The centers of the current components. + + covariances : array-like + The covariance matrix of the current components. + The shape depends of the covariance_type. + """ + nk = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps + means = np.dot(resp.T, X) / nk[:, np.newaxis] + covariances = { + "full": _estimate_gaussian_covariances_full, + "tied": _estimate_gaussian_covariances_tied, + "diag": _estimate_gaussian_covariances_diag, + "spherical": _estimate_gaussian_covariances_spherical, + }[covariance_type](resp, X, nk, means, reg_covar) + return nk, means, covariances + + +def _compute_precision_cholesky(covariances, covariance_type): + """Compute the Cholesky decomposition of the precisions. + + Parameters + ---------- + covariances : array-like + The covariance matrix of the current components. + The shape depends of the covariance_type. + + covariance_type : {'full', 'tied', 'diag', 'spherical'} + The type of precision matrices. + + Returns + ------- + precisions_cholesky : array-like + The cholesky decomposition of sample precisions of the current + components. The shape depends of the covariance_type. + """ + estimate_precision_error_message = ( + "Fitting the mixture model failed because some components have " + "ill-defined empirical covariance (for instance caused by singleton " + "or collapsed samples). Try to decrease the number of components, " + "increase reg_covar, or scale the input data." + ) + dtype = covariances.dtype + if dtype == np.float32: + estimate_precision_error_message += ( + " The numerical accuracy can also be improved by passing float64" + " data instead of float32." + ) + + if covariance_type == "full": + n_components, n_features, _ = covariances.shape + precisions_chol = np.empty((n_components, n_features, n_features), dtype=dtype) + for k, covariance in enumerate(covariances): + try: + cov_chol = linalg.cholesky(covariance, lower=True) + except linalg.LinAlgError: + raise ValueError(estimate_precision_error_message) + precisions_chol[k] = linalg.solve_triangular( + cov_chol, np.eye(n_features, dtype=dtype), lower=True + ).T + elif covariance_type == "tied": + _, n_features = covariances.shape + try: + cov_chol = linalg.cholesky(covariances, lower=True) + except linalg.LinAlgError: + raise ValueError(estimate_precision_error_message) + precisions_chol = linalg.solve_triangular( + cov_chol, np.eye(n_features, dtype=dtype), lower=True + ).T + else: + if np.any(np.less_equal(covariances, 0.0)): + raise ValueError(estimate_precision_error_message) + precisions_chol = 1.0 / np.sqrt(covariances) + return precisions_chol + + +def _flipudlr(array): + """Reverse the rows and columns of an array.""" + return np.flipud(np.fliplr(array)) + + +def _compute_precision_cholesky_from_precisions(precisions, covariance_type): + r"""Compute the Cholesky decomposition of precisions using precisions themselves. + + As implemented in :func:`_compute_precision_cholesky`, the `precisions_cholesky_` is + an upper-triangular matrix for each Gaussian component, which can be expressed as + the $UU^T$ factorization of the precision matrix for each Gaussian component, where + $U$ is an upper-triangular matrix. + + In order to use the Cholesky decomposition to get $UU^T$, the precision matrix + $\Lambda$ needs to be permutated such that its rows and columns are reversed, which + can be done by applying a similarity transformation with an exchange matrix $J$, + where the 1 elements reside on the anti-diagonal and all other elements are 0. In + particular, the Cholesky decomposition of the transformed precision matrix is + $J\Lambda J=LL^T$, where $L$ is a lower-triangular matrix. Because $\Lambda=UU^T$ + and $J=J^{-1}=J^T$, the `precisions_cholesky_` for each Gaussian component can be + expressed as $JLJ$. + + Refer to #26415 for details. + + Parameters + ---------- + precisions : array-like + The precision matrix of the current components. + The shape depends on the covariance_type. + + covariance_type : {'full', 'tied', 'diag', 'spherical'} + The type of precision matrices. + + Returns + ------- + precisions_cholesky : array-like + The cholesky decomposition of sample precisions of the current + components. The shape depends on the covariance_type. + """ + if covariance_type == "full": + precisions_cholesky = np.array( + [ + _flipudlr(linalg.cholesky(_flipudlr(precision), lower=True)) + for precision in precisions + ] + ) + elif covariance_type == "tied": + precisions_cholesky = _flipudlr( + linalg.cholesky(_flipudlr(precisions), lower=True) + ) + else: + precisions_cholesky = np.sqrt(precisions) + return precisions_cholesky + + +############################################################################### +# Gaussian mixture probability estimators +def _compute_log_det_cholesky(matrix_chol, covariance_type, n_features): + """Compute the log-det of the cholesky decomposition of matrices. + + Parameters + ---------- + matrix_chol : array-like + Cholesky decompositions of the matrices. + 'full' : shape of (n_components, n_features, n_features) + 'tied' : shape of (n_features, n_features) + 'diag' : shape of (n_components, n_features) + 'spherical' : shape of (n_components,) + + covariance_type : {'full', 'tied', 'diag', 'spherical'} + + n_features : int + Number of features. + + Returns + ------- + log_det_precision_chol : array-like of shape (n_components,) + The determinant of the precision matrix for each component. + """ + if covariance_type == "full": + n_components, _, _ = matrix_chol.shape + log_det_chol = np.sum( + np.log(matrix_chol.reshape(n_components, -1)[:, :: n_features + 1]), axis=1 + ) + + elif covariance_type == "tied": + log_det_chol = np.sum(np.log(np.diag(matrix_chol))) + + elif covariance_type == "diag": + log_det_chol = np.sum(np.log(matrix_chol), axis=1) + + else: + log_det_chol = n_features * np.log(matrix_chol) + + return log_det_chol + + +def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type): + """Estimate the log Gaussian probability. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + means : array-like of shape (n_components, n_features) + + precisions_chol : array-like + Cholesky decompositions of the precision matrices. + 'full' : shape of (n_components, n_features, n_features) + 'tied' : shape of (n_features, n_features) + 'diag' : shape of (n_components, n_features) + 'spherical' : shape of (n_components,) + + covariance_type : {'full', 'tied', 'diag', 'spherical'} + + Returns + ------- + log_prob : array, shape (n_samples, n_components) + """ + n_samples, n_features = X.shape + n_components, _ = means.shape + # The determinant of the precision matrix from the Cholesky decomposition + # corresponds to the negative half of the determinant of the full precision + # matrix. + # In short: det(precision_chol) = - det(precision) / 2 + log_det = _compute_log_det_cholesky(precisions_chol, covariance_type, n_features) + + if covariance_type == "full": + log_prob = np.empty((n_samples, n_components), dtype=X.dtype) + for k, (mu, prec_chol) in enumerate(zip(means, precisions_chol)): + y = np.dot(X, prec_chol) - np.dot(mu, prec_chol) + log_prob[:, k] = np.sum(np.square(y), axis=1) + + elif covariance_type == "tied": + log_prob = np.empty((n_samples, n_components), dtype=X.dtype) + for k, mu in enumerate(means): + y = np.dot(X, precisions_chol) - np.dot(mu, precisions_chol) + log_prob[:, k] = np.sum(np.square(y), axis=1) + + elif covariance_type == "diag": + precisions = precisions_chol**2 + log_prob = ( + np.sum((means**2 * precisions), 1) + - 2.0 * np.dot(X, (means * precisions).T) + + np.dot(X**2, precisions.T) + ) + + elif covariance_type == "spherical": + precisions = precisions_chol**2 + log_prob = ( + np.sum(means**2, 1) * precisions + - 2 * np.dot(X, means.T * precisions) + + np.outer(row_norms(X, squared=True), precisions) + ) + # Since we are using the precision of the Cholesky decomposition, + # `- 0.5 * log_det_precision` becomes `+ log_det_precision_chol` + return -0.5 * (n_features * np.log(2 * np.pi).astype(X.dtype) + log_prob) + log_det + + +class GaussianMixture(BaseMixture): + """Gaussian Mixture. + + Representation of a Gaussian mixture model probability distribution. + This class allows to estimate the parameters of a Gaussian mixture + distribution. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.18 + + Parameters + ---------- + n_components : int, default=1 + The number of mixture components. + + covariance_type : {'full', 'tied', 'diag', 'spherical'}, default='full' + String describing the type of covariance parameters to use. + Must be one of: + + - 'full': each component has its own general covariance matrix. + - 'tied': all components share the same general covariance matrix. + - 'diag': each component has its own diagonal covariance matrix. + - 'spherical': each component has its own single variance. + + For an example of using `covariance_type`, refer to + :ref:`sphx_glr_auto_examples_mixture_plot_gmm_selection.py`. + + tol : float, default=1e-3 + The convergence threshold. EM iterations will stop when the + lower bound average gain is below this threshold. + + reg_covar : float, default=1e-6 + Non-negative regularization added to the diagonal of covariance. + Allows to assure that the covariance matrices are all positive. + + max_iter : int, default=100 + The number of EM iterations to perform. + + n_init : int, default=1 + The number of initializations to perform. The best results are kept. + + init_params : {'kmeans', 'k-means++', 'random', 'random_from_data'}, \ + default='kmeans' + The method used to initialize the weights, the means and the + precisions. + 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. + + weights_init : array-like of shape (n_components, ), default=None + The user-provided initial weights. + If it is None, weights are initialized using the `init_params` method. + + means_init : array-like of shape (n_components, n_features), default=None + The user-provided initial means, + If it is None, means are initialized using the `init_params` method. + + precisions_init : array-like, default=None + The user-provided initial precisions (inverse of the covariance + matrices). + If it is None, precisions are initialized using the 'init_params' + method. + The shape depends on 'covariance_type':: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + random_state : int, RandomState instance or None, default=None + Controls the random seed given to the method chosen to initialize the + parameters (see `init_params`). + In addition, it controls the generation of random samples from the + fitted distribution (see the method `sample`). + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + warm_start : bool, default=False + If 'warm_start' is True, the solution of the last fitting is used as + initialization for the next call of fit(). This can speed up + convergence when fit is called several times on similar problems. + In that case, 'n_init' is ignored and only a single initialization + occurs upon the first call. + See :term:`the Glossary `. + + verbose : int, default=0 + Enable verbose output. If 1 then it prints the current + initialization and each iteration step. If greater than 1 then + it prints also the log probability and the time needed + for each step. + + verbose_interval : int, default=10 + Number of iteration done before the next print. + + Attributes + ---------- + weights_ : array-like of shape (n_components,) + The weights of each mixture components. + + means_ : array-like of shape (n_components, n_features) + The mean of each mixture component. + + covariances_ : array-like + The covariance of each mixture component. + The shape depends on `covariance_type`:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + For an example of using covariances, refer to + :ref:`sphx_glr_auto_examples_mixture_plot_gmm_covariances.py`. + + precisions_ : array-like + The precision matrices for each component in the mixture. A precision + matrix is the inverse of a covariance matrix. A covariance matrix is + symmetric positive definite so the mixture of Gaussian can be + equivalently parameterized by the precision matrices. Storing the + precision matrices instead of the covariance matrices makes it more + efficient to compute the log-likelihood of new samples at test time. + The shape depends on `covariance_type`:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + precisions_cholesky_ : array-like + The cholesky decomposition of the precision matrices of each mixture + component. A precision matrix is the inverse of a covariance matrix. + A covariance matrix is symmetric positive definite so the mixture of + Gaussian can be equivalently parameterized by the precision matrices. + Storing the precision matrices instead of the covariance matrices makes + it more efficient to compute the log-likelihood of new samples at test + time. The shape depends on `covariance_type`:: + + (n_components,) if 'spherical', + (n_features, n_features) if 'tied', + (n_components, n_features) if 'diag', + (n_components, n_features, n_features) if 'full' + + converged_ : bool + True when convergence of the best fit of EM was reached, False otherwise. + + n_iter_ : int + Number of step used by the best fit of EM to reach the convergence. + + lower_bound_ : float + Lower bound value on the log-likelihood (of the training data with + respect to the model) of the best fit of EM. + + lower_bounds_ : array-like of shape (`n_iter_`,) + The list of lower bound values on the log-likelihood from each + iteration of the best fit of EM. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + BayesianGaussianMixture : Gaussian mixture model fit with a variational + inference. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.mixture import GaussianMixture + >>> X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]]) + >>> gm = GaussianMixture(n_components=2, random_state=0).fit(X) + >>> gm.means_ + array([[10., 2.], + [ 1., 2.]]) + >>> gm.predict([[0, 0], [12, 3]]) + array([1, 0]) + + For a comparison of Gaussian Mixture with other clustering algorithms, see + :ref:`sphx_glr_auto_examples_cluster_plot_cluster_comparison.py` + """ + + _parameter_constraints: dict = { + **BaseMixture._parameter_constraints, + "covariance_type": [StrOptions({"full", "tied", "diag", "spherical"})], + "weights_init": ["array-like", None], + "means_init": ["array-like", None], + "precisions_init": ["array-like", None], + } + + def __init__( + self, + n_components=1, + *, + covariance_type="full", + tol=1e-3, + reg_covar=1e-6, + max_iter=100, + n_init=1, + init_params="kmeans", + weights_init=None, + means_init=None, + precisions_init=None, + random_state=None, + warm_start=False, + verbose=0, + verbose_interval=10, + ): + super().__init__( + n_components=n_components, + tol=tol, + reg_covar=reg_covar, + max_iter=max_iter, + n_init=n_init, + init_params=init_params, + random_state=random_state, + warm_start=warm_start, + verbose=verbose, + verbose_interval=verbose_interval, + ) + + self.covariance_type = covariance_type + self.weights_init = weights_init + self.means_init = means_init + self.precisions_init = precisions_init + + def _check_parameters(self, X): + """Check the Gaussian mixture parameters are well defined.""" + _, n_features = X.shape + + if self.weights_init is not None: + self.weights_init = _check_weights(self.weights_init, self.n_components) + + if self.means_init is not None: + self.means_init = _check_means( + self.means_init, self.n_components, n_features + ) + + if self.precisions_init is not None: + self.precisions_init = _check_precisions( + self.precisions_init, + self.covariance_type, + self.n_components, + n_features, + ) + + def _initialize_parameters(self, X, random_state): + # If all the initial parameters are all provided, then there is no need to run + # the initialization. + compute_resp = ( + self.weights_init is None + or self.means_init is None + or self.precisions_init is None + ) + if compute_resp: + super()._initialize_parameters(X, random_state) + else: + self._initialize(X, None) + + def _initialize(self, X, resp): + """Initialization of the Gaussian mixture parameters. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + resp : array-like of shape (n_samples, n_components) + """ + n_samples, _ = X.shape + weights, means, covariances = None, None, None + if resp is not None: + weights, means, covariances = _estimate_gaussian_parameters( + X, resp, self.reg_covar, self.covariance_type + ) + if self.weights_init is None: + weights /= n_samples + + self.weights_ = weights if self.weights_init is None else self.weights_init + self.means_ = means if self.means_init is None else self.means_init + + if self.precisions_init is None: + self.covariances_ = covariances + self.precisions_cholesky_ = _compute_precision_cholesky( + covariances, self.covariance_type + ) + else: + self.precisions_cholesky_ = _compute_precision_cholesky_from_precisions( + self.precisions_init, self.covariance_type + ) + + def _m_step(self, X, log_resp): + """M step. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + + log_resp : array-like of shape (n_samples, n_components) + Logarithm of the posterior probabilities (or responsibilities) of + the point of each sample in X. + """ + self.weights_, self.means_, self.covariances_ = _estimate_gaussian_parameters( + X, np.exp(log_resp), self.reg_covar, self.covariance_type + ) + self.weights_ /= self.weights_.sum() + self.precisions_cholesky_ = _compute_precision_cholesky( + self.covariances_, self.covariance_type + ) + + def _estimate_log_prob(self, X): + return _estimate_log_gaussian_prob( + X, self.means_, self.precisions_cholesky_, self.covariance_type + ) + + def _estimate_log_weights(self): + return np.log(self.weights_) + + def _compute_lower_bound(self, _, log_prob_norm): + return log_prob_norm + + def _get_parameters(self): + return ( + self.weights_, + self.means_, + self.covariances_, + self.precisions_cholesky_, + ) + + def _set_parameters(self, params): + ( + self.weights_, + self.means_, + self.covariances_, + self.precisions_cholesky_, + ) = params + + # Attributes computation + _, n_features = self.means_.shape + + dtype = self.precisions_cholesky_.dtype + if self.covariance_type == "full": + self.precisions_ = np.empty_like(self.precisions_cholesky_) + for k, prec_chol in enumerate(self.precisions_cholesky_): + self.precisions_[k] = np.dot(prec_chol, prec_chol.T) + + elif self.covariance_type == "tied": + self.precisions_ = np.dot( + self.precisions_cholesky_, self.precisions_cholesky_.T + ) + else: + self.precisions_ = self.precisions_cholesky_**2 + + def _n_parameters(self): + """Return the number of free parameters in the model.""" + _, n_features = self.means_.shape + if self.covariance_type == "full": + cov_params = self.n_components * n_features * (n_features + 1) / 2.0 + elif self.covariance_type == "diag": + cov_params = self.n_components * n_features + elif self.covariance_type == "tied": + cov_params = n_features * (n_features + 1) / 2.0 + elif self.covariance_type == "spherical": + cov_params = self.n_components + mean_params = n_features * self.n_components + return int(cov_params + mean_params + self.n_components - 1) + + def bic(self, X): + """Bayesian information criterion for the current model on the input X. + + You can refer to this :ref:`mathematical section ` for more + details regarding the formulation of the BIC used. + + For an example of GMM selection using `bic` information criterion, + refer to :ref:`sphx_glr_auto_examples_mixture_plot_gmm_selection.py`. + + Parameters + ---------- + X : array of shape (n_samples, n_dimensions) + The input samples. + + Returns + ------- + bic : float + The lower the better. + """ + return -2 * self.score(X) * X.shape[0] + self._n_parameters() * np.log( + X.shape[0] + ) + + def aic(self, X): + """Akaike information criterion for the current model on the input X. + + You can refer to this :ref:`mathematical section ` for more + details regarding the formulation of the AIC used. + + Parameters + ---------- + X : array of shape (n_samples, n_dimensions) + The input samples. + + Returns + ------- + aic : float + The lower the better. + """ + return -2 * self.score(X) * X.shape[0] + 2 * self._n_parameters() diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_bayesian_mixture.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_bayesian_mixture.py new file mode 100644 index 0000000000000000000000000000000000000000..d36543903cb87b07ea1a1c75b9a69aa63bd7dbff --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_bayesian_mixture.py @@ -0,0 +1,464 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import copy + +import numpy as np +import pytest +from scipy.special import gammaln + +from sklearn.exceptions import NotFittedError +from sklearn.metrics.cluster import adjusted_rand_score +from sklearn.mixture import BayesianGaussianMixture +from sklearn.mixture._bayesian_mixture import _log_dirichlet_norm, _log_wishart_norm +from sklearn.mixture.tests.test_gaussian_mixture import RandomData +from sklearn.utils._testing import ( + assert_almost_equal, + assert_array_equal, +) + +COVARIANCE_TYPE = ["full", "tied", "diag", "spherical"] +PRIOR_TYPE = ["dirichlet_process", "dirichlet_distribution"] + + +def test_log_dirichlet_norm(): + rng = np.random.RandomState(0) + + weight_concentration = rng.rand(2) + expected_norm = gammaln(np.sum(weight_concentration)) - np.sum( + gammaln(weight_concentration) + ) + predected_norm = _log_dirichlet_norm(weight_concentration) + + assert_almost_equal(expected_norm, predected_norm) + + +def test_log_wishart_norm(): + rng = np.random.RandomState(0) + + n_components, n_features = 5, 2 + degrees_of_freedom = np.abs(rng.rand(n_components)) + 1.0 + log_det_precisions_chol = n_features * np.log(range(2, 2 + n_components)) + + expected_norm = np.empty(5) + for k, (degrees_of_freedom_k, log_det_k) in enumerate( + zip(degrees_of_freedom, log_det_precisions_chol) + ): + expected_norm[k] = -( + degrees_of_freedom_k * (log_det_k + 0.5 * n_features * np.log(2.0)) + + np.sum( + gammaln( + 0.5 + * (degrees_of_freedom_k - np.arange(0, n_features)[:, np.newaxis]) + ), + 0, + ) + ).item() + predected_norm = _log_wishart_norm( + degrees_of_freedom, log_det_precisions_chol, n_features + ) + + assert_almost_equal(expected_norm, predected_norm) + + +def test_bayesian_mixture_weights_prior_initialisation(): + rng = np.random.RandomState(0) + n_samples, n_components, n_features = 10, 5, 2 + X = rng.rand(n_samples, n_features) + + # Check correct init for a given value of weight_concentration_prior + weight_concentration_prior = rng.rand() + bgmm = BayesianGaussianMixture( + weight_concentration_prior=weight_concentration_prior, random_state=rng + ).fit(X) + assert_almost_equal(weight_concentration_prior, bgmm.weight_concentration_prior_) + + # Check correct init for the default value of weight_concentration_prior + bgmm = BayesianGaussianMixture(n_components=n_components, random_state=rng).fit(X) + assert_almost_equal(1.0 / n_components, bgmm.weight_concentration_prior_) + + +def test_bayesian_mixture_mean_prior_initialisation(): + rng = np.random.RandomState(0) + n_samples, n_components, n_features = 10, 3, 2 + X = rng.rand(n_samples, n_features) + + # Check correct init for a given value of mean_precision_prior + mean_precision_prior = rng.rand() + bgmm = BayesianGaussianMixture( + mean_precision_prior=mean_precision_prior, random_state=rng + ).fit(X) + assert_almost_equal(mean_precision_prior, bgmm.mean_precision_prior_) + + # Check correct init for the default value of mean_precision_prior + bgmm = BayesianGaussianMixture(random_state=rng).fit(X) + assert_almost_equal(1.0, bgmm.mean_precision_prior_) + + # Check correct init for a given value of mean_prior + mean_prior = rng.rand(n_features) + bgmm = BayesianGaussianMixture( + n_components=n_components, mean_prior=mean_prior, random_state=rng + ).fit(X) + assert_almost_equal(mean_prior, bgmm.mean_prior_) + + # Check correct init for the default value of bemean_priorta + bgmm = BayesianGaussianMixture(n_components=n_components, random_state=rng).fit(X) + assert_almost_equal(X.mean(axis=0), bgmm.mean_prior_) + + +def test_bayesian_mixture_precisions_prior_initialisation(): + rng = np.random.RandomState(0) + n_samples, n_features = 10, 2 + X = rng.rand(n_samples, n_features) + + # Check raise message for a bad value of degrees_of_freedom_prior + bad_degrees_of_freedom_prior_ = n_features - 1.0 + bgmm = BayesianGaussianMixture( + degrees_of_freedom_prior=bad_degrees_of_freedom_prior_, random_state=rng + ) + msg = ( + "The parameter 'degrees_of_freedom_prior' should be greater than" + f" {n_features - 1}, but got {bad_degrees_of_freedom_prior_:.3f}." + ) + with pytest.raises(ValueError, match=msg): + bgmm.fit(X) + + # Check correct init for a given value of degrees_of_freedom_prior + degrees_of_freedom_prior = rng.rand() + n_features - 1.0 + bgmm = BayesianGaussianMixture( + degrees_of_freedom_prior=degrees_of_freedom_prior, random_state=rng + ).fit(X) + assert_almost_equal(degrees_of_freedom_prior, bgmm.degrees_of_freedom_prior_) + + # Check correct init for the default value of degrees_of_freedom_prior + degrees_of_freedom_prior_default = n_features + bgmm = BayesianGaussianMixture( + degrees_of_freedom_prior=degrees_of_freedom_prior_default, random_state=rng + ).fit(X) + assert_almost_equal( + degrees_of_freedom_prior_default, bgmm.degrees_of_freedom_prior_ + ) + + # Check correct init for a given value of covariance_prior + covariance_prior = { + "full": np.cov(X.T, bias=1) + 10, + "tied": np.cov(X.T, bias=1) + 5, + "diag": np.diag(np.atleast_2d(np.cov(X.T, bias=1))) + 3, + "spherical": rng.rand(), + } + + bgmm = BayesianGaussianMixture(random_state=rng) + for cov_type in ["full", "tied", "diag", "spherical"]: + bgmm.covariance_type = cov_type + bgmm.covariance_prior = covariance_prior[cov_type] + bgmm.fit(X) + assert_almost_equal(covariance_prior[cov_type], bgmm.covariance_prior_) + + # Check correct init for the default value of covariance_prior + covariance_prior_default = { + "full": np.atleast_2d(np.cov(X.T)), + "tied": np.atleast_2d(np.cov(X.T)), + "diag": np.var(X, axis=0, ddof=1), + "spherical": np.var(X, axis=0, ddof=1).mean(), + } + + bgmm = BayesianGaussianMixture(random_state=0) + for cov_type in ["full", "tied", "diag", "spherical"]: + bgmm.covariance_type = cov_type + bgmm.fit(X) + assert_almost_equal(covariance_prior_default[cov_type], bgmm.covariance_prior_) + + +def test_bayesian_mixture_check_is_fitted(): + rng = np.random.RandomState(0) + n_samples, n_features = 10, 2 + + # Check raise message + bgmm = BayesianGaussianMixture(random_state=rng) + X = rng.rand(n_samples, n_features) + + msg = "This BayesianGaussianMixture instance is not fitted yet." + with pytest.raises(ValueError, match=msg): + bgmm.score(X) + + +def test_bayesian_mixture_weights(): + rng = np.random.RandomState(0) + n_samples, n_features = 10, 2 + + X = rng.rand(n_samples, n_features) + + # Case Dirichlet distribution for the weight concentration prior type + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type="dirichlet_distribution", + n_components=3, + random_state=rng, + ).fit(X) + + expected_weights = bgmm.weight_concentration_ / np.sum(bgmm.weight_concentration_) + assert_almost_equal(expected_weights, bgmm.weights_) + assert_almost_equal(np.sum(bgmm.weights_), 1.0) + + # Case Dirichlet process for the weight concentration prior type + dpgmm = BayesianGaussianMixture( + weight_concentration_prior_type="dirichlet_process", + n_components=3, + random_state=rng, + ).fit(X) + weight_dirichlet_sum = ( + dpgmm.weight_concentration_[0] + dpgmm.weight_concentration_[1] + ) + tmp = dpgmm.weight_concentration_[1] / weight_dirichlet_sum + expected_weights = ( + dpgmm.weight_concentration_[0] + / weight_dirichlet_sum + * np.hstack((1, np.cumprod(tmp[:-1]))) + ) + expected_weights /= np.sum(expected_weights) + assert_almost_equal(expected_weights, dpgmm.weights_) + assert_almost_equal(np.sum(dpgmm.weights_), 1.0) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_monotonic_likelihood(): + # We check that each step of the each step of variational inference without + # regularization improve monotonically the training set of the bound + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=20) + n_components = rand_data.n_components + + for prior_type in PRIOR_TYPE: + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=2 * n_components, + covariance_type=covar_type, + warm_start=True, + max_iter=1, + random_state=rng, + tol=1e-3, + ) + current_lower_bound = -np.inf + # Do one training iteration at a time so we can make sure that the + # training log likelihood increases after each iteration. + for _ in range(600): + prev_lower_bound = current_lower_bound + current_lower_bound = bgmm.fit(X).lower_bound_ + assert current_lower_bound >= prev_lower_bound + + if bgmm.converged_: + break + assert bgmm.converged_ + + +def test_compare_covar_type(): + # We can compare the 'full' precision with the other cov_type if we apply + # 1 iter of the M-step (done during _initialize_parameters). + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7) + X = rand_data.X["full"] + n_components = rand_data.n_components + + for prior_type in PRIOR_TYPE: + # Computation of the full_covariance + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=2 * n_components, + covariance_type="full", + max_iter=1, + random_state=0, + tol=1e-7, + ) + bgmm._check_parameters(X) + bgmm._initialize_parameters(X, np.random.RandomState(0)) + full_covariances = ( + bgmm.covariances_ * bgmm.degrees_of_freedom_[:, np.newaxis, np.newaxis] + ) + + # Check tied_covariance = mean(full_covariances, 0) + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=2 * n_components, + covariance_type="tied", + max_iter=1, + random_state=0, + tol=1e-7, + ) + bgmm._check_parameters(X) + bgmm._initialize_parameters(X, np.random.RandomState(0)) + + tied_covariance = bgmm.covariances_ * bgmm.degrees_of_freedom_ + assert_almost_equal(tied_covariance, np.mean(full_covariances, 0)) + + # Check diag_covariance = diag(full_covariances) + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=2 * n_components, + covariance_type="diag", + max_iter=1, + random_state=0, + tol=1e-7, + ) + bgmm._check_parameters(X) + bgmm._initialize_parameters(X, np.random.RandomState(0)) + + diag_covariances = bgmm.covariances_ * bgmm.degrees_of_freedom_[:, np.newaxis] + assert_almost_equal( + diag_covariances, np.array([np.diag(cov) for cov in full_covariances]) + ) + + # Check spherical_covariance = np.mean(diag_covariances, 0) + bgmm = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=2 * n_components, + covariance_type="spherical", + max_iter=1, + random_state=0, + tol=1e-7, + ) + bgmm._check_parameters(X) + bgmm._initialize_parameters(X, np.random.RandomState(0)) + + spherical_covariances = bgmm.covariances_ * bgmm.degrees_of_freedom_ + assert_almost_equal(spherical_covariances, np.mean(diag_covariances, 1)) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_check_covariance_precision(): + # We check that the dot product of the covariance and the precision + # matrices is identity. + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7) + n_components, n_features = 2 * rand_data.n_components, 2 + + # Computation of the full_covariance + bgmm = BayesianGaussianMixture( + n_components=n_components, max_iter=100, random_state=rng, tol=1e-3, reg_covar=0 + ) + for covar_type in COVARIANCE_TYPE: + bgmm.covariance_type = covar_type + bgmm.fit(rand_data.X[covar_type]) + + if covar_type == "full": + for covar, precision in zip(bgmm.covariances_, bgmm.precisions_): + assert_almost_equal(np.dot(covar, precision), np.eye(n_features)) + elif covar_type == "tied": + assert_almost_equal( + np.dot(bgmm.covariances_, bgmm.precisions_), np.eye(n_features) + ) + + elif covar_type == "diag": + assert_almost_equal( + bgmm.covariances_ * bgmm.precisions_, + np.ones((n_components, n_features)), + ) + + else: + assert_almost_equal( + bgmm.covariances_ * bgmm.precisions_, np.ones(n_components) + ) + + +def test_invariant_translation(): + # We check here that adding a constant in the data change correctly the + # parameters of the mixture + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=100) + n_components = 2 * rand_data.n_components + + for prior_type in PRIOR_TYPE: + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + bgmm1 = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=n_components, + max_iter=100, + random_state=0, + tol=1e-3, + reg_covar=0, + ).fit(X) + bgmm2 = BayesianGaussianMixture( + weight_concentration_prior_type=prior_type, + n_components=n_components, + max_iter=100, + random_state=0, + tol=1e-3, + reg_covar=0, + ).fit(X + 100) + + assert_almost_equal(bgmm1.means_, bgmm2.means_ - 100) + assert_almost_equal(bgmm1.weights_, bgmm2.weights_) + assert_almost_equal(bgmm1.covariances_, bgmm2.covariances_) + + +@pytest.mark.filterwarnings("ignore:.*did not converge.*") +@pytest.mark.parametrize( + "seed, max_iter, tol", + [ + (0, 2, 1e-7), # strict non-convergence + (1, 2, 1e-1), # loose non-convergence + (3, 300, 1e-7), # strict convergence + (4, 300, 1e-1), # loose convergence + ], +) +def test_bayesian_mixture_fit_predict(seed, max_iter, tol): + rng = np.random.RandomState(seed) + rand_data = RandomData(rng, n_samples=50, scale=7) + n_components = 2 * rand_data.n_components + + for covar_type in COVARIANCE_TYPE: + bgmm1 = BayesianGaussianMixture( + n_components=n_components, + max_iter=max_iter, + random_state=rng, + tol=tol, + reg_covar=0, + ) + bgmm1.covariance_type = covar_type + bgmm2 = copy.deepcopy(bgmm1) + X = rand_data.X[covar_type] + + Y_pred1 = bgmm1.fit(X).predict(X) + Y_pred2 = bgmm2.fit_predict(X) + assert_array_equal(Y_pred1, Y_pred2) + + +def test_bayesian_mixture_fit_predict_n_init(): + # Check that fit_predict is equivalent to fit.predict, when n_init > 1 + X = np.random.RandomState(0).randn(50, 5) + gm = BayesianGaussianMixture(n_components=5, n_init=10, random_state=0) + y_pred1 = gm.fit_predict(X) + y_pred2 = gm.predict(X) + assert_array_equal(y_pred1, y_pred2) + + +def test_bayesian_mixture_predict_predict_proba(): + # this is the same test as test_gaussian_mixture_predict_predict_proba() + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + for prior_type in PRIOR_TYPE: + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + Y = rand_data.Y + bgmm = BayesianGaussianMixture( + n_components=rand_data.n_components, + random_state=rng, + weight_concentration_prior_type=prior_type, + covariance_type=covar_type, + ) + + # Check a warning message arrive if we don't do fit + msg = ( + "This BayesianGaussianMixture instance is not fitted yet. " + "Call 'fit' with appropriate arguments before using this " + "estimator." + ) + with pytest.raises(NotFittedError, match=msg): + bgmm.predict(X) + + bgmm.fit(X) + Y_pred = bgmm.predict(X) + Y_pred_proba = bgmm.predict_proba(X).argmax(axis=1) + assert_array_equal(Y_pred, Y_pred_proba) + assert adjusted_rand_score(Y, Y_pred) >= 0.95 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_gaussian_mixture.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_gaussian_mixture.py new file mode 100644 index 0000000000000000000000000000000000000000..488a2ab147e8362eede842f64f4787fda47b9159 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_gaussian_mixture.py @@ -0,0 +1,1473 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import copy +import itertools +import re +import sys +import warnings +from io import StringIO +from unittest.mock import Mock + +import numpy as np +import pytest +from scipy import linalg, stats + +import sklearn +from sklearn.cluster import KMeans +from sklearn.covariance import EmpiricalCovariance +from sklearn.datasets import make_spd_matrix +from sklearn.exceptions import ConvergenceWarning, NotFittedError +from sklearn.metrics.cluster import adjusted_rand_score +from sklearn.mixture import GaussianMixture +from sklearn.mixture._gaussian_mixture import ( + _compute_log_det_cholesky, + _compute_precision_cholesky, + _estimate_gaussian_covariances_diag, + _estimate_gaussian_covariances_full, + _estimate_gaussian_covariances_spherical, + _estimate_gaussian_covariances_tied, + _estimate_gaussian_parameters, +) +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.extmath import fast_logdet + +COVARIANCE_TYPE = ["full", "tied", "diag", "spherical"] + + +def generate_data( + n_samples, n_features, weights, means, precisions, covariance_type, dtype=np.float64 +): + rng = np.random.RandomState(0) + + X = [] + if covariance_type == "spherical": + for _, (w, m, c) in enumerate(zip(weights, means, precisions["spherical"])): + X.append( + rng.multivariate_normal( + m, c * np.eye(n_features), int(np.round(w * n_samples)) + ).astype(dtype) + ) + if covariance_type == "diag": + for _, (w, m, c) in enumerate(zip(weights, means, precisions["diag"])): + X.append( + rng.multivariate_normal( + m, np.diag(c), int(np.round(w * n_samples)) + ).astype(dtype) + ) + if covariance_type == "tied": + for _, (w, m) in enumerate(zip(weights, means)): + X.append( + rng.multivariate_normal( + m, precisions["tied"], int(np.round(w * n_samples)) + ).astype(dtype) + ) + if covariance_type == "full": + for _, (w, m, c) in enumerate(zip(weights, means, precisions["full"])): + X.append( + rng.multivariate_normal(m, c, int(np.round(w * n_samples))).astype( + dtype + ) + ) + + X = np.vstack(X) + return X + + +class RandomData: + def __init__( + self, + rng, + n_samples=200, + n_components=2, + n_features=2, + scale=50, + dtype=np.float64, + ): + self.n_samples = n_samples + self.n_components = n_components + self.n_features = n_features + + self.weights = rng.rand(n_components).astype(dtype) + self.weights = self.weights.astype(dtype) / self.weights.sum() + self.means = rng.rand(n_components, n_features).astype(dtype) * scale + self.covariances = { + "spherical": 0.5 + rng.rand(n_components).astype(dtype), + "diag": (0.5 + rng.rand(n_components, n_features).astype(dtype)) ** 2, + "tied": make_spd_matrix(n_features, random_state=rng).astype(dtype), + "full": np.array( + [ + make_spd_matrix(n_features, random_state=rng).astype(dtype) * 0.5 + for _ in range(n_components) + ] + ), + } + self.precisions = { + "spherical": 1.0 / self.covariances["spherical"], + "diag": 1.0 / self.covariances["diag"], + "tied": linalg.inv(self.covariances["tied"]), + "full": np.array( + [linalg.inv(covariance) for covariance in self.covariances["full"]] + ), + } + + self.X = dict( + zip( + COVARIANCE_TYPE, + [ + generate_data( + n_samples, + n_features, + self.weights, + self.means, + self.covariances, + covar_type, + dtype=dtype, + ) + for covar_type in COVARIANCE_TYPE + ], + ) + ) + self.Y = np.hstack( + [ + np.full(int(np.round(w * n_samples)), k, dtype=int) + for k, w in enumerate(self.weights) + ] + ) + + +def test_gaussian_mixture_attributes(): + # test bad parameters + rng = np.random.RandomState(0) + X = rng.rand(10, 2) + + # test good parameters + n_components, tol, n_init, max_iter, reg_covar = 2, 1e-4, 3, 30, 1e-1 + covariance_type, init_params = "full", "random" + gmm = GaussianMixture( + n_components=n_components, + tol=tol, + n_init=n_init, + max_iter=max_iter, + reg_covar=reg_covar, + covariance_type=covariance_type, + init_params=init_params, + ).fit(X) + + assert gmm.n_components == n_components + assert gmm.covariance_type == covariance_type + assert gmm.tol == tol + assert gmm.reg_covar == reg_covar + assert gmm.max_iter == max_iter + assert gmm.n_init == n_init + assert gmm.init_params == init_params + + +def test_check_weights(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + + n_components = rand_data.n_components + X = rand_data.X["full"] + + g = GaussianMixture(n_components=n_components) + + # Check bad shape + weights_bad_shape = rng.rand(n_components, 1) + g.weights_init = weights_bad_shape + msg = re.escape( + "The parameter 'weights' should have the shape of " + f"({n_components},), but got {weights_bad_shape.shape}" + ) + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check bad range + weights_bad_range = rng.rand(n_components) + 1 + g.weights_init = weights_bad_range + msg = re.escape( + "The parameter 'weights' should be in the range [0, 1], but got" + f" max value {np.min(weights_bad_range):.5f}, " + f"min value {np.max(weights_bad_range):.5f}" + ) + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check bad normalization + weights_bad_norm = rng.rand(n_components) + weights_bad_norm = weights_bad_norm / (weights_bad_norm.sum() + 1) + g.weights_init = weights_bad_norm + msg = re.escape( + "The parameter 'weights' should be normalized, " + f"but got sum(weights) = {np.sum(weights_bad_norm):.5f}" + ) + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check good weights matrix + weights = rand_data.weights + g = GaussianMixture(weights_init=weights, n_components=n_components) + g.fit(X) + assert_array_equal(weights, g.weights_init) + + +def test_check_means(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + + n_components, n_features = rand_data.n_components, rand_data.n_features + X = rand_data.X["full"] + + g = GaussianMixture(n_components=n_components) + + # Check means bad shape + means_bad_shape = rng.rand(n_components + 1, n_features) + g.means_init = means_bad_shape + msg = "The parameter 'means' should have the shape of " + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check good means matrix + means = rand_data.means + g.means_init = means + g.fit(X) + assert_array_equal(means, g.means_init) + + +def test_check_precisions(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + + n_components, n_features = rand_data.n_components, rand_data.n_features + + # Define the bad precisions for each covariance_type + precisions_bad_shape = { + "full": np.ones((n_components + 1, n_features, n_features)), + "tied": np.ones((n_features + 1, n_features + 1)), + "diag": np.ones((n_components + 1, n_features)), + "spherical": np.ones((n_components + 1)), + } + + # Define not positive-definite precisions + precisions_not_pos = np.ones((n_components, n_features, n_features)) + precisions_not_pos[0] = np.eye(n_features) + precisions_not_pos[0, 0, 0] = -1.0 + + precisions_not_positive = { + "full": precisions_not_pos, + "tied": precisions_not_pos[0], + "diag": np.full((n_components, n_features), -1.0), + "spherical": np.full(n_components, -1.0), + } + + not_positive_errors = { + "full": "symmetric, positive-definite", + "tied": "symmetric, positive-definite", + "diag": "positive", + "spherical": "positive", + } + + for covar_type in COVARIANCE_TYPE: + X = RandomData(rng).X[covar_type] + g = GaussianMixture( + n_components=n_components, covariance_type=covar_type, random_state=rng + ) + + # Check precisions with bad shapes + g.precisions_init = precisions_bad_shape[covar_type] + msg = f"The parameter '{covar_type} precision' should have the shape of" + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check not positive precisions + g.precisions_init = precisions_not_positive[covar_type] + msg = f"'{covar_type} precision' should be {not_positive_errors[covar_type]}" + with pytest.raises(ValueError, match=msg): + g.fit(X) + + # Check the correct init of precisions_init + g.precisions_init = rand_data.precisions[covar_type] + g.fit(X) + assert_array_equal(rand_data.precisions[covar_type], g.precisions_init) + + +def test_suffstat_sk_full(): + # compare the precision matrix compute from the + # EmpiricalCovariance.covariance fitted on X*sqrt(resp) + # with _sufficient_sk_full, n_components=1 + rng = np.random.RandomState(0) + n_samples, n_features = 500, 2 + + # special case 1, assuming data is "centered" + X = rng.rand(n_samples, n_features) + resp = rng.rand(n_samples, 1) + X_resp = np.sqrt(resp) * X + nk = np.array([n_samples]) + xk = np.zeros((1, n_features)) + covars_pred = _estimate_gaussian_covariances_full(resp, X, nk, xk, 0) + ecov = EmpiricalCovariance(assume_centered=True) + ecov.fit(X_resp) + assert_almost_equal(ecov.error_norm(covars_pred[0], norm="frobenius"), 0) + assert_almost_equal(ecov.error_norm(covars_pred[0], norm="spectral"), 0) + + # check the precision computation + precs_chol_pred = _compute_precision_cholesky(covars_pred, "full") + precs_pred = np.array([np.dot(prec, prec.T) for prec in precs_chol_pred]) + precs_est = np.array([linalg.inv(cov) for cov in covars_pred]) + assert_array_almost_equal(precs_est, precs_pred) + + # special case 2, assuming resp are all ones + resp = np.ones((n_samples, 1)) + nk = np.array([n_samples]) + xk = X.mean(axis=0).reshape((1, -1)) + covars_pred = _estimate_gaussian_covariances_full(resp, X, nk, xk, 0) + ecov = EmpiricalCovariance(assume_centered=False) + ecov.fit(X) + assert_almost_equal(ecov.error_norm(covars_pred[0], norm="frobenius"), 0) + assert_almost_equal(ecov.error_norm(covars_pred[0], norm="spectral"), 0) + + # check the precision computation + precs_chol_pred = _compute_precision_cholesky(covars_pred, "full") + precs_pred = np.array([np.dot(prec, prec.T) for prec in precs_chol_pred]) + precs_est = np.array([linalg.inv(cov) for cov in covars_pred]) + assert_array_almost_equal(precs_est, precs_pred) + + +def test_suffstat_sk_tied(): + # use equation Nk * Sk / N = S_tied + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 500, 2, 2 + + resp = rng.rand(n_samples, n_components) + resp = resp / resp.sum(axis=1)[:, np.newaxis] + X = rng.rand(n_samples, n_features) + nk = resp.sum(axis=0) + xk = np.dot(resp.T, X) / nk[:, np.newaxis] + + covars_pred_full = _estimate_gaussian_covariances_full(resp, X, nk, xk, 0) + covars_pred_full = ( + np.sum(nk[:, np.newaxis, np.newaxis] * covars_pred_full, 0) / n_samples + ) + + covars_pred_tied = _estimate_gaussian_covariances_tied(resp, X, nk, xk, 0) + + ecov = EmpiricalCovariance() + ecov.covariance_ = covars_pred_full + assert_almost_equal(ecov.error_norm(covars_pred_tied, norm="frobenius"), 0) + assert_almost_equal(ecov.error_norm(covars_pred_tied, norm="spectral"), 0) + + # check the precision computation + precs_chol_pred = _compute_precision_cholesky(covars_pred_tied, "tied") + precs_pred = np.dot(precs_chol_pred, precs_chol_pred.T) + precs_est = linalg.inv(covars_pred_tied) + assert_array_almost_equal(precs_est, precs_pred) + + +def test_suffstat_sk_diag(): + # test against 'full' case + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 500, 2, 2 + + resp = rng.rand(n_samples, n_components) + resp = resp / resp.sum(axis=1)[:, np.newaxis] + X = rng.rand(n_samples, n_features) + nk = resp.sum(axis=0) + xk = np.dot(resp.T, X) / nk[:, np.newaxis] + covars_pred_full = _estimate_gaussian_covariances_full(resp, X, nk, xk, 0) + covars_pred_diag = _estimate_gaussian_covariances_diag(resp, X, nk, xk, 0) + + ecov = EmpiricalCovariance() + for cov_full, cov_diag in zip(covars_pred_full, covars_pred_diag): + ecov.covariance_ = np.diag(np.diag(cov_full)) + cov_diag = np.diag(cov_diag) + assert_almost_equal(ecov.error_norm(cov_diag, norm="frobenius"), 0) + assert_almost_equal(ecov.error_norm(cov_diag, norm="spectral"), 0) + + # check the precision computation + precs_chol_pred = _compute_precision_cholesky(covars_pred_diag, "diag") + assert_almost_equal(covars_pred_diag, 1.0 / precs_chol_pred**2) + + +def test_gaussian_suffstat_sk_spherical(global_dtype): + # computing spherical covariance equals to the variance of one-dimension + # data after flattening, n_components=1 + rng = np.random.RandomState(0) + n_samples, n_features = 500, 2 + + X = rng.rand(n_samples, n_features).astype(global_dtype) + X = X - X.mean() + resp = np.ones((n_samples, 1), dtype=global_dtype) + nk = np.array([n_samples], dtype=global_dtype) + xk = X.mean() + covars_pred_spherical = _estimate_gaussian_covariances_spherical(resp, X, nk, xk, 0) + covars_pred_spherical2 = np.dot(X.flatten().T, X.flatten()) / ( + n_features * n_samples + ) + assert_almost_equal(covars_pred_spherical, covars_pred_spherical2) + assert covars_pred_spherical.dtype == global_dtype + + # check the precision computation + precs_chol_pred = _compute_precision_cholesky(covars_pred_spherical, "spherical") + assert_almost_equal(covars_pred_spherical, 1.0 / precs_chol_pred**2) + assert precs_chol_pred.dtype == global_dtype + + +def test_compute_log_det_cholesky(global_dtype): + n_features = 2 + rand_data = RandomData(np.random.RandomState(0), dtype=global_dtype) + + for covar_type in COVARIANCE_TYPE: + covariance = rand_data.covariances[covar_type] + + if covar_type == "full": + predected_det = np.array([linalg.det(cov) for cov in covariance]) + elif covar_type == "tied": + predected_det = linalg.det(covariance) + elif covar_type == "diag": + predected_det = np.array([np.prod(cov) for cov in covariance]) + elif covar_type == "spherical": + predected_det = covariance**n_features + + # We compute the cholesky decomposition of the covariance matrix + assert covariance.dtype == global_dtype + expected_det = _compute_log_det_cholesky( + _compute_precision_cholesky(covariance, covar_type), + covar_type, + n_features=n_features, + ) + assert_array_almost_equal(expected_det, -0.5 * np.log(predected_det)) + assert expected_det.dtype == global_dtype + + +def _naive_lmvnpdf_diag(X, means, covars): + resp = np.empty((len(X), len(means))) + stds = np.sqrt(covars) + for i, (mean, std) in enumerate(zip(means, stds)): + resp[:, i] = stats.norm.logpdf(X, mean, std).sum(axis=1) + return resp + + +def test_gaussian_mixture_log_probabilities(): + from sklearn.mixture._gaussian_mixture import _estimate_log_gaussian_prob + + # test against with _naive_lmvnpdf_diag + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + n_samples = 500 + n_features = rand_data.n_features + n_components = rand_data.n_components + + means = rand_data.means + covars_diag = rng.rand(n_components, n_features) + X = rng.rand(n_samples, n_features) + log_prob_naive = _naive_lmvnpdf_diag(X, means, covars_diag) + + # full covariances + precs_full = np.array([np.diag(1.0 / np.sqrt(x)) for x in covars_diag]) + + log_prob = _estimate_log_gaussian_prob(X, means, precs_full, "full") + assert_array_almost_equal(log_prob, log_prob_naive) + + # diag covariances + precs_chol_diag = 1.0 / np.sqrt(covars_diag) + log_prob = _estimate_log_gaussian_prob(X, means, precs_chol_diag, "diag") + assert_array_almost_equal(log_prob, log_prob_naive) + + # tied + covars_tied = np.array([x for x in covars_diag]).mean(axis=0) + precs_tied = np.diag(np.sqrt(1.0 / covars_tied)) + + log_prob_naive = _naive_lmvnpdf_diag(X, means, [covars_tied] * n_components) + log_prob = _estimate_log_gaussian_prob(X, means, precs_tied, "tied") + + assert_array_almost_equal(log_prob, log_prob_naive) + + # spherical + covars_spherical = covars_diag.mean(axis=1) + precs_spherical = 1.0 / np.sqrt(covars_diag.mean(axis=1)) + log_prob_naive = _naive_lmvnpdf_diag( + X, means, [[k] * n_features for k in covars_spherical] + ) + log_prob = _estimate_log_gaussian_prob(X, means, precs_spherical, "spherical") + assert_array_almost_equal(log_prob, log_prob_naive) + + +# skip tests on weighted_log_probabilities, log_weights + + +def test_gaussian_mixture_estimate_log_prob_resp(): + # test whether responsibilities are normalized + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=5) + n_samples = rand_data.n_samples + n_features = rand_data.n_features + n_components = rand_data.n_components + + X = rng.rand(n_samples, n_features) + for covar_type in COVARIANCE_TYPE: + weights = rand_data.weights + means = rand_data.means + precisions = rand_data.precisions[covar_type] + g = GaussianMixture( + n_components=n_components, + random_state=rng, + weights_init=weights, + means_init=means, + precisions_init=precisions, + covariance_type=covar_type, + ) + g.fit(X) + resp = g.predict_proba(X) + assert_array_almost_equal(resp.sum(axis=1), np.ones(n_samples)) + assert_array_equal(g.weights_init, weights) + assert_array_equal(g.means_init, means) + assert_array_equal(g.precisions_init, precisions) + + +def test_gaussian_mixture_predict_predict_proba(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + Y = rand_data.Y + g = GaussianMixture( + n_components=rand_data.n_components, + random_state=rng, + weights_init=rand_data.weights, + means_init=rand_data.means, + precisions_init=rand_data.precisions[covar_type], + covariance_type=covar_type, + ) + + # Check a warning message arrive if we don't do fit + msg = ( + "This GaussianMixture instance is not fitted yet. Call 'fit' " + "with appropriate arguments before using this estimator." + ) + with pytest.raises(NotFittedError, match=msg): + g.predict(X) + + g.fit(X) + Y_pred = g.predict(X) + Y_pred_proba = g.predict_proba(X).argmax(axis=1) + assert_array_equal(Y_pred, Y_pred_proba) + assert adjusted_rand_score(Y, Y_pred) > 0.95 + + +@pytest.mark.filterwarnings("ignore:.*did not converge.*") +@pytest.mark.parametrize( + "seed, max_iter, tol", + [ + (0, 2, 1e-7), # strict non-convergence + (1, 2, 1e-1), # loose non-convergence + (3, 300, 1e-7), # strict convergence + (4, 300, 1e-1), # loose convergence + ], +) +def test_gaussian_mixture_fit_predict(seed, max_iter, tol, global_dtype): + rng = np.random.RandomState(seed) + rand_data = RandomData(rng, dtype=global_dtype) + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + Y = rand_data.Y + g = GaussianMixture( + n_components=rand_data.n_components, + random_state=rng, + weights_init=rand_data.weights, + means_init=rand_data.means, + precisions_init=rand_data.precisions[covar_type], + covariance_type=covar_type, + max_iter=max_iter, + tol=tol, + ) + + # check if fit_predict(X) is equivalent to fit(X).predict(X) + f = copy.deepcopy(g) + Y_pred1 = f.fit(X).predict(X) + Y_pred2 = g.fit_predict(X) + assert_array_equal(Y_pred1, Y_pred2) + assert adjusted_rand_score(Y, Y_pred2) > 0.95 + assert g.means_.dtype == global_dtype + assert g.weights_.dtype == global_dtype + assert g.precisions_.dtype == global_dtype + + +def test_gaussian_mixture_fit_predict_n_init(): + # Check that fit_predict is equivalent to fit.predict, when n_init > 1 + X = np.random.RandomState(0).randn(1000, 5) + gm = GaussianMixture(n_components=5, n_init=5, random_state=0) + y_pred1 = gm.fit_predict(X) + y_pred2 = gm.predict(X) + assert_array_equal(y_pred1, y_pred2) + + +def test_gaussian_mixture_fit(global_dtype): + # recover the ground truth + rng = np.random.RandomState(0) + rand_data = RandomData(rng, dtype=global_dtype) + n_features = rand_data.n_features + n_components = rand_data.n_components + + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + g = GaussianMixture( + n_components=n_components, + n_init=20, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + g.fit(X) + + # needs more data to pass the test with rtol=1e-7 + assert_allclose( + np.sort(g.weights_), np.sort(rand_data.weights), rtol=0.1, atol=1e-2 + ) + + arg_idx1 = g.means_[:, 0].argsort() + arg_idx2 = rand_data.means[:, 0].argsort() + assert_allclose( + g.means_[arg_idx1], rand_data.means[arg_idx2], rtol=0.1, atol=1e-2 + ) + + if covar_type == "full": + prec_pred = g.precisions_ + prec_test = rand_data.precisions["full"] + elif covar_type == "tied": + prec_pred = np.array([g.precisions_] * n_components) + prec_test = np.array([rand_data.precisions["tied"]] * n_components) + elif covar_type == "spherical": + prec_pred = np.array([np.eye(n_features) * c for c in g.precisions_]) + prec_test = np.array( + [np.eye(n_features) * c for c in rand_data.precisions["spherical"]] + ) + elif covar_type == "diag": + prec_pred = np.array([np.diag(d) for d in g.precisions_]) + prec_test = np.array([np.diag(d) for d in rand_data.precisions["diag"]]) + + arg_idx1 = np.trace(prec_pred, axis1=1, axis2=2).argsort() + arg_idx2 = np.trace(prec_test, axis1=1, axis2=2).argsort() + for k, h in zip(arg_idx1, arg_idx2): + ecov = EmpiricalCovariance() + ecov.covariance_ = prec_test[h] + # the accuracy depends on the number of data and randomness, rng + assert_allclose(ecov.error_norm(prec_pred[k]), 0, atol=0.15) + + assert g.means_.dtype == global_dtype + assert g.covariances_.dtype == global_dtype + assert g.precisions_.dtype == global_dtype + + +def test_gaussian_mixture_fit_best_params(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + n_components = rand_data.n_components + n_init = 10 + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + g = GaussianMixture( + n_components=n_components, + n_init=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + ll = [] + for _ in range(n_init): + g.fit(X) + ll.append(g.score(X)) + ll = np.array(ll) + g_best = GaussianMixture( + n_components=n_components, + n_init=n_init, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + g_best.fit(X) + assert_almost_equal(ll.min(), g_best.score(X)) + + +def test_gaussian_mixture_fit_convergence_warning(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=1) + n_components = rand_data.n_components + max_iter = 1 + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + g = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=max_iter, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + msg = ( + "Best performing initialization did not converge. " + "Try different init parameters, or increase max_iter, " + "tol, or check for degenerate data." + ) + with pytest.warns(ConvergenceWarning, match=msg): + g.fit(X) + + +def test_multiple_init(): + # Test that multiple inits does not much worse than a single one + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 50, 5, 2 + X = rng.randn(n_samples, n_features) + for cv_type in COVARIANCE_TYPE: + train1 = ( + GaussianMixture( + n_components=n_components, covariance_type=cv_type, random_state=0 + ) + .fit(X) + .score(X) + ) + train2 = ( + GaussianMixture( + n_components=n_components, + covariance_type=cv_type, + random_state=0, + n_init=5, + ) + .fit(X) + .score(X) + ) + assert train2 >= train1 + + +def test_gaussian_mixture_n_parameters(): + # Test that the right number of parameters is estimated + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 50, 5, 2 + X = rng.randn(n_samples, n_features) + n_params = {"spherical": 13, "diag": 21, "tied": 26, "full": 41} + for cv_type in COVARIANCE_TYPE: + g = GaussianMixture( + n_components=n_components, covariance_type=cv_type, random_state=rng + ).fit(X) + assert g._n_parameters() == n_params[cv_type] + + +def test_bic_1d_1component(): + # Test all of the covariance_types return the same BIC score for + # 1-dimensional, 1 component fits. + rng = np.random.RandomState(0) + n_samples, n_dim, n_components = 100, 1, 1 + X = rng.randn(n_samples, n_dim) + bic_full = ( + GaussianMixture( + n_components=n_components, covariance_type="full", random_state=rng + ) + .fit(X) + .bic(X) + ) + for covariance_type in ["tied", "diag", "spherical"]: + bic = ( + GaussianMixture( + n_components=n_components, + covariance_type=covariance_type, + random_state=rng, + ) + .fit(X) + .bic(X) + ) + assert_almost_equal(bic_full, bic) + + +def test_gaussian_mixture_aic_bic(): + # Test the aic and bic criteria + rng = np.random.RandomState(0) + n_samples, n_features, n_components = 50, 3, 2 + X = rng.randn(n_samples, n_features) + # standard gaussian entropy + sgh = 0.5 * ( + fast_logdet(np.cov(X.T, bias=1)) + n_features * (1 + np.log(2 * np.pi)) + ) + for cv_type in COVARIANCE_TYPE: + g = GaussianMixture( + n_components=n_components, + covariance_type=cv_type, + random_state=rng, + max_iter=200, + ) + g.fit(X) + aic = 2 * n_samples * sgh + 2 * g._n_parameters() + bic = 2 * n_samples * sgh + np.log(n_samples) * g._n_parameters() + bound = n_features / np.sqrt(n_samples) + assert (g.aic(X) - aic) / n_samples < bound + assert (g.bic(X) - bic) / n_samples < bound + + +def test_gaussian_mixture_verbose(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + n_components = rand_data.n_components + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + g = GaussianMixture( + n_components=n_components, + n_init=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + verbose=1, + ) + h = GaussianMixture( + n_components=n_components, + n_init=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + verbose=2, + ) + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + g.fit(X) + h.fit(X) + finally: + sys.stdout = old_stdout + + +@pytest.mark.filterwarnings("ignore:.*did not converge.*") +@pytest.mark.parametrize("seed", (0, 1, 2)) +def test_warm_start(seed): + random_state = seed + rng = np.random.RandomState(random_state) + n_samples, n_features, n_components = 500, 2, 2 + X = rng.rand(n_samples, n_features) + + # Assert the warm_start give the same result for the same number of iter + g = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=2, + reg_covar=0, + random_state=random_state, + warm_start=False, + ) + h = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=1, + reg_covar=0, + random_state=random_state, + warm_start=True, + ) + + g.fit(X) + score1 = h.fit(X).score(X) + score2 = h.fit(X).score(X) + + assert_almost_equal(g.weights_, h.weights_) + assert_almost_equal(g.means_, h.means_) + assert_almost_equal(g.precisions_, h.precisions_) + assert score2 > score1 + + # Assert that by using warm_start we can converge to a good solution + g = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=5, + reg_covar=0, + random_state=random_state, + warm_start=False, + tol=1e-6, + ) + h = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=5, + reg_covar=0, + random_state=random_state, + warm_start=True, + tol=1e-6, + ) + + g.fit(X) + assert not g.converged_ + + h.fit(X) + # depending on the data there is large variability in the number of + # refit necessary to converge due to the complete randomness of the + # data + for _ in range(1000): + h.fit(X) + if h.converged_: + break + assert h.converged_ + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_convergence_detected_with_warm_start(): + # We check that convergence is detected when warm_start=True + rng = np.random.RandomState(0) + rand_data = RandomData(rng) + n_components = rand_data.n_components + X = rand_data.X["full"] + + for max_iter in (1, 2, 50): + gmm = GaussianMixture( + n_components=n_components, + warm_start=True, + max_iter=max_iter, + random_state=rng, + ) + for _ in range(100): + gmm.fit(X) + if gmm.converged_: + break + assert gmm.converged_ + assert max_iter >= gmm.n_iter_ + + +def test_score(global_dtype): + covar_type = "full" + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7, dtype=global_dtype) + n_components = rand_data.n_components + X = rand_data.X[covar_type] + assert X.dtype == global_dtype + + # Check the error message if we don't call fit + gmm1 = GaussianMixture( + n_components=n_components, + n_init=1, + max_iter=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + msg = ( + "This GaussianMixture instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using this estimator." + ) + with pytest.raises(NotFittedError, match=msg): + gmm1.score(X) + + # Check score value + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + gmm1.fit(X) + + assert gmm1.means_.dtype == global_dtype + assert gmm1.covariances_.dtype == global_dtype + + gmm_score = gmm1.score(X) + gmm_score_proba = gmm1.score_samples(X).mean() + assert_almost_equal(gmm_score, gmm_score_proba) + assert gmm_score_proba.dtype == global_dtype + + # Check if the score increase + gmm2 = GaussianMixture( + n_components=n_components, + n_init=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ).fit(X) + assert gmm2.score(X) > gmm1.score(X) + + +def test_score_samples(): + covar_type = "full" + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7) + n_components = rand_data.n_components + X = rand_data.X[covar_type] + + # Check the error message if we don't call fit + gmm = GaussianMixture( + n_components=n_components, + n_init=1, + reg_covar=0, + random_state=rng, + covariance_type=covar_type, + ) + msg = ( + "This GaussianMixture instance is not fitted yet. Call 'fit' with " + "appropriate arguments before using this estimator." + ) + with pytest.raises(NotFittedError, match=msg): + gmm.score_samples(X) + + gmm_score_samples = gmm.fit(X).score_samples(X) + assert gmm_score_samples.shape[0] == rand_data.n_samples + + +def test_monotonic_likelihood(): + # We check that each step of the EM without regularization improve + # monotonically the training set likelihood + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7) + n_components = rand_data.n_components + + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + gmm = GaussianMixture( + n_components=n_components, + covariance_type=covar_type, + reg_covar=0, + warm_start=True, + max_iter=1, + random_state=rng, + tol=1e-7, + ) + current_log_likelihood = -np.inf + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ConvergenceWarning) + # Do one training iteration at a time so we can make sure that the + # training log likelihood increases after each iteration. + for _ in range(600): + prev_log_likelihood = current_log_likelihood + current_log_likelihood = gmm.fit(X).score(X) + assert current_log_likelihood >= prev_log_likelihood + + if gmm.converged_: + break + + assert gmm.converged_ + + +def test_regularisation(): + # We train the GaussianMixture on degenerate data by defining two clusters + # of a 0 covariance. + rng = np.random.RandomState(0) + n_samples, n_features = 10, 5 + + X = np.vstack( + (np.ones((n_samples // 2, n_features)), np.zeros((n_samples // 2, n_features))) + ) + + for covar_type in COVARIANCE_TYPE: + gmm = GaussianMixture( + n_components=n_samples, + reg_covar=0, + covariance_type=covar_type, + random_state=rng, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RuntimeWarning) + msg = re.escape( + "Fitting the mixture model failed because some components have" + " ill-defined empirical covariance (for instance caused by " + "singleton or collapsed samples). Try to decrease the number " + "of components, increase reg_covar, or scale the input data." + ) + with pytest.raises(ValueError, match=msg): + gmm.fit(X) + + gmm.set_params(reg_covar=1e-6).fit(X) + + +@pytest.mark.parametrize("covar_type", COVARIANCE_TYPE) +def test_fitted_precision_covariance_concistency(covar_type, global_dtype): + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7, dtype=global_dtype) + n_components = rand_data.n_components + + X = rand_data.X[covar_type] + gmm = GaussianMixture( + n_components=n_components, + covariance_type=covar_type, + random_state=rng, + n_init=5, + ) + gmm.fit(X) + assert gmm.precisions_.dtype == global_dtype + assert gmm.covariances_.dtype == global_dtype + if covar_type == "full": + for prec, covar in zip(gmm.precisions_, gmm.covariances_): + assert_array_almost_equal(linalg.inv(prec), covar) + elif covar_type == "tied": + assert_array_almost_equal(linalg.inv(gmm.precisions_), gmm.covariances_) + else: + assert_array_almost_equal(gmm.precisions_, 1.0 / gmm.covariances_) + + +def test_sample(): + rng = np.random.RandomState(0) + rand_data = RandomData(rng, scale=7, n_components=3) + n_features, n_components = rand_data.n_features, rand_data.n_components + + for covar_type in COVARIANCE_TYPE: + X = rand_data.X[covar_type] + + gmm = GaussianMixture( + n_components=n_components, covariance_type=covar_type, random_state=rng + ) + # To sample we need that GaussianMixture is fitted + msg = "This GaussianMixture instance is not fitted" + with pytest.raises(NotFittedError, match=msg): + gmm.sample(0) + gmm.fit(X) + + msg = "Invalid value for 'n_samples'" + with pytest.raises(ValueError, match=msg): + gmm.sample(0) + + # Just to make sure the class samples correctly + n_samples = 20000 + X_s, y_s = gmm.sample(n_samples) + + for k in range(n_components): + if covar_type == "full": + assert_array_almost_equal( + gmm.covariances_[k], np.cov(X_s[y_s == k].T), decimal=1 + ) + elif covar_type == "tied": + assert_array_almost_equal( + gmm.covariances_, np.cov(X_s[y_s == k].T), decimal=1 + ) + elif covar_type == "diag": + assert_array_almost_equal( + gmm.covariances_[k], np.diag(np.cov(X_s[y_s == k].T)), decimal=1 + ) + else: + assert_array_almost_equal( + gmm.covariances_[k], + np.var(X_s[y_s == k] - gmm.means_[k]), + decimal=1, + ) + + means_s = np.array([np.mean(X_s[y_s == k], 0) for k in range(n_components)]) + assert_array_almost_equal(gmm.means_, means_s, decimal=1) + + # Check shapes of sampled data, see + # https://github.com/scikit-learn/scikit-learn/issues/7701 + assert X_s.shape == (n_samples, n_features) + + for sample_size in range(1, 100): + X_s, _ = gmm.sample(sample_size) + assert X_s.shape == (sample_size, n_features) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.ConvergenceWarning") +def test_init(): + # We check that by increasing the n_init number we have a better solution + for random_state in range(15): + rand_data = RandomData( + np.random.RandomState(random_state), n_samples=50, scale=1 + ) + n_components = rand_data.n_components + X = rand_data.X["full"] + + gmm1 = GaussianMixture( + n_components=n_components, n_init=1, max_iter=1, random_state=random_state + ).fit(X) + gmm2 = GaussianMixture( + n_components=n_components, n_init=10, max_iter=1, random_state=random_state + ).fit(X) + + assert gmm2.lower_bound_ >= gmm1.lower_bound_ + + +def test_gaussian_mixture_setting_best_params(): + """`GaussianMixture`'s best_parameters, `n_iter_` and `lower_bound_` + must be set appropriately in the case of divergence. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/18216 + """ + rnd = np.random.RandomState(0) + n_samples = 30 + X = rnd.uniform(size=(n_samples, 3)) + + # following initialization parameters were found to lead to divergence + means_init = np.array( + [ + [0.670637869618158, 0.21038256107384043, 0.12892629765485303], + [0.09394051075844147, 0.5759464955561779, 0.929296197576212], + [0.5033230372781258, 0.9569852381759425, 0.08654043447295741], + [0.18578301420435747, 0.5531158970919143, 0.19388943970532435], + [0.4548589928173794, 0.35182513658825276, 0.568146063202464], + [0.609279894978321, 0.7929063819678847, 0.9620097270828052], + ] + ) + precisions_init = np.array( + [ + 999999.999604483, + 999999.9990869573, + 553.7603944542167, + 204.78596008931834, + 15.867423501783637, + 85.4595728389735, + ] + ) + weights_init = [ + 0.03333333333333341, + 0.03333333333333341, + 0.06666666666666674, + 0.06666666666666674, + 0.7000000000000001, + 0.10000000000000007, + ] + + gmm = GaussianMixture( + covariance_type="spherical", + reg_covar=0, + means_init=means_init, + weights_init=weights_init, + random_state=rnd, + n_components=len(weights_init), + precisions_init=precisions_init, + max_iter=1, + ) + # ensure that no error is thrown during fit + gmm.fit(X) + + # check that the fit did not converge + assert not gmm.converged_ + + # check that parameters are set for gmm + for attr in [ + "weights_", + "means_", + "covariances_", + "precisions_cholesky_", + "n_iter_", + "lower_bound_", + "lower_bounds_", + ]: + assert hasattr(gmm, attr) + + +@pytest.mark.parametrize( + "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) + + +@pytest.mark.parametrize( + "init_params", ["random", "random_from_data", "k-means++", "kmeans"] +) +def test_means_for_all_inits(init_params, global_random_seed, global_dtype): + # Check fitted means properties for all initializations + rng = np.random.RandomState(global_random_seed) + rand_data = RandomData(rng, scale=5, dtype=global_dtype) + 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_ + assert gmm.means_.dtype == global_dtype + assert gmm.covariances_.dtype == global_dtype + assert gmm.weights_.dtype == global_dtype + + +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(global_dtype): + """Check that we properly initialize `precision_cholesky_` when we manually + provide the precision matrix. + + In this regard, we check the consistency between estimating the precision + matrix and providing the same precision matrix as initialization. It should + lead to the same results with the same number of iterations. + + If the initialization is wrong then the number of iterations will increase. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/16944 + """ + # generate a toy dataset + n_samples = 300 + rng = np.random.RandomState(0) + shifted_gaussian = rng.randn(n_samples, 2) + np.array([20, 20]) + C = np.array([[0.0, -0.7], [3.5, 0.7]]) + stretched_gaussian = np.dot(rng.randn(n_samples, 2), C) + X = np.vstack([shifted_gaussian, stretched_gaussian]).astype(global_dtype) + + # common parameters to check the consistency of precision initialization + n_components, covariance_type, reg_covar, random_state = 2, "diag", 1e-6, 0 + + # execute the manual initialization to compute the precision matrix: + # - run KMeans to have an initial guess + # - estimate the covariance + # - compute the precision matrix from the estimated covariance + resp = np.zeros((X.shape[0], n_components)).astype(global_dtype) + label = ( + KMeans(n_clusters=n_components, n_init=1, random_state=random_state) + .fit(X) + .labels_ + ) + resp[np.arange(X.shape[0]), label] = 1 + _, _, covariance = _estimate_gaussian_parameters( + X, resp, reg_covar=reg_covar, covariance_type=covariance_type + ) + assert covariance.dtype == global_dtype + precisions_init = 1 / covariance + + gm_with_init = GaussianMixture( + n_components=n_components, + covariance_type=covariance_type, + reg_covar=reg_covar, + precisions_init=precisions_init, + random_state=random_state, + ).fit(X) + assert gm_with_init.means_.dtype == global_dtype + assert gm_with_init.covariances_.dtype == global_dtype + assert gm_with_init.precisions_cholesky_.dtype == global_dtype + + gm_without_init = GaussianMixture( + n_components=n_components, + covariance_type=covariance_type, + reg_covar=reg_covar, + random_state=random_state, + ).fit(X) + assert gm_without_init.means_.dtype == global_dtype + assert gm_without_init.covariances_.dtype == global_dtype + assert gm_without_init.precisions_cholesky_.dtype == global_dtype + + assert gm_without_init.n_iter_ == gm_with_init.n_iter_ + assert_allclose( + gm_with_init.precisions_cholesky_, gm_without_init.precisions_cholesky_ + ) + + +def _generate_data(seed, n_samples, n_features, n_components, dtype=np.float64): + """Randomly generate samples and responsibilities.""" + rs = np.random.RandomState(seed) + X = rs.random_sample((n_samples, n_features)).astype(dtype) + resp = rs.random_sample((n_samples, n_components)).astype(dtype) + resp /= resp.sum(axis=1)[:, np.newaxis] + return X, resp + + +def _calculate_precisions(X, resp, covariance_type): + """Calculate precision matrix of X and its Cholesky decomposition + for the given covariance type. + """ + reg_covar = 1e-6 + weights, means, covariances = _estimate_gaussian_parameters( + X, resp, reg_covar, covariance_type + ) + precisions_cholesky = _compute_precision_cholesky(covariances, covariance_type) + + _, n_components = resp.shape + # Instantiate a `GaussianMixture` model in order to use its + # `_set_parameters` method to return the `precisions_` and + # `precisions_cholesky_` from matching the `covariance_type` + # provided. + gmm = GaussianMixture(n_components=n_components, covariance_type=covariance_type) + params = (weights, means, covariances, precisions_cholesky) + gmm._set_parameters(params) + return gmm.precisions_, gmm.precisions_cholesky_ + + +@pytest.mark.parametrize("covariance_type", COVARIANCE_TYPE) +def test_gaussian_mixture_precisions_init( + covariance_type, global_random_seed, global_dtype +): + """Non-regression test for #26415.""" + + X, resp = _generate_data( + seed=global_random_seed, + n_samples=100, + n_features=3, + n_components=4, + dtype=global_dtype, + ) + + precisions_init, desired_precisions_cholesky = _calculate_precisions( + X, resp, covariance_type + ) + assert precisions_init.dtype == global_dtype + assert desired_precisions_cholesky.dtype == global_dtype + + gmm = GaussianMixture( + covariance_type=covariance_type, precisions_init=precisions_init + ) + gmm._initialize(X, resp) + actual_precisions_cholesky = gmm.precisions_cholesky_ + assert_allclose(actual_precisions_cholesky, desired_precisions_cholesky) + + +def test_gaussian_mixture_single_component_stable(): + """ + Non-regression test for #23032 ensuring 1-component GM works on only a + few samples. + """ + rng = np.random.RandomState(0) + X = rng.multivariate_normal(np.zeros(2), np.identity(2), size=3) + gm = GaussianMixture(n_components=1) + gm.fit(X).sample() + + +def test_gaussian_mixture_all_init_does_not_estimate_gaussian_parameters( + monkeypatch, + global_random_seed, +): + """When all init parameters are provided, the Gaussian parameters + are not estimated. + + Non-regression test for gh-26015. + """ + + mock = Mock(side_effect=_estimate_gaussian_parameters) + monkeypatch.setattr( + sklearn.mixture._gaussian_mixture, "_estimate_gaussian_parameters", mock + ) + + rng = np.random.RandomState(global_random_seed) + rand_data = RandomData(rng) + + gm = GaussianMixture( + n_components=rand_data.n_components, + weights_init=rand_data.weights, + means_init=rand_data.means, + precisions_init=rand_data.precisions["full"], + random_state=rng, + ) + gm.fit(rand_data.X["full"]) + # The initial gaussian parameters are not estimated. They are estimated for every + # m_step. + assert mock.call_count == gm.n_iter_ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_mixture.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_mixture.py new file mode 100644 index 0000000000000000000000000000000000000000..9c98d150f06a8c7685d24c083e2ed2866f17c8ca --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/mixture/tests/test_mixture.py @@ -0,0 +1,30 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np +import pytest + +from sklearn.mixture import BayesianGaussianMixture, GaussianMixture + + +@pytest.mark.parametrize("estimator", [GaussianMixture(), BayesianGaussianMixture()]) +def test_gaussian_mixture_n_iter(estimator): + # check that n_iter is the number of iteration performed. + rng = np.random.RandomState(0) + X = rng.rand(10, 5) + max_iter = 1 + estimator.set_params(max_iter=max_iter) + estimator.fit(X) + assert estimator.n_iter_ == max_iter + + +@pytest.mark.parametrize("estimator", [GaussianMixture(), BayesianGaussianMixture()]) +def test_mixture_n_components_greater_than_n_samples_error(estimator): + """Check error when n_components <= n_samples""" + rng = np.random.RandomState(0) + X = rng.rand(10, 5) + estimator.set_params(n_components=12) + + msg = "Expected n_samples >= n_components" + with pytest.raises(ValueError, match=msg): + estimator.fit(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8eb0ef772c552fc6e2171acc13c1e98966a1cfb4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/__init__.py @@ -0,0 +1,99 @@ +"""Tools for model selection, such as cross validation and hyper-parameter tuning.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import typing + +from ._classification_threshold import ( + FixedThresholdClassifier, + TunedThresholdClassifierCV, +) +from ._plot import LearningCurveDisplay, ValidationCurveDisplay +from ._search import GridSearchCV, ParameterGrid, ParameterSampler, RandomizedSearchCV +from ._split import ( + BaseCrossValidator, + BaseShuffleSplit, + GroupKFold, + GroupShuffleSplit, + KFold, + LeaveOneGroupOut, + LeaveOneOut, + LeavePGroupsOut, + LeavePOut, + PredefinedSplit, + RepeatedKFold, + RepeatedStratifiedKFold, + ShuffleSplit, + StratifiedGroupKFold, + StratifiedKFold, + StratifiedShuffleSplit, + TimeSeriesSplit, + check_cv, + train_test_split, +) +from ._validation import ( + cross_val_predict, + cross_val_score, + cross_validate, + learning_curve, + permutation_test_score, + validation_curve, +) + +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: F401 + HalvingGridSearchCV, + HalvingRandomSearchCV, + ) + + +__all__ = [ + "BaseCrossValidator", + "BaseShuffleSplit", + "FixedThresholdClassifier", + "GridSearchCV", + "GroupKFold", + "GroupShuffleSplit", + "KFold", + "LearningCurveDisplay", + "LeaveOneGroupOut", + "LeaveOneOut", + "LeavePGroupsOut", + "LeavePOut", + "ParameterGrid", + "ParameterSampler", + "PredefinedSplit", + "RandomizedSearchCV", + "RepeatedKFold", + "RepeatedStratifiedKFold", + "ShuffleSplit", + "StratifiedGroupKFold", + "StratifiedKFold", + "StratifiedShuffleSplit", + "TimeSeriesSplit", + "TunedThresholdClassifierCV", + "ValidationCurveDisplay", + "check_cv", + "cross_val_predict", + "cross_val_score", + "cross_validate", + "learning_curve", + "permutation_test_score", + "train_test_split", + "validation_curve", +] + + +# TODO: remove this check once the estimator is no longer experimental. +def __getattr__(name): + if name in {"HalvingGridSearchCV", "HalvingRandomSearchCV"}: + raise ImportError( + f"{name} is experimental and the API might change without any " + "deprecation cycle. To use it, you need to explicitly import " + "enable_halving_search_cv:\n" + "from sklearn.experimental import enable_halving_search_cv" + ) + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_classification_threshold.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_classification_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..c68ed38b8819d989d0ec838840b5b5406eec7e57 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_classification_threshold.py @@ -0,0 +1,889 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from collections.abc import MutableMapping +from numbers import Integral, Real + +import numpy as np + +from ..base import ( + BaseEstimator, + ClassifierMixin, + MetaEstimatorMixin, + _fit_context, + clone, +) +from ..exceptions import NotFittedError +from ..metrics import ( + check_scoring, + get_scorer_names, +) +from ..metrics._scorer import ( + _CurveScorer, + _threshold_scores_to_class_labels, +) +from ..utils import _safe_indexing, get_tags +from ..utils._param_validation import HasMethods, Interval, RealNotInt, StrOptions +from ..utils._response import _get_response_values_binary +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + process_routing, +) +from ..utils.metaestimators import available_if +from ..utils.multiclass import type_of_target +from ..utils.parallel import Parallel, delayed +from ..utils.validation import ( + _check_method_params, + _estimator_has, + _num_samples, + check_is_fitted, + indexable, +) +from ._split import StratifiedShuffleSplit, check_cv + + +def _check_is_fitted(estimator): + try: + check_is_fitted(estimator.estimator) + except NotFittedError: + check_is_fitted(estimator, "estimator_") + + +class BaseThresholdClassifier(ClassifierMixin, MetaEstimatorMixin, BaseEstimator): + """Base class for binary classifiers that set a non-default decision threshold. + + In this base class, we define the following interface: + + - the validation of common parameters in `fit`; + - the different prediction methods that can be used with the classifier. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The binary classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke, for each classifier, + `"predict_proba"` or `"decision_function"` in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + """ + + _parameter_constraints: dict = { + "estimator": [ + HasMethods(["fit", "predict_proba"]), + HasMethods(["fit", "decision_function"]), + ], + "response_method": [StrOptions({"auto", "predict_proba", "decision_function"})], + } + + def __init__(self, estimator, *, response_method="auto"): + self.estimator = estimator + self.response_method = response_method + + def _get_response_method(self): + """Define the response method.""" + if self.response_method == "auto": + response_method = ["predict_proba", "decision_function"] + else: + response_method = self.response_method + return response_method + + @_fit_context( + # *ThresholdClassifier*.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y, **params): + """Fit the classifier. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier. + + Returns + ------- + self : object + Returns an instance of self. + """ + _raise_for_params(params, self, None) + + X, y = indexable(X, y) + + y_type = type_of_target(y, input_name="y") + if y_type != "binary": + raise ValueError( + f"Only binary classification is supported. Unknown label type: {y_type}" + ) + + self._fit(X, y, **params) + + if hasattr(self.estimator_, "n_features_in_"): + self.n_features_in_ = self.estimator_.n_features_in_ + if hasattr(self.estimator_, "feature_names_in_"): + self.feature_names_in_ = self.estimator_.feature_names_in_ + + return self + + @property + def classes_(self): + """Classes labels.""" + return self.estimator_.classes_ + + @available_if(_estimator_has("predict_proba")) + def predict_proba(self, X): + """Predict class probabilities for `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + probabilities : ndarray of shape (n_samples, n_classes) + The class probabilities of the input samples. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.predict_proba(X) + + @available_if(_estimator_has("predict_log_proba")) + def predict_log_proba(self, X): + """Predict logarithm class probabilities for `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + log_probabilities : ndarray of shape (n_samples, n_classes) + The logarithm class probabilities of the input samples. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.predict_log_proba(X) + + @available_if(_estimator_has("decision_function")) + def decision_function(self, X): + """Decision function for samples in `X` using the fitted estimator. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. + + Returns + ------- + decisions : ndarray of shape (n_samples,) + The decision function computed the fitted estimator. + """ + _check_is_fitted(self) + estimator = getattr(self, "estimator_", self.estimator) + return estimator.decision_function(X) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_class = False + tags.input_tags.sparse = get_tags(self.estimator).input_tags.sparse + return tags + + +class FixedThresholdClassifier(BaseThresholdClassifier): + """Binary classifier that manually sets the decision threshold. + + This classifier allows to change the default decision threshold used for + converting posterior probability estimates (i.e. output of `predict_proba`) or + decision scores (i.e. output of `decision_function`) into a class label. + + Here, the threshold is not optimized and is set to a constant value. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The binary classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + threshold : {"auto"} or float, default="auto" + The decision threshold to use when converting posterior probability estimates + (i.e. output of `predict_proba`) or decision scores (i.e. output of + `decision_function`) into a class label. When `"auto"`, the threshold is set + to 0.5 if `predict_proba` is used as `response_method`, otherwise it is set to + 0 (i.e. the default threshold for `decision_function`). + + pos_label : int, float, bool or str, default=None + The label of the positive class. Used to process the output of the + `response_method` method. 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. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke `"predict_proba"` or `"decision_function"` + in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + + Attributes + ---------- + estimator_ : estimator instance + The fitted classifier used when predicting. + + classes_ : ndarray of shape (n_classes,) + The class labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + See Also + -------- + sklearn.model_selection.TunedThresholdClassifierCV : Classifier that post-tunes + the decision threshold based on some metrics and using cross-validation. + sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates + probabilities. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.metrics import confusion_matrix + >>> from sklearn.model_selection import FixedThresholdClassifier, train_test_split + >>> X, y = make_classification( + ... n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42 + ... ) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, stratify=y, random_state=42 + ... ) + >>> classifier = LogisticRegression(random_state=0).fit(X_train, y_train) + >>> print(confusion_matrix(y_test, classifier.predict(X_test))) + [[217 7] + [ 19 7]] + >>> classifier_other_threshold = FixedThresholdClassifier( + ... classifier, threshold=0.1, response_method="predict_proba" + ... ).fit(X_train, y_train) + >>> print(confusion_matrix(y_test, classifier_other_threshold.predict(X_test))) + [[184 40] + [ 6 20]] + """ + + _parameter_constraints: dict = { + **BaseThresholdClassifier._parameter_constraints, + "threshold": [StrOptions({"auto"}), Real], + "pos_label": [Real, str, "boolean", None], + } + + def __init__( + self, + estimator, + *, + threshold="auto", + pos_label=None, + response_method="auto", + ): + super().__init__(estimator=estimator, response_method=response_method) + self.pos_label = pos_label + self.threshold = threshold + + @property + def classes_(self): + if estimator := getattr(self, "estimator_", None): + return estimator.classes_ + try: + check_is_fitted(self.estimator) + return self.estimator.classes_ + except NotFittedError: + raise AttributeError( + "The underlying estimator is not fitted yet." + ) from NotFittedError + + def _fit(self, X, y, **params): + """Fit the classifier. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier. + + Returns + ------- + self : object + Returns an instance of self. + """ + routed_params = process_routing(self, "fit", **params) + self.estimator_ = clone(self.estimator).fit(X, y, **routed_params.estimator.fit) + return self + + def predict(self, X): + """Predict the target of new samples. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The samples, as accepted by `estimator.predict`. + + Returns + ------- + class_labels : ndarray of shape (n_samples,) + The predicted class. + """ + _check_is_fitted(self) + + estimator = getattr(self, "estimator_", self.estimator) + + y_score, _, response_method_used = _get_response_values_binary( + estimator, + X, + self._get_response_method(), + pos_label=self.pos_label, + return_response_method_used=True, + ) + + if self.threshold == "auto": + decision_threshold = 0.5 if response_method_used == "predict_proba" else 0.0 + else: + decision_threshold = self.threshold + + return _threshold_scores_to_class_labels( + y_score, decision_threshold, self.classes_, self.pos_label + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__).add( + estimator=self.estimator, + method_mapping=MethodMapping().add(callee="fit", caller="fit"), + ) + return router + + +def _fit_and_score_over_thresholds( + classifier, + X, + y, + *, + fit_params, + train_idx, + val_idx, + curve_scorer, + score_params, +): + """Fit a classifier and compute the scores for different decision thresholds. + + Parameters + ---------- + classifier : estimator instance + The classifier to fit and use for scoring. If `classifier` is already fitted, + it will be used as is. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The entire dataset. + + y : array-like of shape (n_samples,) + The entire target vector. + + fit_params : dict + Parameters to pass to the `fit` method of the underlying classifier. + + train_idx : ndarray of shape (n_train_samples,) or None + The indices of the training set. If `None`, `classifier` is expected to be + already fitted. + + val_idx : ndarray of shape (n_val_samples,) + The indices of the validation set used to score `classifier`. If `train_idx`, + the entire set will be used. + + curve_scorer : scorer instance + The scorer taking `classifier` and the validation set as input and outputting + decision thresholds and scores as a curve. Note that this is different from + the usual scorer that outputs a single score value as `curve_scorer` + outputs a single score value for each threshold. + + score_params : dict + Parameters to pass to the `score` method of the underlying scorer. + + Returns + ------- + scores : ndarray of shape (thresholds,) or tuple of such arrays + The scores computed for each decision threshold. When TPR/TNR or precision/ + recall are computed, `scores` is a tuple of two arrays. + + potential_thresholds : ndarray of shape (thresholds,) + The decision thresholds used to compute the scores. They are returned in + ascending order. + """ + + if train_idx is not None: + X_train, X_val = _safe_indexing(X, train_idx), _safe_indexing(X, val_idx) + y_train, y_val = _safe_indexing(y, train_idx), _safe_indexing(y, val_idx) + fit_params_train = _check_method_params(X, fit_params, indices=train_idx) + score_params_val = _check_method_params(X, score_params, indices=val_idx) + classifier.fit(X_train, y_train, **fit_params_train) + else: # prefit estimator, only a validation set is provided + X_val, y_val, score_params_val = X, y, score_params + + return curve_scorer(classifier, X_val, y_val, **score_params_val) + + +def _mean_interpolated_score(target_thresholds, cv_thresholds, cv_scores): + """Compute the mean interpolated score across folds by defining common thresholds. + + Parameters + ---------- + target_thresholds : ndarray of shape (thresholds,) + The thresholds to use to compute the mean score. + + cv_thresholds : ndarray of shape (n_folds, thresholds_fold) + The thresholds used to compute the scores for each fold. + + cv_scores : ndarray of shape (n_folds, thresholds_fold) + The scores computed for each threshold for each fold. + + Returns + ------- + mean_score : ndarray of shape (thresholds,) + The mean score across all folds for each target threshold. + """ + return np.mean( + [ + np.interp(target_thresholds, split_thresholds, split_score) + for split_thresholds, split_score in zip(cv_thresholds, cv_scores) + ], + axis=0, + ) + + +class TunedThresholdClassifierCV(BaseThresholdClassifier): + """Classifier that post-tunes the decision threshold using cross-validation. + + This estimator post-tunes the decision threshold (cut-off point) that is + used for converting posterior probability estimates (i.e. output of + `predict_proba`) or decision scores (i.e. output of `decision_function`) + into a class label. The tuning is done by optimizing a binary metric, + potentially constrained by a another metric. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 1.5 + + Parameters + ---------- + estimator : estimator instance + The classifier, fitted or not, for which we want to optimize + the decision threshold used during `predict`. + + scoring : str or callable, default="balanced_accuracy" + The objective metric to be optimized. Can be one of: + + - str: string associated to a scoring function for binary classification, + see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + + response_method : {"auto", "decision_function", "predict_proba"}, default="auto" + Methods by the classifier `estimator` corresponding to the + decision function for which we want to find a threshold. It can be: + + * if `"auto"`, it will try to invoke, for each classifier, + `"predict_proba"` or `"decision_function"` in that order. + * otherwise, one of `"predict_proba"` or `"decision_function"`. + If the method is not implemented by the classifier, it will raise an + error. + + thresholds : int or array-like, default=100 + The number of decision threshold to use when discretizing the output of the + classifier `method`. Pass an array-like to manually specify the thresholds + to use. + + cv : int, float, cross-validation generator, iterable or "prefit", default=None + Determines the cross-validation splitting strategy to train classifier. + Possible inputs for cv are: + + * `None`, to use the default 5-fold stratified K-fold cross validation; + * An integer number, to specify the number of folds in a stratified k-fold; + * A float number, to specify a single shuffle split. The floating number should + be in (0, 1) and represent the size of the validation set; + * An object to be used as a cross-validation generator; + * An iterable yielding train, test splits; + * `"prefit"`, to bypass the cross-validation. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. warning:: + Using `cv="prefit"` and passing the same dataset for fitting `estimator` + and tuning the cut-off point is subject to undesired overfitting. You can + refer to :ref:`TunedThresholdClassifierCV_no_cv` for an example. + + This option should only be used when the set used to fit `estimator` is + different from the one used to tune the cut-off point (by calling + :meth:`TunedThresholdClassifierCV.fit`). + + refit : bool, default=True + Whether or not to refit the classifier on the entire training set once + the decision threshold has been found. + Note that forcing `refit=False` on cross-validation having more + than a single split will raise an error. Similarly, `refit=True` in + conjunction with `cv="prefit"` will raise an error. + + n_jobs : int, default=None + The number of jobs to run in parallel. When `cv` represents a + cross-validation strategy, the fitting and scoring on each data split + is done in parallel. ``None`` means 1 unless in a + :obj:`joblib.parallel_backend` context. ``-1`` means using all + processors. See :term:`Glossary ` for more details. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of cross-validation when `cv` is a float. + See :term:`Glossary `. + + store_cv_results : bool, default=False + Whether to store all scores and thresholds computed during the cross-validation + process. + + Attributes + ---------- + estimator_ : estimator instance + The fitted classifier used when predicting. + + best_threshold_ : float + The new decision threshold. + + best_score_ : float or None + The optimal score of the objective metric, evaluated at `best_threshold_`. + + cv_results_ : dict or None + A dictionary containing the scores and thresholds computed during the + cross-validation process. Only exist if `store_cv_results=True`. The + keys are `"thresholds"` and `"scores"`. + + classes_ : ndarray of shape (n_classes,) + The class labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if the + underlying estimator exposes such an attribute when fit. + + See Also + -------- + sklearn.model_selection.FixedThresholdClassifier : Classifier that uses a + constant threshold. + sklearn.calibration.CalibratedClassifierCV : Estimator that calibrates + probabilities. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.metrics import classification_report + >>> from sklearn.model_selection import TunedThresholdClassifierCV, train_test_split + >>> X, y = make_classification( + ... n_samples=1_000, weights=[0.9, 0.1], class_sep=0.8, random_state=42 + ... ) + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, stratify=y, random_state=42 + ... ) + >>> classifier = RandomForestClassifier(random_state=0).fit(X_train, y_train) + >>> print(classification_report(y_test, classifier.predict(X_test))) + precision recall f1-score support + + 0 0.94 0.99 0.96 224 + 1 0.80 0.46 0.59 26 + + accuracy 0.93 250 + macro avg 0.87 0.72 0.77 250 + weighted avg 0.93 0.93 0.92 250 + + >>> classifier_tuned = TunedThresholdClassifierCV( + ... classifier, scoring="balanced_accuracy" + ... ).fit(X_train, y_train) + >>> print( + ... f"Cut-off point found at {classifier_tuned.best_threshold_:.3f}" + ... ) + Cut-off point found at 0.342 + >>> print(classification_report(y_test, classifier_tuned.predict(X_test))) + precision recall f1-score support + + 0 0.96 0.95 0.96 224 + 1 0.61 0.65 0.63 26 + + accuracy 0.92 250 + macro avg 0.78 0.80 0.79 250 + weighted avg 0.92 0.92 0.92 250 + + """ + + _parameter_constraints: dict = { + **BaseThresholdClassifier._parameter_constraints, + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + MutableMapping, + ], + "thresholds": [Interval(Integral, 1, None, closed="left"), "array-like"], + "cv": [ + "cv_object", + StrOptions({"prefit"}), + Interval(RealNotInt, 0.0, 1.0, closed="neither"), + ], + "refit": ["boolean"], + "n_jobs": [Integral, None], + "random_state": ["random_state"], + "store_cv_results": ["boolean"], + } + + def __init__( + self, + estimator, + *, + scoring="balanced_accuracy", + response_method="auto", + thresholds=100, + cv=None, + refit=True, + n_jobs=None, + random_state=None, + store_cv_results=False, + ): + super().__init__(estimator=estimator, response_method=response_method) + self.scoring = scoring + self.thresholds = thresholds + self.cv = cv + self.refit = refit + self.n_jobs = n_jobs + self.random_state = random_state + self.store_cv_results = store_cv_results + + def _fit(self, X, y, **params): + """Fit the classifier and post-tune the decision threshold. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training data. + + y : array-like of shape (n_samples,) + Target values. + + **params : dict + Parameters to pass to the `fit` method of the underlying + classifier and to the `scoring` scorer. + + Returns + ------- + self : object + Returns an instance of self. + """ + if isinstance(self.cv, Real) and 0 < self.cv < 1: + cv = StratifiedShuffleSplit( + n_splits=1, test_size=self.cv, random_state=self.random_state + ) + elif self.cv == "prefit": + if self.refit is True: + raise ValueError("When cv='prefit', refit cannot be True.") + try: + check_is_fitted(self.estimator, "classes_") + except NotFittedError as exc: + raise NotFittedError( + """When cv='prefit', `estimator` must be fitted.""" + ) from exc + cv = self.cv + else: + cv = check_cv(self.cv, y=y, classifier=True) + if self.refit is False and cv.get_n_splits() > 1: + raise ValueError("When cv has several folds, refit cannot be False.") + + routed_params = process_routing(self, "fit", **params) + self._curve_scorer = self._get_curve_scorer() + + # in the following block, we: + # - define the final classifier `self.estimator_` and train it if necessary + # - define `classifier` to be used to post-tune the decision threshold + # - define `split` to be used to fit/score `classifier` + if cv == "prefit": + self.estimator_ = self.estimator + classifier = self.estimator_ + splits = [(None, range(_num_samples(X)))] + else: + self.estimator_ = clone(self.estimator) + classifier = clone(self.estimator) + splits = cv.split(X, y, **routed_params.splitter.split) + + if self.refit: + # train on the whole dataset + X_train, y_train, fit_params_train = X, y, routed_params.estimator.fit + else: + # single split cross-validation + train_idx, _ = next(cv.split(X, y, **routed_params.splitter.split)) + X_train = _safe_indexing(X, train_idx) + y_train = _safe_indexing(y, train_idx) + fit_params_train = _check_method_params( + X, routed_params.estimator.fit, indices=train_idx + ) + + self.estimator_.fit(X_train, y_train, **fit_params_train) + + cv_scores, cv_thresholds = zip( + *Parallel(n_jobs=self.n_jobs)( + delayed(_fit_and_score_over_thresholds)( + clone(classifier) if cv != "prefit" else classifier, + X, + y, + fit_params=routed_params.estimator.fit, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=self._curve_scorer, + score_params=routed_params.scorer.score, + ) + for train_idx, val_idx in splits + ) + ) + + if any(np.isclose(th[0], th[-1]) for th in cv_thresholds): + raise ValueError( + "The provided estimator makes constant predictions. Therefore, it is " + "impossible to optimize the decision threshold." + ) + + # find the global min and max thresholds across all folds + min_threshold = min( + split_thresholds.min() for split_thresholds in cv_thresholds + ) + max_threshold = max( + split_thresholds.max() for split_thresholds in cv_thresholds + ) + if isinstance(self.thresholds, Integral): + decision_thresholds = np.linspace( + min_threshold, max_threshold, num=self.thresholds + ) + else: + decision_thresholds = np.asarray(self.thresholds) + + objective_scores = _mean_interpolated_score( + decision_thresholds, cv_thresholds, cv_scores + ) + best_idx = objective_scores.argmax() + self.best_score_ = objective_scores[best_idx] + self.best_threshold_ = decision_thresholds[best_idx] + if self.store_cv_results: + self.cv_results_ = { + "thresholds": decision_thresholds, + "scores": objective_scores, + } + + return self + + def predict(self, X): + """Predict the target of new samples. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The samples, as accepted by `estimator.predict`. + + Returns + ------- + class_labels : ndarray of shape (n_samples,) + The predicted class. + """ + check_is_fitted(self, "estimator_") + pos_label = self._curve_scorer._get_pos_label() + y_score, _ = _get_response_values_binary( + self.estimator_, + X, + self._get_response_method(), + pos_label=pos_label, + ) + + return _threshold_scores_to_class_labels( + y_score, self.best_threshold_, self.classes_, pos_label + ) + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = ( + MetadataRouter(owner=self.__class__.__name__) + .add( + estimator=self.estimator, + method_mapping=MethodMapping().add(callee="fit", caller="fit"), + ) + .add( + splitter=self.cv, + method_mapping=MethodMapping().add(callee="split", caller="fit"), + ) + .add( + scorer=self._get_curve_scorer(), + method_mapping=MethodMapping().add(callee="score", caller="fit"), + ) + ) + return router + + def _get_curve_scorer(self): + """Get the curve scorer based on the objective metric used.""" + scoring = check_scoring(self.estimator, scoring=self.scoring) + curve_scorer = _CurveScorer.from_scorer( + scoring, self._get_response_method(), self.thresholds + ) + return curve_scorer diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_plot.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..a69c8f455bd417b97c716c473304bfdc041d85c5 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_plot.py @@ -0,0 +1,885 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numpy as np + +from ..utils._optional_dependencies import check_matplotlib_support +from ..utils._plotting import _interval_max_min_ratio, _validate_score_name +from ._validation import learning_curve, validation_curve + + +class _BaseCurveDisplay: + def _plot_curve( + self, + x_data, + *, + ax=None, + negate_score=False, + score_name=None, + score_type="test", + std_display_style="fill_between", + line_kw=None, + fill_between_kw=None, + errorbar_kw=None, + ): + check_matplotlib_support(f"{self.__class__.__name__}.plot") + + import matplotlib.pyplot as plt + + if ax is None: + _, ax = plt.subplots() + + if negate_score: + train_scores, test_scores = -self.train_scores, -self.test_scores + else: + train_scores, test_scores = self.train_scores, self.test_scores + + if std_display_style not in ("errorbar", "fill_between", None): + raise ValueError( + f"Unknown std_display_style: {std_display_style}. Should be one of" + " 'errorbar', 'fill_between', or None." + ) + + if score_type not in ("test", "train", "both"): + raise ValueError( + f"Unknown score_type: {score_type}. Should be one of 'test', " + "'train', or 'both'." + ) + + if score_type == "train": + scores = {"Train": train_scores} + elif score_type == "test": + scores = {"Test": test_scores} + else: # score_type == "both" + scores = {"Train": train_scores, "Test": test_scores} + + if std_display_style in ("fill_between", None): + # plot the mean score + if line_kw is None: + line_kw = {} + + self.lines_ = [] + for line_label, score in scores.items(): + self.lines_.append( + *ax.plot( + x_data, + score.mean(axis=1), + label=line_label, + **line_kw, + ) + ) + self.errorbar_ = None + self.fill_between_ = None # overwritten below by fill_between + + if std_display_style == "errorbar": + if errorbar_kw is None: + errorbar_kw = {} + + self.errorbar_ = [] + for line_label, score in scores.items(): + self.errorbar_.append( + ax.errorbar( + x_data, + score.mean(axis=1), + score.std(axis=1), + label=line_label, + **errorbar_kw, + ) + ) + self.lines_, self.fill_between_ = None, None + elif std_display_style == "fill_between": + if fill_between_kw is None: + fill_between_kw = {} + default_fill_between_kw = {"alpha": 0.5} + fill_between_kw = {**default_fill_between_kw, **fill_between_kw} + + self.fill_between_ = [] + for line_label, score in scores.items(): + self.fill_between_.append( + ax.fill_between( + x_data, + score.mean(axis=1) - score.std(axis=1), + score.mean(axis=1) + score.std(axis=1), + **fill_between_kw, + ) + ) + + score_name = self.score_name if score_name is None else score_name + + ax.legend() + + # We found that a ratio, smaller or bigger than 5, between the largest and + # smallest gap of the x values is a good indicator to choose between linear + # and log scale. + if _interval_max_min_ratio(x_data) > 5: + xscale = "symlog" if x_data.min() <= 0 else "log" + else: + xscale = "linear" + + ax.set_xscale(xscale) + ax.set_ylabel(f"{score_name}") + + self.ax_ = ax + self.figure_ = ax.figure + + +class LearningCurveDisplay(_BaseCurveDisplay): + """Learning Curve visualization. + + It is recommended to use + :meth:`~sklearn.model_selection.LearningCurveDisplay.from_estimator` to + create a :class:`~sklearn.model_selection.LearningCurveDisplay` instance. + All parameters are stored as attributes. + + Read more in the :ref:`User Guide ` for general information + about the visualization API and + :ref:`detailed documentation ` regarding the learning + curve visualization. + + .. versionadded:: 1.2 + + Parameters + ---------- + train_sizes : ndarray of shape (n_unique_ticks,) + Numbers of training examples that has been used to generate the + learning curve. + + train_scores : ndarray of shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : ndarray of shape (n_ticks, n_cv_folds) + Scores on test set. + + score_name : str, default=None + The name of the score used in `learning_curve`. It will override the name + inferred from the `scoring` parameter. If `score` is `None`, we use `"Score"` if + `negate_score` is `False` and `"Negative score"` otherwise. If `scoring` is a + string or a callable, we infer the name. We replace `_` by spaces and capitalize + the first letter. We remove `neg_` and replace it by `"Negative"` if + `negate_score` is `False` or just remove it otherwise. + + Attributes + ---------- + ax_ : matplotlib Axes + Axes with the learning curve. + + figure_ : matplotlib Figure + Figure containing the learning curve. + + errorbar_ : list of matplotlib Artist or None + When the `std_display_style` is `"errorbar"`, this is a list of + `matplotlib.container.ErrorbarContainer` objects. If another style is + used, `errorbar_` is `None`. + + lines_ : list of matplotlib Artist or None + When the `std_display_style` is `"fill_between"`, this is a list of + `matplotlib.lines.Line2D` objects corresponding to the mean train and + test scores. If another style is used, `line_` is `None`. + + fill_between_ : list of matplotlib Artist or None + When the `std_display_style` is `"fill_between"`, this is a list of + `matplotlib.collections.PolyCollection` objects. If another style is + used, `fill_between_` is `None`. + + See Also + -------- + sklearn.model_selection.learning_curve : Compute the learning curve. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_iris + >>> from sklearn.model_selection import LearningCurveDisplay, learning_curve + >>> from sklearn.tree import DecisionTreeClassifier + >>> X, y = load_iris(return_X_y=True) + >>> tree = DecisionTreeClassifier(random_state=0) + >>> train_sizes, train_scores, test_scores = learning_curve( + ... tree, X, y) + >>> display = LearningCurveDisplay(train_sizes=train_sizes, + ... train_scores=train_scores, test_scores=test_scores, score_name="Score") + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__(self, *, train_sizes, train_scores, test_scores, score_name=None): + self.train_sizes = train_sizes + self.train_scores = train_scores + self.test_scores = test_scores + self.score_name = score_name + + def plot( + self, + ax=None, + *, + negate_score=False, + score_name=None, + score_type="both", + std_display_style="fill_between", + line_kw=None, + fill_between_kw=None, + errorbar_kw=None, + ): + """Plot visualization. + + Parameters + ---------- + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + negate_score : bool, default=False + Whether or not to negate the scores obtained through + :func:`~sklearn.model_selection.learning_curve`. This is + particularly useful when using the error denoted by `neg_*` in + `scikit-learn`. + + score_name : str, default=None + The name of the score used to decorate the y-axis of the plot. It will + override the name inferred from the `scoring` parameter. If `score` is + `None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"` + otherwise. If `scoring` is a string or a callable, we infer the name. We + replace `_` by spaces and capitalize the first letter. We remove `neg_` and + replace it by `"Negative"` if `negate_score` is + `False` or just remove it otherwise. + + score_type : {"test", "train", "both"}, default="both" + The type of score to plot. Can be one of `"test"`, `"train"`, or + `"both"`. + + std_display_style : {"errorbar", "fill_between"} or None, default="fill_between" + The style used to display the score standard deviation around the + mean score. If None, no standard deviation representation is + displayed. + + line_kw : dict, default=None + Additional keyword arguments passed to the `plt.plot` used to draw + the mean score. + + fill_between_kw : dict, default=None + Additional keyword arguments passed to the `plt.fill_between` used + to draw the score standard deviation. + + errorbar_kw : dict, default=None + Additional keyword arguments passed to the `plt.errorbar` used to + draw mean score and standard deviation score. + + Returns + ------- + display : :class:`~sklearn.model_selection.LearningCurveDisplay` + Object that stores computed values. + """ + self._plot_curve( + self.train_sizes, + ax=ax, + negate_score=negate_score, + score_name=score_name, + score_type=score_type, + std_display_style=std_display_style, + line_kw=line_kw, + fill_between_kw=fill_between_kw, + errorbar_kw=errorbar_kw, + ) + self.ax_.set_xlabel("Number of samples in the training set") + return self + + @classmethod + def from_estimator( + cls, + 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, + fit_params=None, + ax=None, + negate_score=False, + score_name=None, + score_type="both", + std_display_style="fill_between", + line_kw=None, + fill_between_kw=None, + errorbar_kw=None, + ): + """Create a learning curve display from an estimator. + + Read more in the :ref:`User Guide ` for general + information about the visualization API and :ref:`detailed + documentation ` regarding the learning curve + visualization. + + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + An object of that type which is cloned for each validation. + + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + 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:`GroupKFold`). + + train_sizes : array-like of shape (n_ticks,), \ + default=np.linspace(0.1, 1.0, 5) + Relative or absolute numbers of training examples that will be used + to generate the learning curve. If the dtype is float, it is + regarded as a fraction of the maximum size of the training set + (that is determined by the selected validation method), i.e. it has + to be within (0, 1]. Otherwise it is interpreted as absolute sizes + of the training sets. Note that for classification the number of + samples usually have to be big enough to contain at least one + sample from each class. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and `y` is + either binary or multiclass, + :class:`~sklearn.model_selection.StratifiedKFold` is used. In all + other cases, :class:`~sklearn.model_selection.KFold` is used. These + splitters are instantiated with `shuffle=False` so the splits will + be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + scoring : str or callable, default=None + The scoring method to use when calculating the learning curve. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + exploit_incremental_learning : bool, default=False + If the estimator supports incremental learning, this will be + used to speed up fitting for different training set sizes. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and + computing the score are parallelized over the different training + and test sets. `None` means 1 unless in a + :obj:`joblib.parallel_backend` context. `-1` means using all + processors. See :term:`Glossary ` for more details. + + pre_dispatch : int or str, default='all' + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The str can + be an expression like '2*n_jobs'. + + verbose : int, default=0 + Controls the verbosity: the higher, the more messages. + + shuffle : bool, default=False + Whether to shuffle training data before taking prefixes of it + based on`train_sizes`. + + random_state : int, RandomState instance or None, default=None + Used when `shuffle` is True. Pass an int for reproducible + output across multiple function calls. + See :term:`Glossary `. + + 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. If a numeric value + is given, FitFailedWarning is raised. + + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + negate_score : bool, default=False + Whether or not to negate the scores obtained through + :func:`~sklearn.model_selection.learning_curve`. This is + particularly useful when using the error denoted by `neg_*` in + `scikit-learn`. + + score_name : str, default=None + The name of the score used to decorate the y-axis of the plot. It will + override the name inferred from the `scoring` parameter. If `score` is + `None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"` + otherwise. If `scoring` is a string or a callable, we infer the name. We + replace `_` by spaces and capitalize the first letter. We remove `neg_` and + replace it by `"Negative"` if `negate_score` is + `False` or just remove it otherwise. + + score_type : {"test", "train", "both"}, default="both" + The type of score to plot. Can be one of `"test"`, `"train"`, or + `"both"`. + + std_display_style : {"errorbar", "fill_between"} or None, default="fill_between" + The style used to display the score standard deviation around the + mean score. If `None`, no representation of the standard deviation + is displayed. + + line_kw : dict, default=None + Additional keyword arguments passed to the `plt.plot` used to draw + the mean score. + + fill_between_kw : dict, default=None + Additional keyword arguments passed to the `plt.fill_between` used + to draw the score standard deviation. + + errorbar_kw : dict, default=None + Additional keyword arguments passed to the `plt.errorbar` used to + draw mean score and standard deviation score. + + Returns + ------- + display : :class:`~sklearn.model_selection.LearningCurveDisplay` + Object that stores computed values. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import load_iris + >>> from sklearn.model_selection import LearningCurveDisplay + >>> from sklearn.tree import DecisionTreeClassifier + >>> X, y = load_iris(return_X_y=True) + >>> tree = DecisionTreeClassifier(random_state=0) + >>> LearningCurveDisplay.from_estimator(tree, X, y) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + score_name = _validate_score_name(score_name, scoring, negate_score) + + train_sizes, train_scores, test_scores = learning_curve( + estimator, + X, + y, + groups=groups, + train_sizes=train_sizes, + cv=cv, + scoring=scoring, + exploit_incremental_learning=exploit_incremental_learning, + n_jobs=n_jobs, + pre_dispatch=pre_dispatch, + verbose=verbose, + shuffle=shuffle, + random_state=random_state, + error_score=error_score, + return_times=False, + fit_params=fit_params, + ) + + viz = cls( + train_sizes=train_sizes, + train_scores=train_scores, + test_scores=test_scores, + score_name=score_name, + ) + return viz.plot( + ax=ax, + negate_score=negate_score, + score_type=score_type, + std_display_style=std_display_style, + line_kw=line_kw, + fill_between_kw=fill_between_kw, + errorbar_kw=errorbar_kw, + ) + + +class ValidationCurveDisplay(_BaseCurveDisplay): + """Validation Curve visualization. + + It is recommended to use + :meth:`~sklearn.model_selection.ValidationCurveDisplay.from_estimator` to + create a :class:`~sklearn.model_selection.ValidationCurveDisplay` instance. + All parameters are stored as attributes. + + Read more in the :ref:`User Guide ` for general information + about the visualization API and :ref:`detailed documentation + ` regarding the validation curve visualization. + + .. versionadded:: 1.3 + + Parameters + ---------- + param_name : str + Name of the parameter that has been varied. + + param_range : array-like of shape (n_ticks,) + The values of the parameter that have been evaluated. + + train_scores : ndarray of shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : ndarray of shape (n_ticks, n_cv_folds) + Scores on test set. + + score_name : str, default=None + The name of the score used in `validation_curve`. It will override the name + inferred from the `scoring` parameter. If `score` is `None`, we use `"Score"` if + `negate_score` is `False` and `"Negative score"` otherwise. If `scoring` is a + string or a callable, we infer the name. We replace `_` by spaces and capitalize + the first letter. We remove `neg_` and replace it by `"Negative"` if + `negate_score` is `False` or just remove it otherwise. + + Attributes + ---------- + ax_ : matplotlib Axes + Axes with the validation curve. + + figure_ : matplotlib Figure + Figure containing the validation curve. + + errorbar_ : list of matplotlib Artist or None + When the `std_display_style` is `"errorbar"`, this is a list of + `matplotlib.container.ErrorbarContainer` objects. If another style is + used, `errorbar_` is `None`. + + lines_ : list of matplotlib Artist or None + When the `std_display_style` is `"fill_between"`, this is a list of + `matplotlib.lines.Line2D` objects corresponding to the mean train and + test scores. If another style is used, `line_` is `None`. + + fill_between_ : list of matplotlib Artist or None + When the `std_display_style` is `"fill_between"`, this is a list of + `matplotlib.collections.PolyCollection` objects. If another style is + used, `fill_between_` is `None`. + + See Also + -------- + sklearn.model_selection.validation_curve : Compute the validation curve. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import ValidationCurveDisplay, validation_curve + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(n_samples=1_000, random_state=0) + >>> logistic_regression = LogisticRegression() + >>> param_name, param_range = "C", np.logspace(-8, 3, 10) + >>> train_scores, test_scores = validation_curve( + ... logistic_regression, X, y, param_name=param_name, param_range=param_range + ... ) + >>> display = ValidationCurveDisplay( + ... param_name=param_name, param_range=param_range, + ... train_scores=train_scores, test_scores=test_scores, score_name="Score" + ... ) + >>> display.plot() + <...> + >>> plt.show() + """ + + def __init__( + self, *, param_name, param_range, train_scores, test_scores, score_name=None + ): + self.param_name = param_name + self.param_range = param_range + self.train_scores = train_scores + self.test_scores = test_scores + self.score_name = score_name + + def plot( + self, + ax=None, + *, + negate_score=False, + score_name=None, + score_type="both", + std_display_style="fill_between", + line_kw=None, + fill_between_kw=None, + errorbar_kw=None, + ): + """Plot visualization. + + Parameters + ---------- + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + negate_score : bool, default=False + Whether or not to negate the scores obtained through + :func:`~sklearn.model_selection.validation_curve`. This is + particularly useful when using the error denoted by `neg_*` in + `scikit-learn`. + + score_name : str, default=None + The name of the score used to decorate the y-axis of the plot. It will + override the name inferred from the `scoring` parameter. If `score` is + `None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"` + otherwise. If `scoring` is a string or a callable, we infer the name. We + replace `_` by spaces and capitalize the first letter. We remove `neg_` and + replace it by `"Negative"` if `negate_score` is + `False` or just remove it otherwise. + + score_type : {"test", "train", "both"}, default="both" + The type of score to plot. Can be one of `"test"`, `"train"`, or + `"both"`. + + std_display_style : {"errorbar", "fill_between"} or None, default="fill_between" + The style used to display the score standard deviation around the + mean score. If None, no standard deviation representation is + displayed. + + line_kw : dict, default=None + Additional keyword arguments passed to the `plt.plot` used to draw + the mean score. + + fill_between_kw : dict, default=None + Additional keyword arguments passed to the `plt.fill_between` used + to draw the score standard deviation. + + errorbar_kw : dict, default=None + Additional keyword arguments passed to the `plt.errorbar` used to + draw mean score and standard deviation score. + + Returns + ------- + display : :class:`~sklearn.model_selection.ValidationCurveDisplay` + Object that stores computed values. + """ + self._plot_curve( + self.param_range, + ax=ax, + negate_score=negate_score, + score_name=score_name, + score_type=score_type, + std_display_style=std_display_style, + line_kw=line_kw, + fill_between_kw=fill_between_kw, + errorbar_kw=errorbar_kw, + ) + self.ax_.set_xlabel(f"{self.param_name}") + return self + + @classmethod + def from_estimator( + cls, + 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, + fit_params=None, + ax=None, + negate_score=False, + score_name=None, + score_type="both", + std_display_style="fill_between", + line_kw=None, + fill_between_kw=None, + errorbar_kw=None, + ): + """Create a validation curve display from an estimator. + + Read more in the :ref:`User Guide ` for general + information about the visualization API and :ref:`detailed + documentation ` regarding the validation curve + visualization. + + Parameters + ---------- + estimator : object type that implements the "fit" and "predict" methods + An object of that type which is cloned for each validation. + + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + Target relative to X for classification or regression; + None for unsupervised learning. + + param_name : str + Name of the parameter that will be varied. + + param_range : array-like of shape (n_values,) + The values of the parameter that will be evaluated. + + 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:`GroupKFold`). + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and `y` is + either binary or multiclass, + :class:`~sklearn.model_selection.StratifiedKFold` is used. In all + other cases, :class:`~sklearn.model_selection.KFold` is used. These + splitters are instantiated with `shuffle=False` so the splits will + be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + scoring : str or callable, default=None + Scoring method to use when computing the validation curve. Options: + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and + computing the score are parallelized over the different training + and test sets. `None` means 1 unless in a + :obj:`joblib.parallel_backend` context. `-1` means using all + processors. See :term:`Glossary ` for more details. + + pre_dispatch : int or str, default='all' + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The str can + be an expression like '2*n_jobs'. + + verbose : int, default=0 + Controls the verbosity: the higher, the more messages. + + 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. If a numeric value + is given, FitFailedWarning is raised. + + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + ax : matplotlib Axes, default=None + Axes object to plot on. If `None`, a new figure and axes is + created. + + negate_score : bool, default=False + Whether or not to negate the scores obtained through + :func:`~sklearn.model_selection.validation_curve`. This is + particularly useful when using the error denoted by `neg_*` in + `scikit-learn`. + + score_name : str, default=None + The name of the score used to decorate the y-axis of the plot. It will + override the name inferred from the `scoring` parameter. If `score` is + `None`, we use `"Score"` if `negate_score` is `False` and `"Negative score"` + otherwise. If `scoring` is a string or a callable, we infer the name. We + replace `_` by spaces and capitalize the first letter. We remove `neg_` and + replace it by `"Negative"` if `negate_score` is + `False` or just remove it otherwise. + + score_type : {"test", "train", "both"}, default="both" + The type of score to plot. Can be one of `"test"`, `"train"`, or + `"both"`. + + std_display_style : {"errorbar", "fill_between"} or None, default="fill_between" + The style used to display the score standard deviation around the + mean score. If `None`, no representation of the standard deviation + is displayed. + + line_kw : dict, default=None + Additional keyword arguments passed to the `plt.plot` used to draw + the mean score. + + fill_between_kw : dict, default=None + Additional keyword arguments passed to the `plt.fill_between` used + to draw the score standard deviation. + + errorbar_kw : dict, default=None + Additional keyword arguments passed to the `plt.errorbar` used to + draw mean score and standard deviation score. + + Returns + ------- + display : :class:`~sklearn.model_selection.ValidationCurveDisplay` + Object that stores computed values. + + Examples + -------- + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import ValidationCurveDisplay + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(n_samples=1_000, random_state=0) + >>> logistic_regression = LogisticRegression() + >>> param_name, param_range = "C", np.logspace(-8, 3, 10) + >>> ValidationCurveDisplay.from_estimator( + ... logistic_regression, X, y, param_name=param_name, + ... param_range=param_range, + ... ) + <...> + >>> plt.show() + """ + check_matplotlib_support(f"{cls.__name__}.from_estimator") + + score_name = _validate_score_name(score_name, scoring, negate_score) + + train_scores, test_scores = validation_curve( + estimator, + X, + y, + param_name=param_name, + param_range=param_range, + groups=groups, + cv=cv, + scoring=scoring, + n_jobs=n_jobs, + pre_dispatch=pre_dispatch, + verbose=verbose, + error_score=error_score, + fit_params=fit_params, + ) + + viz = cls( + param_name=param_name, + param_range=np.asarray(param_range), + train_scores=train_scores, + test_scores=test_scores, + score_name=score_name, + ) + return viz.plot( + ax=ax, + negate_score=negate_score, + score_type=score_type, + std_display_style=std_display_style, + line_kw=line_kw, + fill_between_kw=fill_between_kw, + errorbar_kw=errorbar_kw, + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search.py new file mode 100644 index 0000000000000000000000000000000000000000..5bd3f81195631da3fd21b8c3db95dcfc3df258fc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search.py @@ -0,0 +1,1996 @@ +""" +The :mod:`sklearn.model_selection._search` includes utilities to fine-tune the +parameters of an estimator. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import operator +import time +import warnings +from abc import ABCMeta, abstractmethod +from collections import defaultdict +from collections.abc import Iterable, Mapping, Sequence +from copy import deepcopy +from functools import partial, reduce +from inspect import signature +from itertools import product + +import numpy as np +from numpy.ma import MaskedArray +from scipy.stats import rankdata + +from ..base import BaseEstimator, MetaEstimatorMixin, _fit_context, clone, is_classifier +from ..exceptions import NotFittedError +from ..metrics import check_scoring +from ..metrics._scorer import ( + _check_multimetric_scoring, + _MultimetricScorer, + get_scorer_names, +) +from ..utils import Bunch, check_random_state +from ..utils._param_validation import HasMethods, Interval, StrOptions +from ..utils._repr_html.estimator import _VisualBlock +from ..utils._tags import get_tags +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _raise_for_params, + _routing_enabled, + process_routing, +) +from ..utils.metaestimators import available_if +from ..utils.parallel import Parallel, delayed +from ..utils.random import sample_without_replacement +from ..utils.validation import _check_method_params, check_is_fitted, indexable +from ._split import check_cv +from ._validation import ( + _aggregate_score_dicts, + _fit_and_score, + _insert_error_scores, + _normalize_score_results, + _warn_or_raise_about_fit_failures, +) + +__all__ = ["GridSearchCV", "ParameterGrid", "ParameterSampler", "RandomizedSearchCV"] + + +class ParameterGrid: + """Grid of parameters with a discrete number of values for each. + + Can be used to iterate over parameter value combinations with the + Python built-in function iter. + The order of the generated parameter combinations is deterministic. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + param_grid : dict of str to sequence, or sequence of such + The parameter grid to explore, as a dictionary mapping estimator + parameters to sequences of allowed values. + + An empty dict signifies default parameters. + + A sequence of dicts signifies a sequence of grids to search, and is + useful to avoid exploring parameter combinations that make no sense + or have no effect. See the examples below. + + Examples + -------- + >>> from sklearn.model_selection import ParameterGrid + >>> param_grid = {'a': [1, 2], 'b': [True, False]} + >>> list(ParameterGrid(param_grid)) == ( + ... [{'a': 1, 'b': True}, {'a': 1, 'b': False}, + ... {'a': 2, 'b': True}, {'a': 2, 'b': False}]) + True + + >>> grid = [{'kernel': ['linear']}, {'kernel': ['rbf'], 'gamma': [1, 10]}] + >>> list(ParameterGrid(grid)) == [{'kernel': 'linear'}, + ... {'kernel': 'rbf', 'gamma': 1}, + ... {'kernel': 'rbf', 'gamma': 10}] + True + >>> ParameterGrid(grid)[1] == {'kernel': 'rbf', 'gamma': 1} + True + + See Also + -------- + GridSearchCV : Uses :class:`ParameterGrid` to perform a full parallelized + parameter search. + """ + + def __init__(self, param_grid): + if not isinstance(param_grid, (Mapping, Iterable)): + raise TypeError( + f"Parameter grid should be a dict or a list, got: {param_grid!r} of" + f" type {type(param_grid).__name__}" + ) + + if isinstance(param_grid, Mapping): + # wrap dictionary in a singleton list to support either dict + # or list of dicts + param_grid = [param_grid] + + # check if all entries are dictionaries of lists + for grid in param_grid: + if not isinstance(grid, dict): + raise TypeError(f"Parameter grid is not a dict ({grid!r})") + for key, value in grid.items(): + if isinstance(value, np.ndarray) and value.ndim > 1: + raise ValueError( + f"Parameter array for {key!r} should be one-dimensional, got:" + f" {value!r} with shape {value.shape}" + ) + if isinstance(value, str) or not isinstance( + value, (np.ndarray, Sequence) + ): + raise TypeError( + f"Parameter grid for parameter {key!r} needs to be a list or a" + f" numpy array, but got {value!r} (of type " + f"{type(value).__name__}) instead. Single values " + "need to be wrapped in a list with one element." + ) + if len(value) == 0: + raise ValueError( + f"Parameter grid for parameter {key!r} need " + f"to be a non-empty sequence, got: {value!r}" + ) + + self.param_grid = param_grid + + def __iter__(self): + """Iterate over the points in the grid. + + Returns + ------- + params : iterator over dict of str to any + Yields dictionaries mapping each estimator parameter to one of its + allowed values. + """ + for p in self.param_grid: + # Always sort the keys of a dictionary, for reproducibility + items = sorted(p.items()) + if not items: + yield {} + else: + keys, values = zip(*items) + for v in product(*values): + params = dict(zip(keys, v)) + yield params + + def __len__(self): + """Number of points on the grid.""" + # Product function that can handle iterables (np.prod can't). + product = partial(reduce, operator.mul) + return sum( + product(len(v) for v in p.values()) if p else 1 for p in self.param_grid + ) + + def __getitem__(self, ind): + """Get the parameters that would be ``ind``th in iteration + + Parameters + ---------- + ind : int + The iteration index + + Returns + ------- + params : dict of str to any + Equal to list(self)[ind] + """ + # This is used to make discrete sampling without replacement memory + # efficient. + for sub_grid in self.param_grid: + # XXX: could memoize information used here + if not sub_grid: + if ind == 0: + return {} + else: + ind -= 1 + continue + + # Reverse so most frequent cycling parameter comes first + keys, values_lists = zip(*sorted(sub_grid.items())[::-1]) + sizes = [len(v_list) for v_list in values_lists] + total = np.prod(sizes) + + if ind >= total: + # Try the next grid + ind -= total + else: + out = {} + for key, v_list, n in zip(keys, values_lists, sizes): + ind, offset = divmod(ind, n) + out[key] = v_list[offset] + return out + + raise IndexError("ParameterGrid index out of range") + + +class ParameterSampler: + """Generator on parameters sampled from given distributions. + + Non-deterministic iterable over random candidate combinations for hyper- + parameter search. If all parameters are presented as a list, + sampling without replacement is performed. If at least one parameter + is given as a distribution, sampling with replacement is used. + It is highly recommended to use continuous distributions for continuous + parameters. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + param_distributions : dict + Dictionary with parameters names (`str`) 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. + If a list of dicts is given, first a dict is sampled uniformly, and + then a parameter is sampled using that dict as above. + + n_iter : int + Number of parameter settings that are produced. + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state 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 `. + + Returns + ------- + params : dict of str to any + **Yields** dictionaries mapping each estimator parameter to + as sampled value. + + Examples + -------- + >>> from sklearn.model_selection import ParameterSampler + >>> from scipy.stats.distributions import expon + >>> import numpy as np + >>> rng = np.random.RandomState(0) + >>> param_grid = {'a':[1, 2], 'b': expon()} + >>> param_list = list(ParameterSampler(param_grid, n_iter=4, + ... random_state=rng)) + >>> rounded_list = [dict((k, round(v, 6)) for (k, v) in d.items()) + ... for d in param_list] + >>> rounded_list == [{'b': 0.89856, 'a': 1}, + ... {'b': 0.923223, 'a': 1}, + ... {'b': 1.878964, 'a': 2}, + ... {'b': 1.038159, 'a': 2}] + True + """ + + def __init__(self, param_distributions, n_iter, *, random_state=None): + if not isinstance(param_distributions, (Mapping, Iterable)): + raise TypeError( + "Parameter distribution is not a dict or a list," + f" got: {param_distributions!r} of type " + f"{type(param_distributions).__name__}" + ) + + if isinstance(param_distributions, Mapping): + # wrap dictionary in a singleton list to support either dict + # or list of dicts + param_distributions = [param_distributions] + + for dist in param_distributions: + if not isinstance(dist, dict): + raise TypeError( + "Parameter distribution is not a dict ({!r})".format(dist) + ) + for key in dist: + if not isinstance(dist[key], Iterable) and not hasattr( + dist[key], "rvs" + ): + raise TypeError( + f"Parameter grid for parameter {key!r} is not iterable " + f"or a distribution (value={dist[key]})" + ) + self.n_iter = n_iter + self.random_state = random_state + self.param_distributions = param_distributions + + def _is_all_lists(self): + return all( + all(not hasattr(v, "rvs") for v in dist.values()) + for dist in self.param_distributions + ) + + def __iter__(self): + rng = check_random_state(self.random_state) + + # if all distributions are given as lists, we want to sample without + # replacement + if self._is_all_lists(): + # look up sampled parameter settings in parameter grid + param_grid = ParameterGrid(self.param_distributions) + grid_size = len(param_grid) + n_iter = self.n_iter + + if grid_size < n_iter: + warnings.warn( + "The total space of parameters %d is smaller " + "than n_iter=%d. Running %d iterations. For exhaustive " + "searches, use GridSearchCV." % (grid_size, self.n_iter, grid_size), + UserWarning, + ) + n_iter = grid_size + for i in sample_without_replacement(grid_size, n_iter, random_state=rng): + yield param_grid[i] + + else: + for _ in range(self.n_iter): + dist = rng.choice(self.param_distributions) + # Always sort the keys of a dictionary, for reproducibility + items = sorted(dist.items()) + params = dict() + for k, v in items: + if hasattr(v, "rvs"): + params[k] = v.rvs(random_state=rng) + else: + params[k] = v[rng.randint(len(v))] + yield params + + def __len__(self): + """Number of points that will be sampled.""" + if self._is_all_lists(): + grid_size = len(ParameterGrid(self.param_distributions)) + return min(self.n_iter, grid_size) + else: + return self.n_iter + + +def _check_refit(search_cv, attr): + if not search_cv.refit: + raise AttributeError( + f"This {type(search_cv).__name__} instance was initialized with " + f"`refit=False`. {attr} is available only after refitting on the best " + "parameters. You can refit an estimator manually using the " + "`best_params_` attribute" + ) + + +def _search_estimator_has(attr): + """Check if we can delegate a method to the underlying estimator. + + Calling a prediction method will only be available if `refit=True`. In + such case, we check first the fitted best estimator. If it is not + fitted, we check the unfitted estimator. + + Checking the unfitted estimator allows to use `hasattr` on the `SearchCV` + instance even before calling `fit`. + """ + + def check(self): + _check_refit(self, attr) + if hasattr(self, "best_estimator_"): + # raise an AttributeError if `attr` does not exist + getattr(self.best_estimator_, attr) + return True + # raise an AttributeError if `attr` does not exist + getattr(self.estimator, attr) + return True + + return check + + +def _yield_masked_array_for_each_param(candidate_params): + """ + Yield a masked array for each candidate param. + + `candidate_params` is a sequence of params which were used in + a `GridSearchCV`. We use masked arrays for the results, as not + all params are necessarily present in each element of + `candidate_params`. For example, if using `GridSearchCV` with + a `SVC` model, then one might search over params like: + + - kernel=["rbf"], gamma=[0.1, 1] + - kernel=["poly"], degree=[1, 2] + + and then param `'gamma'` would not be present in entries of + `candidate_params` corresponding to `kernel='poly'`. + """ + n_candidates = len(candidate_params) + param_results = defaultdict(dict) + + for cand_idx, params in enumerate(candidate_params): + for name, value in params.items(): + param_results["param_%s" % name][cand_idx] = value + + for key, param_result in param_results.items(): + param_list = list(param_result.values()) + try: + arr = np.array(param_list) + except ValueError: + # This can happen when param_list contains lists of different + # lengths, for example: + # param_list=[[1], [2, 3]] + arr_dtype = np.dtype(object) + else: + # There are two cases when we don't use the automatically inferred + # dtype when creating the array and we use object instead: + # - string dtype + # - when array.ndim > 1, that means that param_list was something + # like a list of same-size sequences, which gets turned into a + # multi-dimensional array but we want a 1d array + arr_dtype = arr.dtype if arr.dtype.kind != "U" and arr.ndim == 1 else object + + # Use one MaskedArray and mask all the places where the param is not + # applicable for that candidate (which may not contain all the params). + ma = MaskedArray(np.empty(n_candidates, dtype=arr_dtype), mask=True) + for index, value in param_result.items(): + # Setting the value at an index unmasks that index + ma[index] = value + yield (key, ma) + + +class BaseSearchCV(MetaEstimatorMixin, BaseEstimator, metaclass=ABCMeta): + """Abstract base class for hyper parameter search with cross-validation.""" + + _parameter_constraints: dict = { + "estimator": [HasMethods(["fit"])], + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + list, + tuple, + dict, + None, + ], + "n_jobs": [numbers.Integral, None], + "refit": ["boolean", str, callable], + "cv": ["cv_object"], + "verbose": ["verbose"], + "pre_dispatch": [numbers.Integral, str], + "error_score": [StrOptions({"raise"}), numbers.Real], + "return_train_score": ["boolean"], + } + + @abstractmethod + def __init__( + self, + estimator, + *, + scoring=None, + n_jobs=None, + refit=True, + cv=None, + verbose=0, + pre_dispatch="2*n_jobs", + error_score=np.nan, + return_train_score=True, + ): + self.scoring = scoring + self.estimator = estimator + self.n_jobs = n_jobs + self.refit = refit + self.cv = cv + self.verbose = verbose + self.pre_dispatch = pre_dispatch + self.error_score = error_score + self.return_train_score = return_train_score + + @property + # TODO(1.8) remove this property + def _estimator_type(self): + return self.estimator._estimator_type + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + sub_estimator_tags = get_tags(self.estimator) + tags.estimator_type = sub_estimator_tags.estimator_type + tags.classifier_tags = deepcopy(sub_estimator_tags.classifier_tags) + tags.regressor_tags = deepcopy(sub_estimator_tags.regressor_tags) + # allows cross-validation to see 'precomputed' metrics + tags.input_tags.pairwise = sub_estimator_tags.input_tags.pairwise + tags.input_tags.sparse = sub_estimator_tags.input_tags.sparse + tags.array_api_support = sub_estimator_tags.array_api_support + return tags + + def score(self, X, y=None, **params): + """Return the score on the given data, if the estimator has been refit. + + This uses the score defined by ``scoring`` where provided, and the + ``best_estimator_.score`` method otherwise. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Input data, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples, n_output) \ + or (n_samples,), default=None + Target relative to X for classification or regression; + None for unsupervised learning. + + **params : dict + Parameters to be passed to the underlying scorer(s). + + .. versionadded:: 1.4 + Only available if `enable_metadata_routing=True`. See + :ref:`Metadata Routing User Guide ` for more + details. + + Returns + ------- + score : float + The score defined by ``scoring`` if provided, and the + ``best_estimator_.score`` method otherwise. + """ + _check_refit(self, "score") + check_is_fitted(self) + + _raise_for_params(params, self, "score") + + if _routing_enabled(): + score_params = process_routing(self, "score", **params).scorer["score"] + else: + score_params = dict() + + if self.scorer_ is None: + raise ValueError( + "No score function explicitly defined, " + "and the estimator doesn't provide one %s" % self.best_estimator_ + ) + if isinstance(self.scorer_, dict): + if self.multimetric_: + scorer = self.scorer_[self.refit] + else: + scorer = self.scorer_ + return scorer(self.best_estimator_, X, y, **score_params) + + # callable + score = self.scorer_(self.best_estimator_, X, y, **score_params) + if self.multimetric_: + score = score[self.refit] + return score + + @available_if(_search_estimator_has("score_samples")) + def score_samples(self, X): + """Call score_samples on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``score_samples``. + + .. versionadded:: 0.24 + + Parameters + ---------- + X : iterable + Data to predict on. Must fulfill input requirements + of the underlying estimator. + + Returns + ------- + y_score : ndarray of shape (n_samples,) + The ``best_estimator_.score_samples`` method. + """ + check_is_fitted(self) + return self.best_estimator_.score_samples(X) + + @available_if(_search_estimator_has("predict")) + def predict(self, X): + """Call predict on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted labels or values for `X` based on the estimator with + the best found parameters. + """ + check_is_fitted(self) + return self.best_estimator_.predict(X) + + @available_if(_search_estimator_has("predict_proba")) + def predict_proba(self, X): + """Call predict_proba on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict_proba``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) or (n_samples, n_classes) + Predicted class probabilities for `X` based on the estimator with + the best found parameters. The order of the classes corresponds + to that in the fitted attribute :term:`classes_`. + """ + check_is_fitted(self) + return self.best_estimator_.predict_proba(X) + + @available_if(_search_estimator_has("predict_log_proba")) + def predict_log_proba(self, X): + """Call predict_log_proba on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``predict_log_proba``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) or (n_samples, n_classes) + Predicted class log-probabilities for `X` based on the estimator + with the best found parameters. The order of the classes + corresponds to that in the fitted attribute :term:`classes_`. + """ + check_is_fitted(self) + return self.best_estimator_.predict_log_proba(X) + + @available_if(_search_estimator_has("decision_function")) + def decision_function(self, X): + """Call decision_function on the estimator with the best found parameters. + + Only available if ``refit=True`` and the underlying estimator supports + ``decision_function``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + y_score : ndarray of shape (n_samples,) or (n_samples, n_classes) \ + or (n_samples, n_classes * (n_classes-1) / 2) + Result of the decision function for `X` based on the estimator with + the best found parameters. + """ + check_is_fitted(self) + return self.best_estimator_.decision_function(X) + + @available_if(_search_estimator_has("transform")) + def transform(self, X): + """Call transform on the estimator with the best found parameters. + + Only available if the underlying estimator supports ``transform`` and + ``refit=True``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + Xt : {ndarray, sparse matrix} of shape (n_samples, n_features) + `X` transformed in the new space based on the estimator with + the best found parameters. + """ + check_is_fitted(self) + return self.best_estimator_.transform(X) + + @available_if(_search_estimator_has("inverse_transform")) + def inverse_transform(self, X): + """Call inverse_transform on the estimator with the best found params. + + Only available if the underlying estimator implements + ``inverse_transform`` and ``refit=True``. + + Parameters + ---------- + X : indexable, length n_samples + Must fulfill the input assumptions of the + underlying estimator. + + Returns + ------- + X_original : {ndarray, sparse matrix} of shape (n_samples, n_features) + Result of the `inverse_transform` function for `X` based on the + estimator with the best found parameters. + """ + check_is_fitted(self) + return self.best_estimator_.inverse_transform(X) + + @property + def n_features_in_(self): + """Number of features seen during :term:`fit`. + + Only available when `refit=True`. + """ + # For consistency with other estimators we raise a AttributeError so + # that hasattr() fails if the search estimator isn't fitted. + try: + check_is_fitted(self) + except NotFittedError as nfe: + raise AttributeError( + "{} object has no n_features_in_ attribute.".format( + self.__class__.__name__ + ) + ) from nfe + + return self.best_estimator_.n_features_in_ + + @property + def classes_(self): + """Class labels. + + Only available when `refit=True` and the estimator is a classifier. + """ + _search_estimator_has("classes_")(self) + return self.best_estimator_.classes_ + + def _run_search(self, evaluate_candidates): + """Repeatedly calls `evaluate_candidates` to conduct a search. + + This method, implemented in sub-classes, makes it possible to + customize the scheduling of evaluations: GridSearchCV and + RandomizedSearchCV schedule evaluations for their whole parameter + search space at once but other more sequential approaches are also + possible: for instance is possible to iteratively schedule evaluations + for new regions of the parameter search space based on previously + 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. + - 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 + Successive Halving 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 + -------- + + :: + + def _run_search(self, evaluate_candidates): + 'Try C=0.1 only if C=1 is better than C=10' + all_results = evaluate_candidates([{'C': 1}, {'C': 10}]) + score = all_results['mean_test_score'] + if score[0] < score[1]: + evaluate_candidates([{'C': 0.1}]) + """ + raise NotImplementedError("_run_search not implemented.") + + def _check_refit_for_multimetric(self, scores): + """Check `refit` is compatible with `scores` is valid""" + multimetric_refit_msg = ( + "For multi-metric scoring, the parameter refit must be set to a " + "scorer key or a callable to refit an estimator with the best " + "parameter setting on the whole data and make the best_* " + "attributes available for that metric. If this is not needed, " + f"refit should be set to False explicitly. {self.refit!r} was " + "passed." + ) + + valid_refit_dict = isinstance(self.refit, str) and self.refit in scores + + if ( + self.refit is not False + and not valid_refit_dict + and not callable(self.refit) + ): + raise ValueError(multimetric_refit_msg) + + @staticmethod + def _select_best_index(refit, refit_metric, results): + """Select index of the best combination of hyperparemeters.""" + if callable(refit): + # If callable, refit is expected to return the index of the best + # parameter set. + best_index = refit(results) + if not isinstance(best_index, numbers.Integral): + raise TypeError("best_index_ returned is not an integer") + if best_index < 0 or best_index >= len(results["params"]): + raise IndexError("best_index_ index out of range") + else: + best_index = results[f"rank_test_{refit_metric}"].argmin() + return best_index + + def _get_scorers(self): + """Get the scorer(s) to be used. + + This is used in ``fit`` and ``get_metadata_routing``. + + Returns + ------- + scorers, refit_metric + """ + refit_metric = "score" + + if callable(self.scoring): + scorers = self.scoring + elif self.scoring is None or isinstance(self.scoring, str): + scorers = check_scoring(self.estimator, self.scoring) + else: + scorers = _check_multimetric_scoring(self.estimator, self.scoring) + self._check_refit_for_multimetric(scorers) + refit_metric = self.refit + scorers = _MultimetricScorer( + scorers=scorers, raise_exc=(self.error_score == "raise") + ) + + return scorers, refit_metric + + def _check_scorers_accept_sample_weight(self): + # TODO(slep006): remove when metadata routing is the only way + scorers, _ = self._get_scorers() + # In the multimetric case, warn the user for each scorer separately + if isinstance(scorers, _MultimetricScorer): + for name, scorer in scorers._scorers.items(): + if not scorer._accept_sample_weight(): + warnings.warn( + f"The scoring {name}={scorer} does not support sample_weight, " + "which may lead to statistically incorrect results when " + f"fitting {self} with sample_weight. " + ) + return scorers._accept_sample_weight() + # In most cases, scorers is a Scorer object + # But it's a function when user passes scoring=function + if hasattr(scorers, "_accept_sample_weight"): + accept = scorers._accept_sample_weight() + else: + accept = "sample_weight" in signature(scorers).parameters + if not accept: + warnings.warn( + f"The scoring {scorers} does not support sample_weight, " + "which may lead to statistically incorrect results when " + f"fitting {self} with sample_weight. " + ) + return accept + + def _get_routed_params_for_fit(self, params): + """Get the parameters to be used for routing. + + This is a method instead of a snippet in ``fit`` since it's used twice, + here in ``fit``, and in ``HalvingRandomSearchCV.fit``. + """ + if _routing_enabled(): + routed_params = process_routing(self, "fit", **params) + else: + params = params.copy() + groups = params.pop("groups", None) + routed_params = Bunch( + estimator=Bunch(fit=params), + splitter=Bunch(split={"groups": groups}), + scorer=Bunch(score={}), + ) + # NOTE: sample_weight is forwarded to the scorer if sample_weight + # is not None and scorers accept sample_weight. For _MultimetricScorer, + # sample_weight is forwarded if any scorer accepts sample_weight + if ( + params.get("sample_weight") is not None + and self._check_scorers_accept_sample_weight() + ): + routed_params.scorer.score["sample_weight"] = params["sample_weight"] + return routed_params + + @_fit_context( + # *SearchCV.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, **params): + """Run fit with all sets of parameters. + + Parameters + ---------- + + X : array-like of shape (n_samples, n_features) or (n_samples, n_samples) + Training vectors, where `n_samples` is the number of samples and + `n_features` is the number of features. For precomputed kernel or + distance matrix, the expected shape of X is (n_samples, n_samples). + + y : array-like of shape (n_samples, n_output) \ + or (n_samples,), default=None + Target relative to X for classification or regression; + None for unsupervised learning. + + **params : dict of str -> object + Parameters passed to the ``fit`` method of the estimator, the scorer, + and the CV splitter. + + If a fit parameter is an array-like whose length is equal to + `num_samples` then it will be split by cross-validation along with + `X` and `y`. For example, the :term:`sample_weight` parameter is + split because `len(sample_weights) = len(X)`. However, this behavior + does not apply to `groups` which is passed to the splitter configured + via the `cv` parameter of the constructor. Thus, `groups` is used + *to perform the split* and determines which samples are + assigned to the each side of the a split. + + Returns + ------- + self : object + Instance of fitted estimator. + """ + estimator = self.estimator + scorers, refit_metric = self._get_scorers() + + X, y = indexable(X, y) + params = _check_method_params(X, params=params) + + routed_params = self._get_routed_params_for_fit(params) + + cv_orig = check_cv(self.cv, y, classifier=is_classifier(estimator)) + n_splits = cv_orig.get_n_splits(X, y, **routed_params.splitter.split) + + base_estimator = clone(self.estimator) + + parallel = Parallel(n_jobs=self.n_jobs, pre_dispatch=self.pre_dispatch) + + fit_and_score_kwargs = dict( + scorer=scorers, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + return_train_score=self.return_train_score, + return_n_test_samples=True, + return_times=True, + return_parameters=False, + error_score=self.error_score, + verbose=self.verbose, + ) + results = {} + with parallel: + all_candidate_params = [] + all_out = [] + all_more_results = defaultdict(list) + + 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) + + if self.verbose > 0: + print( + "Fitting {0} folds for each of {1} candidates," + " totalling {2} fits".format( + n_splits, n_candidates, n_candidates * n_splits + ) + ) + + out = parallel( + delayed(_fit_and_score)( + clone(base_estimator), + X, + y, + train=train, + test=test, + parameters=parameters, + split_progress=(split_idx, n_splits), + candidate_progress=(cand_idx, n_candidates), + **fit_and_score_kwargs, + ) + for (cand_idx, parameters), (split_idx, (train, test)) in product( + enumerate(candidate_params), + enumerate(cv.split(X, y, **routed_params.splitter.split)), + ) + ) + + if len(out) < 1: + raise ValueError( + "No fits were performed. " + "Was the CV iterator empty? " + "Were there no candidates?" + ) + elif len(out) != n_candidates * n_splits: + raise ValueError( + "cv.split and cv.get_n_splits returned " + "inconsistent results. Expected {} " + "splits, got {}".format(n_splits, len(out) // n_candidates) + ) + + _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 + # 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) + + nonlocal results + results = self._format_results( + all_candidate_params, n_splits, all_out, all_more_results + ) + + return results + + self._run_search(evaluate_candidates) + + # multimetric is determined here because in the case of a callable + # self.scoring the return type is only known after calling + first_test_score = all_out[0]["test_scores"] + self.multimetric_ = isinstance(first_test_score, dict) + + # check refit_metric now for a callable scorer that is multimetric + if callable(self.scoring) and self.multimetric_: + self._check_refit_for_multimetric(first_test_score) + refit_metric = self.refit + + # For multi-metric evaluation, store the best_index_, best_params_ and + # best_score_ iff refit is one of the scorer names + # In single metric evaluation, refit_metric is "score" + if self.refit or not self.multimetric_: + self.best_index_ = self._select_best_index( + self.refit, refit_metric, results + ) + if not callable(self.refit): + # With a non-custom callable, we can select the best score + # based on the best index + self.best_score_ = results[f"mean_test_{refit_metric}"][ + self.best_index_ + ] + self.best_params_ = results["params"][self.best_index_] + + if self.refit: + # here we clone the estimator as well as the parameters, since + # sometimes the parameters themselves might be estimators, e.g. + # when we search over different estimators in a pipeline. + # ref: https://github.com/scikit-learn/scikit-learn/pull/26786 + self.best_estimator_ = clone(base_estimator).set_params( + **clone(self.best_params_, safe=False) + ) + + refit_start_time = time.time() + if y is not None: + self.best_estimator_.fit(X, y, **routed_params.estimator.fit) + else: + self.best_estimator_.fit(X, **routed_params.estimator.fit) + refit_end_time = time.time() + self.refit_time_ = refit_end_time - refit_start_time + + if hasattr(self.best_estimator_, "feature_names_in_"): + self.feature_names_in_ = self.best_estimator_.feature_names_in_ + + # Store the only scorer not as a dict for single metric evaluation + if isinstance(scorers, _MultimetricScorer): + self.scorer_ = scorers._scorers + else: + self.scorer_ = scorers + + self.cv_results_ = results + self.n_splits_ = n_splits + + return self + + def _format_results(self, candidate_params, n_splits, out, more_results=None): + n_candidates = len(candidate_params) + out = _aggregate_score_dicts(out) + + results = dict(more_results or {}) + for key, val in results.items(): + # each value is a list (as per evaluate_candidate's convention) + # we convert it to an array for consistency with the other keys + results[key] = np.asarray(val) + + def _store(key_name, array, weights=None, splits=False, rank=False): + """A small helper to store the scores/times to the cv_results_""" + # When iterated first by splits, then by parameters + # We want `array` to have `n_candidates` rows and `n_splits` cols. + array = np.array(array, dtype=np.float64).reshape(n_candidates, n_splits) + if splits: + for split_idx in range(n_splits): + # Uses closure to alter the results + results["split%d_%s" % (split_idx, key_name)] = array[:, split_idx] + + array_means = np.average(array, axis=1, weights=weights) + results["mean_%s" % key_name] = array_means + + if key_name.startswith(("train_", "test_")) and np.any( + ~np.isfinite(array_means) + ): + warnings.warn( + ( + f"One or more of the {key_name.split('_')[0]} scores " + f"are non-finite: {array_means}" + ), + category=UserWarning, + ) + + # Weighted std is not directly available in numpy + array_stds = np.sqrt( + np.average( + (array - array_means[:, np.newaxis]) ** 2, axis=1, weights=weights + ) + ) + results["std_%s" % key_name] = array_stds + + if rank: + # When the fit/scoring fails `array_means` contains NaNs, we + # will exclude them from the ranking process and consider them + # as tied with the worst performers. + if np.isnan(array_means).all(): + # All fit/scoring routines failed. + rank_result = np.ones_like(array_means, dtype=np.int32) + else: + min_array_means = np.nanmin(array_means) - 1 + array_means = np.nan_to_num(array_means, nan=min_array_means) + rank_result = rankdata(-array_means, method="min").astype( + np.int32, copy=False + ) + results["rank_%s" % key_name] = rank_result + + _store("fit_time", out["fit_time"]) + _store("score_time", out["score_time"]) + # Store a list of param dicts at the key 'params' + for param, ma in _yield_masked_array_for_each_param(candidate_params): + results[param] = ma + results["params"] = candidate_params + + test_scores_dict = _normalize_score_results(out["test_scores"]) + if self.return_train_score: + train_scores_dict = _normalize_score_results(out["train_scores"]) + + for scorer_name in test_scores_dict: + # Computed the (weighted) mean and std for test scores alone + _store( + "test_%s" % scorer_name, + test_scores_dict[scorer_name], + splits=True, + rank=True, + weights=None, + ) + if self.return_train_score: + _store( + "train_%s" % scorer_name, + train_scores_dict[scorer_name], + splits=True, + ) + + return results + + def get_metadata_routing(self): + """Get metadata routing of this object. + + Please check :ref:`User Guide ` on how the routing + mechanism works. + + .. versionadded:: 1.4 + + Returns + ------- + routing : MetadataRouter + A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating + routing information. + """ + router = MetadataRouter(owner=self.__class__.__name__) + router.add( + estimator=self.estimator, + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + + scorer, _ = self._get_scorers() + router.add( + scorer=scorer, + method_mapping=MethodMapping() + .add(caller="score", callee="score") + .add(caller="fit", callee="score"), + ) + router.add( + splitter=self.cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + return router + + def _sk_visual_block_(self): + if hasattr(self, "best_estimator_"): + key, estimator = "best_estimator_", self.best_estimator_ + else: + key, estimator = "estimator", self.estimator + + return _VisualBlock( + "parallel", + [estimator], + names=[f"{key}: {estimator.__class__.__name__}"], + name_details=[str(estimator)], + ) + + +class GridSearchCV(BaseSearchCV): + """Exhaustive search over specified parameter values for an estimator. + + Important members are fit, predict. + + GridSearchCV implements a "fit" and a "score" method. + It also implements "score_samples", "predict", "predict_proba", + "decision_function", "transform" and "inverse_transform" if they are + implemented in the estimator used. + + The parameters of the estimator used to apply these methods are optimized + by cross-validated grid-search over a parameter grid. + + Read more in the :ref:`User Guide `. + + 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 (`str`) 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. + + scoring : str, callable, list, tuple or dict, default=None + Strategy to evaluate the performance of the cross-validated model on + the test set. + + If `scoring` represents a single score, one can use: + + - a single string (see :ref:`scoring_string_names`); + - a callable (see :ref:`scoring_callable`) that returns a single value; + - `None`, the `estimator`'s + :ref:`default evaluation criterion ` is used. + + If `scoring` represents multiple scores, one can use: + + - a list or tuple of unique strings; + - a callable returning a dictionary where the keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables as values. + + See :ref:`multimetric_grid_search` for an example. + + n_jobs : int, 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 ` + for more details. + + .. versionchanged:: v0.20 + `n_jobs` default changed from 1 to None + + refit : bool, str, or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + For multiple metric evaluation, this needs to be a `str` denoting the + scorer that would be used to find the best parameters for refitting + the estimator at the end. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``GridSearchCV`` instance. + + Also for multiple metric evaluation, the attributes ``best_index_``, + ``best_score_`` and ``best_params_`` will only be available if + ``refit`` is set and all of them will be determined w.r.t this specific + scorer. + + See ``scoring`` parameter to know more about multiple metric + evaluation. + + See :ref:`sphx_glr_auto_examples_model_selection_plot_grid_search_digits.py` + to see how to design a custom selection strategy using a callable + via `refit`. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + .. versionchanged:: 0.20 + Support for callable added. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + verbose : int + Controls the verbosity: the higher, the more messages. + + - >1 : the computation time for each fold and parameter candidate is + displayed; + - >2 : the score is also displayed; + - >3 : the fold and candidate parameter indexes are also displayed + together with the starting time of the computation. + + pre_dispatch : int, or str, default='2*n_jobs' + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - None, in which case all the jobs are immediately created and spawned. Use + this for lightweight and fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + - An int, giving the exact number of total jobs that are spawned + - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' + + 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. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + 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. + + .. versionadded:: 0.19 + + .. versionchanged:: 0.21 + Default value was changed from ``True`` to ``False`` + + Attributes + ---------- + 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``. + + For instance the below given table + + +------------+-----------+------------+-----------------+---+---------+ + |param_kernel|param_gamma|param_degree|split0_test_score|...|rank_t...| + +============+===========+============+=================+===+=========+ + | 'poly' | -- | 2 | 0.80 |...| 2 | + +------------+-----------+------------+-----------------+---+---------+ + | 'poly' | -- | 3 | 0.70 |...| 4 | + +------------+-----------+------------+-----------------+---+---------+ + | 'rbf' | 0.1 | -- | 0.80 |...| 3 | + +------------+-----------+------------+-----------------+---+---------+ + | 'rbf' | 0.2 | -- | 0.93 |...| 1 | + +------------+-----------+------------+-----------------+---+---------+ + + will be represented by a ``cv_results_`` dict of:: + + { + 'param_kernel': masked_array(data = ['poly', 'poly', 'rbf', 'rbf'], + mask = [False False False False]...) + 'param_gamma': masked_array(data = [-- -- 0.1 0.2], + mask = [ True True False False]...), + 'param_degree': masked_array(data = [2.0 3.0 -- --], + mask = [False False True True]...), + 'split0_test_score' : [0.80, 0.70, 0.80, 0.93], + 'split1_test_score' : [0.82, 0.50, 0.70, 0.78], + 'mean_test_score' : [0.81, 0.60, 0.75, 0.85], + 'std_test_score' : [0.01, 0.10, 0.05, 0.08], + 'rank_test_score' : [2, 4, 3, 1], + 'split0_train_score' : [0.80, 0.92, 0.70, 0.93], + 'split1_train_score' : [0.82, 0.55, 0.70, 0.87], + 'mean_train_score' : [0.81, 0.74, 0.70, 0.90], + 'std_train_score' : [0.01, 0.19, 0.00, 0.03], + 'mean_fit_time' : [0.73, 0.63, 0.43, 0.49], + 'std_fit_time' : [0.01, 0.02, 0.01, 0.01], + 'mean_score_time' : [0.01, 0.06, 0.04, 0.04], + 'std_score_time' : [0.00, 0.00, 0.00, 0.01], + 'params' : [{'kernel': 'poly', 'degree': 2}, ...], + } + + NOTE + + The key ``'params'`` is used to store a list of parameter + settings dicts for all the parameter candidates. + + The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and + ``std_score_time`` are all in seconds. + + For multi-metric evaluation, the scores for all the scorers are + available in the ``cv_results_`` dict at the keys ending with that + scorer's name (``'_'``) instead of ``'_score'`` shown + above. ('split0_test_precision', 'mean_train_precision' etc.) + + best_estimator_ : estimator + 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``. + + See ``refit`` parameter for more information on allowed values. + + best_score_ : float + Mean cross-validated score of the best_estimator + + For multi-metric evaluation, this is present only if ``refit`` is + specified. + + This attribute is not available if ``refit`` is a function. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + For multi-metric evaluation, this is present only if ``refit`` is + specified. + + 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_``). + + For multi-metric evaluation, this is present only if ``refit`` is + specified. + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + For multi-metric evaluation, this attribute holds the validated + ``scoring`` dict which maps the scorer key to the scorer callable. + + 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. + + .. versionadded:: 0.20 + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + See Also + -------- + ParameterGrid : Generates all the combinations of a hyperparameter grid. + train_test_split : Utility function to split the data into a development + set usable for fitting a GridSearchCV instance and an evaluation set + for its final evaluation. + sklearn.metrics.make_scorer : Make a scorer from a performance metric or + loss function. + + Notes + ----- + The parameters selected are those that maximize the score of the left out + data, unless an explicit score is passed in which case it is used instead. + + If `n_jobs` was set to a value higher than one, the data is copied for each + point in the grid (and not `n_jobs` times). This is done for efficiency + reasons if individual jobs take very little time, but may raise errors if + the dataset is large and not enough memory is available. A workaround in + this case is to set `pre_dispatch`. Then, the memory is copied only + `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * + n_jobs`. + + Examples + -------- + >>> from sklearn import svm, datasets + >>> from sklearn.model_selection import GridSearchCV + >>> iris = datasets.load_iris() + >>> parameters = {'kernel':('linear', 'rbf'), 'C':[1, 10]} + >>> svc = svm.SVC() + >>> clf = GridSearchCV(svc, parameters) + >>> clf.fit(iris.data, iris.target) + GridSearchCV(estimator=SVC(), + param_grid={'C': [1, 10], 'kernel': ('linear', 'rbf')}) + >>> sorted(clf.cv_results_.keys()) + ['mean_fit_time', 'mean_score_time', 'mean_test_score',... + 'param_C', 'param_kernel', 'params',... + 'rank_test_score', 'split0_test_score',... + 'split2_test_score', ... + 'std_fit_time', 'std_score_time', 'std_test_score'] + """ + + _parameter_constraints: dict = { + **BaseSearchCV._parameter_constraints, + "param_grid": [dict, list], + } + + def __init__( + self, + estimator, + param_grid, + *, + scoring=None, + n_jobs=None, + refit=True, + cv=None, + verbose=0, + pre_dispatch="2*n_jobs", + error_score=np.nan, + return_train_score=False, + ): + super().__init__( + estimator=estimator, + scoring=scoring, + n_jobs=n_jobs, + refit=refit, + cv=cv, + verbose=verbose, + pre_dispatch=pre_dispatch, + error_score=error_score, + return_train_score=return_train_score, + ) + self.param_grid = param_grid + + def _run_search(self, evaluate_candidates): + """Search all candidates in param_grid""" + evaluate_candidates(ParameterGrid(self.param_grid)) + + +class RandomizedSearchCV(BaseSearchCV): + """Randomized search on hyper parameters. + + RandomizedSearchCV implements a "fit" and a "score" method. + It also implements "score_samples", "predict", "predict_proba", + "decision_function", "transform" and "inverse_transform" if they are + implemented in the estimator used. + + The parameters of the estimator used to apply these methods are optimized + by cross-validated search over parameter settings. + + In contrast to GridSearchCV, not all parameter values are tried out, but + rather a fixed number of parameter settings is sampled from the specified + distributions. The number of parameter settings that are tried is + given by n_iter. + + If all parameters are presented as a list, + sampling without replacement is performed. If at least one parameter + is given as a distribution, sampling with replacement is used. + It is highly recommended to use continuous distributions for continuous + parameters. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.14 + + Parameters + ---------- + estimator : estimator object + An object of that type is instantiated for each grid point. + 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 or list of dicts + Dictionary with parameters names (`str`) 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. + If a list of dicts is given, first a dict is sampled uniformly, and + then a parameter is sampled using that dict as above. + + n_iter : int, default=10 + Number of parameter settings that are sampled. n_iter trades + off runtime vs quality of the solution. + + scoring : str, callable, list, tuple or dict, default=None + Strategy to evaluate the performance of the cross-validated model on + the test set. + + If `scoring` represents a single score, one can use: + + - a single string (see :ref:`scoring_string_names`); + - a callable (see :ref:`scoring_callable`) that returns a single value; + - `None`, the `estimator`'s + :ref:`default evaluation criterion ` is used. + + If `scoring` represents multiple scores, one can use: + + - a list or tuple of unique strings; + - a callable returning a dictionary where the keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables as values. + + See :ref:`multimetric_grid_search` for an example. + + If None, the estimator's score method is used. + + n_jobs : int, 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 ` + for more details. + + .. versionchanged:: v0.20 + `n_jobs` default changed from 1 to None + + refit : bool, str, or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + For multiple metric evaluation, this needs to be a `str` denoting the + scorer that would be used to find the best parameters for refitting + the estimator at the end. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given the ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``RandomizedSearchCV`` instance. + + Also for multiple metric evaluation, the attributes ``best_index_``, + ``best_score_`` and ``best_params_`` will only be available if + ``refit`` is set and all of them will be determined w.r.t this specific + scorer. + + See ``scoring`` parameter to know more about multiple metric + evaluation. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + .. versionchanged:: 0.20 + Support for callable added. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - integer, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For integer/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + verbose : int + Controls the verbosity: the higher, the more messages. + + - >1 : the computation time for each fold and parameter candidate is + displayed; + - >2 : the score is also displayed; + - >3 : the fold and candidate parameter indexes are also displayed + together with the starting time of the computation. + + pre_dispatch : int, or str, default='2*n_jobs' + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - None, in which case all the jobs are immediately created and spawned. Use + this for lightweight and fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + - An int, giving the exact number of total jobs that are spawned + - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' + + random_state : int, RandomState instance or None, default=None + Pseudo random number generator state 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 `. + + 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. If a numeric value is given, + FitFailedWarning is raised. This parameter does not affect the refit + step, which will always raise the error. + + 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. + + .. versionadded:: 0.19 + + .. versionchanged:: 0.21 + Default value was changed from ``True`` to ``False`` + + Attributes + ---------- + 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``. + + For instance the below given table + + +--------------+-------------+-------------------+---+---------------+ + | param_kernel | param_gamma | split0_test_score |...|rank_test_score| + +==============+=============+===================+===+===============+ + | 'rbf' | 0.1 | 0.80 |...| 1 | + +--------------+-------------+-------------------+---+---------------+ + | 'rbf' | 0.2 | 0.84 |...| 3 | + +--------------+-------------+-------------------+---+---------------+ + | 'rbf' | 0.3 | 0.70 |...| 2 | + +--------------+-------------+-------------------+---+---------------+ + + will be represented by a ``cv_results_`` dict of:: + + { + 'param_kernel' : masked_array(data = ['rbf', 'rbf', 'rbf'], + mask = False), + 'param_gamma' : masked_array(data = [0.1 0.2 0.3], mask = False), + 'split0_test_score' : [0.80, 0.84, 0.70], + 'split1_test_score' : [0.82, 0.50, 0.70], + 'mean_test_score' : [0.81, 0.67, 0.70], + 'std_test_score' : [0.01, 0.24, 0.00], + 'rank_test_score' : [1, 3, 2], + 'split0_train_score' : [0.80, 0.92, 0.70], + 'split1_train_score' : [0.82, 0.55, 0.70], + 'mean_train_score' : [0.81, 0.74, 0.70], + 'std_train_score' : [0.01, 0.19, 0.00], + 'mean_fit_time' : [0.73, 0.63, 0.43], + 'std_fit_time' : [0.01, 0.02, 0.01], + 'mean_score_time' : [0.01, 0.06, 0.04], + 'std_score_time' : [0.00, 0.00, 0.00], + 'params' : [{'kernel' : 'rbf', 'gamma' : 0.1}, ...], + } + + NOTE + + The key ``'params'`` is used to store a list of parameter + settings dicts for all the parameter candidates. + + The ``mean_fit_time``, ``std_fit_time``, ``mean_score_time`` and + ``std_score_time`` are all in seconds. + + For multi-metric evaluation, the scores for all the scorers are + available in the ``cv_results_`` dict at the keys ending with that + scorer's name (``'_'``) instead of ``'_score'`` shown + above. ('split0_test_precision', 'mean_train_precision' etc.) + + best_estimator_ : estimator + 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``. + + For multi-metric evaluation, this attribute is present only if + ``refit`` is specified. + + See ``refit`` parameter for more information on allowed values. + + best_score_ : float + Mean cross-validated score of the best_estimator. + + For multi-metric evaluation, this is not available if ``refit`` is + ``False``. See ``refit`` parameter for more information. + + This attribute is not available if ``refit`` is a function. + + best_params_ : dict + Parameter setting that gave the best results on the hold out data. + + For multi-metric evaluation, this is not available if ``refit`` is + ``False``. See ``refit`` parameter for more information. + + 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_``). + + For multi-metric evaluation, this is not available if ``refit`` is + ``False``. See ``refit`` parameter for more information. + + scorer_ : function or a dict + Scorer function used on the held out data to choose the best + parameters for the model. + + For multi-metric evaluation, this attribute holds the validated + ``scoring`` dict which maps the scorer key to the scorer callable. + + 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. + + .. versionadded:: 0.20 + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + See Also + -------- + GridSearchCV : Does exhaustive search over a grid of parameters. + ParameterSampler : A generator over parameter settings, constructed from + param_distributions. + + Notes + ----- + The parameters selected are those that maximize the score of the held-out + data, according to the scoring parameter. + + If `n_jobs` was set to a value higher than one, the data is copied for each + parameter setting(and not `n_jobs` times). This is done for efficiency + reasons if individual jobs take very little time, but may raise errors if + the dataset is large and not enough memory is available. A workaround in + this case is to set `pre_dispatch`. Then, the memory is copied only + `pre_dispatch` many times. A reasonable value for `pre_dispatch` is `2 * + n_jobs`. + + Examples + -------- + >>> from sklearn.datasets import load_iris + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.model_selection import RandomizedSearchCV + >>> from scipy.stats import uniform + >>> iris = load_iris() + >>> logistic = LogisticRegression(solver='saga', tol=1e-2, max_iter=200, + ... random_state=0) + >>> distributions = dict(C=uniform(loc=0, scale=4), + ... penalty=['l2', 'l1']) + >>> clf = RandomizedSearchCV(logistic, distributions, random_state=0) + >>> search = clf.fit(iris.data, iris.target) + >>> search.best_params_ + {'C': np.float64(2.195...), 'penalty': 'l1'} + """ + + _parameter_constraints: dict = { + **BaseSearchCV._parameter_constraints, + "param_distributions": [dict, list], + "n_iter": [Interval(numbers.Integral, 1, None, closed="left")], + "random_state": ["random_state"], + } + + def __init__( + self, + estimator, + param_distributions, + *, + n_iter=10, + scoring=None, + n_jobs=None, + refit=True, + cv=None, + verbose=0, + pre_dispatch="2*n_jobs", + random_state=None, + error_score=np.nan, + return_train_score=False, + ): + self.param_distributions = param_distributions + self.n_iter = n_iter + self.random_state = random_state + super().__init__( + estimator=estimator, + scoring=scoring, + n_jobs=n_jobs, + refit=refit, + cv=cv, + verbose=verbose, + pre_dispatch=pre_dispatch, + error_score=error_score, + return_train_score=return_train_score, + ) + + def _run_search(self, evaluate_candidates): + """Search n_iter candidates from param_distributions""" + evaluate_candidates( + ParameterSampler( + self.param_distributions, self.n_iter, random_state=self.random_state + ) + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search_successive_halving.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search_successive_halving.py new file mode 100644 index 0000000000000000000000000000000000000000..bcd9a83e6dc4394c1ab75713a4373dd0709e90cf --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_search_successive_halving.py @@ -0,0 +1,1095 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from abc import abstractmethod +from math import ceil, floor, log +from numbers import Integral, Real + +import numpy as np + +from ..base import _fit_context, is_classifier +from ..metrics._scorer import get_scorer_names +from ..utils import resample +from ..utils._param_validation import Interval, StrOptions +from ..utils.multiclass import check_classification_targets +from ..utils.validation import _num_samples, validate_data +from . import ParameterGrid, ParameterSampler +from ._search import BaseSearchCV +from ._split import _yields_constant_splits, check_cv + +__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, **kwargs): + for train_idx, test_idx in self.base_cv.split(X, y, **kwargs): + train_idx = resample( + train_idx, + replace=False, + random_state=self.random_state, + n_samples=int(self.fraction * len(train_idx)), + ) + if self.subsample_test: + test_idx = resample( + test_idx, + replace=False, + random_state=self.random_state, + n_samples=int(self.fraction * len(test_idx)), + ) + yield train_idx, test_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) + scores = mean_test_score[iter_indices] + # argsort() places NaNs at the end of the array so we move NaNs to the + # front of the array so the last `k` items are the those with the + # highest scores. + sorted_indices = np.roll(np.argsort(scores), np.count_nonzero(np.isnan(scores))) + 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 + """ + + _parameter_constraints: dict = { + **BaseSearchCV._parameter_constraints, + # overwrite `scoring` since multi-metrics are not supported + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "random_state": ["random_state"], + "max_resources": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"auto"}), + ], + "min_resources": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"exhaust", "smallest"}), + ], + "resource": [str], + "factor": [Interval(Real, 0, None, closed="neither")], + "aggressive_elimination": ["boolean"], + } + _parameter_constraints.pop("pre_dispatch") # not used in this class + + 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, + ): + 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, split_params): + # 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, 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'." + ) + + 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, **split_params) + # please see https://gph.is/1KjihQe for a justification + magic_factor = 2 + self.min_resources_ = n_splits * magic_factor + if is_classifier(self.estimator): + y = validate_data(self, X="no_validation", y=y) + check_classification_targets(y) + 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( + "resource can only be 'n_samples' when max_resources='auto'" + ) + 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_}." + ) + + if self.min_resources_ == 0: + raise ValueError( + f"min_resources_={self.min_resources_}: you might have passed " + "an empty dataset X." + ) + + @staticmethod + def _select_best_index(refit, refit_metric, 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. + + Currently, we only support for a single metric thus `refit` and + `refit_metric` are not required. + """ + last_iter = np.max(results["iter"]) + last_iter_indices = np.flatnonzero(results["iter"] == last_iter) + + test_scores = results["mean_test_score"][last_iter_indices] + # If all scores are NaNs there is no way to pick between them, + # so we (arbitrarily) declare the zero'th entry the best one + if np.isnan(test_scores).all(): + best_idx = 0 + else: + best_idx = np.nanargmax(test_scores) + + return last_iter_indices[best_idx] + + @_fit_context( + # Halving*SearchCV.estimator is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, **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. + + **params : dict of string -> object + Parameters passed to the ``fit`` method of the estimator. + + Returns + ------- + self : object + Instance of fitted estimator. + """ + self._checked_cv_orig = check_cv( + self.cv, y, classifier=is_classifier(self.estimator) + ) + + routed_params = self._get_routed_params_for_fit(params) + self._check_input_parameters( + X=X, y=y, split_params=routed_params.splitter.split + ) + + self._n_samples_orig = _num_samples(X) + + super().fit(X, y=y, **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 `. + + .. 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_halving_search_cv``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_halving_search_cv # 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 + classification 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. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. 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 : str or callable, default=None + Scoring method to use to evaluate the predictions on the test set. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + refit : bool or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``HalvingGridSearchCV`` instance. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + 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 `. + + 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 ` + 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 lots of information + for analysing the results of a search. + Please refer to the :ref:`User guide` + 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. + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + 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. + + All parameter combinations scored with a NaN will share the lowest rank. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_halving_search_cv # 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} + """ + + _parameter_constraints: dict = { + **BaseSuccessiveHalving._parameter_constraints, + "param_grid": [dict, list], + } + + 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 + + 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`. + + .. 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_halving_search_cv``:: + + >>> # explicitly require this experimental feature + >>> from sklearn.experimental import enable_halving_search_cv # 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 or list of dicts + Dictionary with parameters names (`str`) 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. + If a list of dicts is given, first a dict is sampled uniformly, and + then a parameter is sampled using that dict as above. + + n_candidates : "exhaust" or 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 + classification 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. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. 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 : str or callable, default=None + Scoring method to use to evaluate the predictions on the test set. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + refit : bool or callable, default=True + Refit an estimator using the best found parameters on the whole + dataset. + + Where there are considerations other than maximum score in + choosing a best estimator, ``refit`` can be set to a function which + returns the selected ``best_index_`` given ``cv_results_``. In that + case, the ``best_estimator_`` and ``best_params_`` will be set + according to the returned ``best_index_`` while the ``best_score_`` + attribute will not be available. + + The refitted estimator is made available at the ``best_estimator_`` + attribute and permits using ``predict`` directly on this + ``HalvingRandomSearchCV`` instance. + + See :ref:`this example + ` + for an example of how to use ``refit=callable`` to balance model + complexity and cross-validated score. + + 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 `. + + 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 ` + 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 lots of information + for analysing the results of a search. + Please refer to the :ref:`User guide` + 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. + + multimetric_ : bool + Whether or not the scorers compute several metrics. + + classes_ : ndarray of shape (n_classes,) + The classes labels. This is present only if ``refit`` is specified and + the underlying estimator is a classifier. + + n_features_in_ : int + Number of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `n_features_in_` when fit. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Only defined if + `best_estimator_` is defined (see the documentation for the `refit` + parameter for more details) and that `best_estimator_` exposes + `feature_names_in_` when fit. + + .. versionadded:: 1.0 + + 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. + + All parameter combinations scored with a NaN will share the lowest rank. + + Examples + -------- + + >>> from sklearn.datasets import load_iris + >>> from sklearn.ensemble import RandomForestClassifier + >>> from sklearn.experimental import enable_halving_search_cv # noqa + >>> from sklearn.model_selection import HalvingRandomSearchCV + >>> from scipy.stats import randint + >>> import numpy as np + ... + >>> 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} + """ + + _parameter_constraints: dict = { + **BaseSuccessiveHalving._parameter_constraints, + "param_distributions": [dict, list], + "n_candidates": [ + Interval(Integral, 0, None, closed="neither"), + StrOptions({"exhaust"}), + ], + } + + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_split.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_split.py new file mode 100644 index 0000000000000000000000000000000000000000..640b7f6eee2f02c0f7f22d89b8d9523d36ddc27f --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_split.py @@ -0,0 +1,3055 @@ +""" +The :mod:`sklearn.model_selection._split` module includes classes and +functions to split the data based on a preset strategy. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import warnings +from abc import ABCMeta, abstractmethod +from collections import defaultdict +from collections.abc import Iterable +from inspect import signature +from itertools import chain, combinations +from math import ceil, floor + +import numpy as np +from scipy.special import comb + +from ..utils import ( + _safe_indexing, + check_random_state, + indexable, + metadata_routing, +) +from ..utils._array_api import ( + _convert_to_numpy, + ensure_common_namespace_device, + get_namespace, +) +from ..utils._param_validation import Interval, RealNotInt, validate_params +from ..utils.extmath import _approximate_mode +from ..utils.metadata_routing import _MetadataRequester +from ..utils.multiclass import type_of_target +from ..utils.validation import _num_samples, check_array, column_or_1d + +__all__ = [ + "BaseCrossValidator", + "GroupKFold", + "GroupShuffleSplit", + "KFold", + "LeaveOneGroupOut", + "LeaveOneOut", + "LeavePGroupsOut", + "LeavePOut", + "PredefinedSplit", + "RepeatedKFold", + "RepeatedStratifiedKFold", + "ShuffleSplit", + "StratifiedGroupKFold", + "StratifiedKFold", + "StratifiedShuffleSplit", + "check_cv", + "train_test_split", +] + + +class _UnsupportedGroupCVMixin: + """Mixin for splitters that do not support Groups.""" + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + if groups is not None: + warnings.warn( + f"The groups parameter is ignored by {self.__class__.__name__}", + UserWarning, + ) + return super().split(X, y, groups=groups) + + +class GroupsConsumerMixin(_MetadataRequester): + """A Mixin to ``groups`` by default. + + This Mixin makes the object to request ``groups`` by default as ``True``. + + .. versionadded:: 1.3 + """ + + __metadata_request__split = {"groups": True} + + +class BaseCrossValidator(_MetadataRequester, metaclass=ABCMeta): + """Base class for all cross-validators. + + Implementations must define `_iter_test_masks` or `_iter_test_indices`. + """ + + # This indicates that by default CV splitters don't have a "groups" kwarg, + # unless indicated by inheriting from ``GroupsConsumerMixin``. + # This also prevents ``set_split_request`` to be generated for splitters + # which don't support ``groups``. + __metadata_request__split = {"groups": metadata_routing.UNUSED} + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + X, y, groups = indexable(X, y, groups) + indices = np.arange(_num_samples(X)) + for test_index in self._iter_test_masks(X, y, groups): + train_index = indices[np.logical_not(test_index)] + test_index = indices[test_index] + yield train_index, test_index + + # Since subclasses must implement either _iter_test_masks or + # _iter_test_indices, neither can be abstract. + def _iter_test_masks(self, X=None, y=None, groups=None): + """Generates boolean masks corresponding to test sets. + + By default, delegates to _iter_test_indices(X, y, groups) + """ + for test_index in self._iter_test_indices(X, y, groups): + test_mask = np.zeros(_num_samples(X), dtype=bool) + test_mask[test_index] = True + yield test_mask + + def _iter_test_indices(self, X=None, y=None, groups=None): + """Generates integer indices corresponding to test sets.""" + raise NotImplementedError + + @abstractmethod + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator.""" + + def __repr__(self): + return _build_repr(self) + + +class LeaveOneOut(_UnsupportedGroupCVMixin, BaseCrossValidator): + """Leave-One-Out cross-validator. + + Provides train/test indices to split data in train/test sets. Each + sample is used once as a test set (singleton) while the remaining + samples form the training set. + + Note: ``LeaveOneOut()`` is equivalent to ``KFold(n_splits=n)`` and + ``LeavePOut(p=1)`` where ``n`` is the number of samples. + + Due to the high number of test sets (which is the same as the + number of samples) this cross-validation method can be very costly. + For large datasets one should favor :class:`KFold`, :class:`ShuffleSplit` + or :class:`StratifiedKFold`. + + Read more in the :ref:`User Guide `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import LeaveOneOut + >>> X = np.array([[1, 2], [3, 4]]) + >>> y = np.array([1, 2]) + >>> loo = LeaveOneOut() + >>> loo.get_n_splits(X) + 2 + >>> print(loo) + LeaveOneOut() + >>> for i, (train_index, test_index) in enumerate(loo.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[1] + Test: index=[0] + Fold 1: + Train: index=[0] + Test: index=[1] + + See Also + -------- + LeaveOneGroupOut : For splitting the data according to explicit, + domain-specific stratification of the dataset. + GroupKFold : K-fold iterator variant with non-overlapping groups. + """ + + def _iter_test_indices(self, X, y=None, groups=None): + n_samples = _num_samples(X) + if n_samples <= 1: + raise ValueError( + "Cannot perform LeaveOneOut with n_samples={}.".format(n_samples) + ) + return range(n_samples) + + def get_n_splits(self, X, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + if X is None: + raise ValueError("The 'X' parameter should not be None.") + return _num_samples(X) + + +class LeavePOut(_UnsupportedGroupCVMixin, BaseCrossValidator): + """Leave-P-Out cross-validator. + + Provides train/test indices to split data in train/test sets. This results + in testing on all distinct samples of size p, while the remaining n - p + samples form the training set in each iteration. + + Note: ``LeavePOut(p)`` is NOT equivalent to + ``KFold(n_splits=n_samples // p)`` which creates non-overlapping test sets. + + Due to the high number of iterations which grows combinatorically with the + number of samples this cross-validation method can be very costly. For + large datasets one should favor :class:`KFold`, :class:`StratifiedKFold` + or :class:`ShuffleSplit`. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + p : int + Size of the test sets. Must be strictly less than the number of + samples. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import LeavePOut + >>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + >>> y = np.array([1, 2, 3, 4]) + >>> lpo = LeavePOut(2) + >>> lpo.get_n_splits(X) + 6 + >>> print(lpo) + LeavePOut(p=2) + >>> for i, (train_index, test_index) in enumerate(lpo.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[2 3] + Test: index=[0 1] + Fold 1: + Train: index=[1 3] + Test: index=[0 2] + Fold 2: + Train: index=[1 2] + Test: index=[0 3] + Fold 3: + Train: index=[0 3] + Test: index=[1 2] + Fold 4: + Train: index=[0 2] + Test: index=[1 3] + Fold 5: + Train: index=[0 1] + Test: index=[2 3] + """ + + def __init__(self, p): + self.p = p + + def _iter_test_indices(self, X, y=None, groups=None): + n_samples = _num_samples(X) + if n_samples <= self.p: + raise ValueError( + "p={} must be strictly less than the number of samples={}".format( + self.p, n_samples + ) + ) + for combination in combinations(range(n_samples), self.p): + yield np.array(combination) + + def get_n_splits(self, X, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + """ + if X is None: + raise ValueError("The 'X' parameter should not be None.") + return int(comb(_num_samples(X), self.p, exact=True)) + + +class _BaseKFold(BaseCrossValidator, metaclass=ABCMeta): + """Base class for K-Fold cross-validators and TimeSeriesSplit.""" + + @abstractmethod + def __init__(self, n_splits, *, shuffle, random_state): + if not isinstance(n_splits, numbers.Integral): + raise ValueError( + "The number of folds must be of Integral type. " + "%s of type %s was passed." % (n_splits, type(n_splits)) + ) + n_splits = int(n_splits) + + if n_splits <= 1: + raise ValueError( + "k-fold cross-validation requires at least one" + " train/test split by setting n_splits=2 or more," + " got n_splits={0}.".format(n_splits) + ) + + if not isinstance(shuffle, bool): + raise TypeError("shuffle must be True or False; got {0}".format(shuffle)) + + if not shuffle and random_state is not None: # None is the default + raise ValueError( + ( + "Setting a random_state has no effect since shuffle is " + "False. You should leave " + "random_state to its default (None), or set shuffle=True." + ), + ) + + self.n_splits = n_splits + self.shuffle = shuffle + self.random_state = random_state + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,), default=None + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + X, y, groups = indexable(X, y, groups) + n_samples = _num_samples(X) + if self.n_splits > n_samples: + raise ValueError( + ( + "Cannot have number of splits n_splits={0} greater" + " than the number of samples: n_samples={1}." + ).format(self.n_splits, n_samples) + ) + + for train, test in super().split(X, y, groups): + yield train, test + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + return self.n_splits + + +class KFold(_UnsupportedGroupCVMixin, _BaseKFold): + """K-Fold cross-validator. + + Provides train/test indices to split data in train/test sets. Split + dataset into k consecutive folds (without shuffling by default). + + Each fold is then used once as a validation while the k - 1 remaining + folds form the training set. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + .. versionchanged:: 0.22 + ``n_splits`` default value changed from 3 to 5. + + shuffle : bool, default=False + Whether to shuffle the data before splitting into batches. + Note that the samples within each split will not be shuffled. + + random_state : int, RandomState instance or None, default=None + When `shuffle` is True, `random_state` affects the ordering of the + indices, which controls the randomness of each fold. Otherwise, this + parameter has no effect. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import KFold + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([1, 2, 3, 4]) + >>> kf = KFold(n_splits=2) + >>> kf.get_n_splits(X) + 2 + >>> print(kf) + KFold(n_splits=2, random_state=None, shuffle=False) + >>> for i, (train_index, test_index) in enumerate(kf.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[2 3] + Test: index=[0 1] + Fold 1: + Train: index=[0 1] + Test: index=[2 3] + + Notes + ----- + The first ``n_samples % n_splits`` folds have size + ``n_samples // n_splits + 1``, other folds have size + ``n_samples // n_splits``, where ``n_samples`` is the number of samples. + + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + + See Also + -------- + StratifiedKFold : Takes class information into account to avoid building + folds with imbalanced class distributions (for binary or multiclass + classification tasks). + + GroupKFold : K-fold iterator variant with non-overlapping groups. + + RepeatedKFold : Repeats K-Fold n times. + """ + + 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=None, groups=None): + n_samples = _num_samples(X) + indices = np.arange(n_samples) + if self.shuffle: + check_random_state(self.random_state).shuffle(indices) + + n_splits = self.n_splits + fold_sizes = np.full(n_splits, n_samples // n_splits, dtype=int) + fold_sizes[: n_samples % n_splits] += 1 + current = 0 + for fold_size in fold_sizes: + start, stop = current, current + fold_size + yield indices[start:stop] + current = stop + + +class GroupKFold(GroupsConsumerMixin, _BaseKFold): + """K-fold iterator variant with non-overlapping groups. + + Each group will appear exactly once in the test set across all folds (the + number of distinct groups has to be at least equal to the number of folds). + + The folds are approximately balanced in the sense that the number of + samples is approximately the same in each test fold when `shuffle` is True. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + .. versionchanged:: 0.22 + ``n_splits`` default value changed from 3 to 5. + + shuffle : bool, default=False + Whether to shuffle the groups before splitting into batches. + Note that the samples within each split will not be shuffled. + + .. versionadded:: 1.6 + + random_state : int, RandomState instance or None, default=None + When `shuffle` is True, `random_state` affects the ordering of the + indices, which controls the randomness of each fold. Otherwise, this + parameter has no effect. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + .. versionadded:: 1.6 + + Notes + ----- + Groups appear in an arbitrary order throughout the folds. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import GroupKFold + >>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]) + >>> y = np.array([1, 2, 3, 4, 5, 6]) + >>> groups = np.array([0, 0, 2, 2, 3, 3]) + >>> group_kfold = GroupKFold(n_splits=2) + >>> group_kfold.get_n_splits(X, y, groups) + 2 + >>> print(group_kfold) + GroupKFold(n_splits=2, random_state=None, shuffle=False) + >>> for i, (train_index, test_index) in enumerate(group_kfold.split(X, y, groups)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}, group={groups[train_index]}") + ... print(f" Test: index={test_index}, group={groups[test_index]}") + Fold 0: + Train: index=[2 3], group=[2 2] + Test: index=[0 1 4 5], group=[0 0 3 3] + Fold 1: + Train: index=[0 1 4 5], group=[0 0 3 3] + Test: index=[2 3], group=[2 2] + + See Also + -------- + LeaveOneGroupOut : For splitting the data according to explicit + domain-specific stratification of the dataset. + + StratifiedKFold : Takes class information into account to avoid building + folds with imbalanced class proportions (for binary or multiclass + classification tasks). + """ + + def __init__(self, n_splits=5, *, shuffle=False, random_state=None): + super().__init__(n_splits, shuffle=shuffle, random_state=random_state) + + 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, input_name="groups", ensure_2d=False, dtype=None) + + unique_groups, group_idx = np.unique(groups, return_inverse=True) + n_groups = len(unique_groups) + + if self.n_splits > n_groups: + raise ValueError( + "Cannot have number of splits n_splits=%d greater" + " than the number of groups: %d." % (self.n_splits, n_groups) + ) + + if self.shuffle: + # Split and shuffle unique groups across n_splits + rng = check_random_state(self.random_state) + unique_groups = rng.permutation(unique_groups) + split_groups = np.array_split(unique_groups, self.n_splits) + + for test_group_ids in split_groups: + test_mask = np.isin(groups, test_group_ids) + yield np.where(test_mask)[0] + + else: + # Weight groups by their number of occurrences + n_samples_per_group = np.bincount(group_idx) + + # Distribute the most frequent groups first + indices = np.argsort(n_samples_per_group)[::-1] + n_samples_per_group = n_samples_per_group[indices] + + # Total weight of each fold + n_samples_per_fold = np.zeros(self.n_splits) + + # Mapping from group index to fold index + group_to_fold = np.zeros(len(unique_groups)) + + # Distribute samples by adding the largest weight to the lightest fold + for group_index, weight in enumerate(n_samples_per_group): + lightest_fold = np.argmin(n_samples_per_fold) + n_samples_per_fold[lightest_fold] += weight + group_to_fold[indices[group_index]] = lightest_fold + + indices = group_to_fold[group_idx] + + for f in range(self.n_splits): + yield np.where(indices == f)[0] + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,), default=None + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + return super().split(X, y, groups) + + +class StratifiedKFold(_BaseKFold): + """Class-wise stratified K-Fold cross-validator. + + Provides train/test indices to split data in train/test sets. + + This cross-validation object is a variation of KFold that returns + stratified folds. The folds are made by preserving the percentage of + samples for each class in `y` in a binary or multiclass classification + setting. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + .. note:: + + Stratification on the class label solves an engineering problem rather + than a statistical one. See :ref:`stratification` for more details. + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + .. versionchanged:: 0.22 + ``n_splits`` default value changed from 3 to 5. + + 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. + + random_state : int, RandomState instance or None, 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 `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import StratifiedKFold + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 1, 1]) + >>> skf = StratifiedKFold(n_splits=2) + >>> skf.get_n_splits(X, y) + 2 + >>> print(skf) + StratifiedKFold(n_splits=2, random_state=None, shuffle=False) + >>> for i, (train_index, test_index) in enumerate(skf.split(X, y)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[1 3] + Test: index=[0 2] + Fold 1: + Train: index=[0 2] + Test: index=[1 3] + + Notes + ----- + The implementation is designed to: + + * Generate test sets such that all contain the same distribution of + classes, or as close as possible. + * Be invariant to class label: relabelling ``y = ["Happy", "Sad"]`` to + ``y = [1, 0]`` should not change the indices generated. + * Preserve order dependencies in the dataset ordering, when + ``shuffle=False``: all samples from class k in some test set were + contiguous in y, or separated in y by samples from classes other than k. + * Generate test sets where the smallest and largest differ by at most one + sample. + + .. versionchanged:: 0.22 + The previous implementation did not follow the last constraint. + + See Also + -------- + RepeatedStratifiedKFold : Repeats Stratified K-Fold n times. + """ + + def __init__(self, n_splits=5, *, shuffle=False, random_state=None): + super().__init__(n_splits=n_splits, shuffle=shuffle, random_state=random_state) + + def _make_test_folds(self, X, y=None): + rng = check_random_state(self.random_state) + # XXX: as of now, cross-validation splitters only operate in NumPy-land + # without attempting to leverage array API namespace features. However + # they might be fed by array API inputs, e.g. in CV-enabled estimators so + # we need the following explicit conversion: + xp, is_array_api = get_namespace(y) + if is_array_api: + y = _convert_to_numpy(y, xp) + else: + 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_idx, y_inv = np.unique(y, return_index=True, return_inverse=True) + # y_inv encodes y according to lexicographic order. We invert y_idx to + # map the classes so that they are encoded by order of appearance: + # 0 represents the first label appearing in y, 1 the second, etc. + _, class_perm = np.unique(y_idx, return_inverse=True) + y_encoded = class_perm[y_inv] + + n_classes = len(y_idx) + y_counts = np.bincount(y_encoded) + min_groups = np.min(y_counts) + if np.all(self.n_splits > y_counts): + raise ValueError( + "n_splits=%d cannot be greater than the" + " number of members in each class." % (self.n_splits) + ) + if self.n_splits > min_groups: + warnings.warn( + "The least populated class in y has only %d" + " members, which is less than n_splits=%d." + % (min_groups, self.n_splits), + UserWarning, + ) + + # Determine the optimal number of samples from each class in each fold, + # using round robin over the sorted y. (This can be done direct from + # counts, but that code is unreadable.) + y_order = np.sort(y_encoded) + allocation = np.asarray( + [ + np.bincount(y_order[i :: self.n_splits], minlength=n_classes) + for i in range(self.n_splits) + ] + ) + + # To maintain the data order dependencies as best as possible within + # the stratification constraint, we assign samples from each class in + # blocks (and then mess that up when shuffle=True). + test_folds = np.empty(len(y), dtype="i") + for k in range(n_classes): + # since the kth column of allocation stores the number of samples + # of class k in each test set, this generates blocks of fold + # indices corresponding to the allocation for class k. + folds_for_class = np.arange(self.n_splits).repeat(allocation[:, k]) + if self.shuffle: + rng.shuffle(folds_for_class) + test_folds[y_encoded == k] = folds_for_class + return test_folds + + def _iter_test_masks(self, X, y=None, groups=None): + test_folds = self._make_test_folds(X, y) + for i in range(self.n_splits): + yield test_folds == i + + def split(self, X, y, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Note that providing ``y`` is sufficient to generate the splits and + hence ``np.zeros(n_samples)`` may be used as a placeholder for + ``X`` instead of actual training data. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + Stratification is done based on the y labels. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + """ + if groups is not None: + warnings.warn( + f"The groups parameter is ignored by {self.__class__.__name__}", + UserWarning, + ) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) + return super().split(X, y, groups) + + +class StratifiedGroupKFold(GroupsConsumerMixin, _BaseKFold): + """Class-wise stratified K-Fold 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 in `y` in a binary or + multiclass classification setting. + + Each group will appear exactly once in the test set across all folds (the + number of distinct groups has to be at least equal to the number of folds). + + The difference between :class:`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 `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + .. note:: + + Stratification on the class label solves an engineering problem rather + than a statistical one. See :ref:`stratification` for more details. + + 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 `. + + 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]) + >>> sgkf = StratifiedGroupKFold(n_splits=3) + >>> sgkf.get_n_splits(X, y) + 3 + >>> print(sgkf) + StratifiedGroupKFold(n_splits=3, random_state=None, shuffle=False) + >>> for i, (train_index, test_index) in enumerate(sgkf.split(X, y, groups)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" group={groups[train_index]}") + ... print(f" Test: index={test_index}") + ... print(f" group={groups[test_index]}") + Fold 0: + Train: index=[ 0 1 2 3 7 8 9 10 11 15 16] + group=[1 1 2 2 4 5 5 5 5 8 8] + Test: index=[ 4 5 6 12 13 14] + group=[3 3 3 6 6 7] + Fold 1: + Train: index=[ 4 5 6 7 8 9 10 11 12 13 14] + group=[3 3 3 4 5 5 5 5 6 6 7] + Test: index=[ 0 1 2 3 15 16] + group=[1 1 2 2 8 8] + Fold 2: + Train: index=[ 0 1 2 3 4 5 6 12 13 14 15 16] + group=[1 1 2 2 3 3 3 6 6 7 8 8] + Test: index=[ 7 8 9 10 11] + group=[4 5 5 5 5] + + 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. + + Provides train/test indices to split time-ordered data, where other + cross-validation methods are inappropriate, as they would lead to training + on future data and evaluating on past data. + To ensure comparable metrics across folds, samples must be equally spaced. + Once this condition is met, each test set covers the same time duration, + while the train set size accumulates data from previous splits. + + This cross-validation object is a variation of :class:`KFold`. + In the k-th split, it returns the first k folds as the train set and the + (k+1)-th fold as the test set. + + Note that, unlike standard cross-validation methods, successive + training sets are supersets of those that come before them. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + .. versionadded:: 0.18 + + Parameters + ---------- + n_splits : int, default=5 + Number of splits. Must be at least 2. + + .. versionchanged:: 0.22 + ``n_splits`` default value changed from 3 to 5. + + 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``. + + .. versionadded:: 0.24 + + gap : int, default=0 + Number of samples to exclude from the end of each train set before + the test set. + + .. versionadded:: 0.24 + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import TimeSeriesSplit + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([1, 2, 3, 4, 5, 6]) + >>> tscv = TimeSeriesSplit() + >>> print(tscv) + TimeSeriesSplit(gap=0, max_train_size=None, n_splits=5, test_size=None) + >>> for i, (train_index, test_index) in enumerate(tscv.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[0] + Test: index=[1] + Fold 1: + Train: index=[0 1] + Test: index=[2] + Fold 2: + Train: index=[0 1 2] + Test: index=[3] + Fold 3: + Train: index=[0 1 2 3] + Test: index=[4] + Fold 4: + Train: index=[0 1 2 3 4] + Test: index=[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 i, (train_index, test_index) in enumerate(tscv.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[0 1 2 3 4 5] + Test: index=[6 7] + Fold 1: + Train: index=[0 1 2 3 4 5 6 7] + Test: index=[8 9] + Fold 2: + Train: index=[0 1 2 3 4 5 6 7 8 9] + Test: index=[10 11] + >>> # Add in a 2 period gap + >>> tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=2) + >>> for i, (train_index, test_index) in enumerate(tscv.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[0 1 2 3] + Test: index=[6 7] + Fold 1: + Train: index=[0 1 2 3 4 5] + Test: index=[8 9] + Fold 2: + Train: index=[0 1 2 3 4 5 6 7] + Test: index=[10 11] + + For a more extended example see + :ref:`sphx_glr_auto_examples_applications_plot_cyclical_feature_engineering.py`. + + 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)`` by default, + where ``n_samples`` is the number of samples. Note that this + formula is only valid when ``test_size`` and ``max_train_size`` are + left to their default values. + """ + + 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. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,) + Always ignored, exists for compatibility. + + groups : array-like of shape (n_samples,) + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + if groups is not None: + warnings.warn( + f"The groups parameter is ignored by {self.__class__.__name__}", + UserWarning, + ) + return self._split(X) + + def _split(self, X): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + (X,) = indexable(X) + 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( + 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_starts = range(n_samples - n_splits * test_size, n_samples, test_size) + + for test_start in test_starts: + 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[:train_end], + indices[test_start : test_start + test_size], + ) + + +class LeaveOneGroupOut(GroupsConsumerMixin, BaseCrossValidator): + """Leave One Group Out cross-validator. + + Provides train/test indices to split data such that each training set is + comprised of all samples except ones belonging to one specific group. + Arbitrary domain specific group information is provided as an array of integers + that encodes the group of each sample. + + For instance the groups could be the year of collection of the samples + and thus allow for cross-validation against time-based splits. + + Read more in the :ref:`User Guide `. + + Notes + ----- + Splits are ordered according to the index of the group left out. The first + split has testing set consisting of the group whose index in `groups` is + lowest, and so on. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import LeaveOneGroupOut + >>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + >>> y = np.array([1, 2, 1, 2]) + >>> groups = np.array([1, 1, 2, 2]) + >>> logo = LeaveOneGroupOut() + >>> logo.get_n_splits(X, y, groups) + 2 + >>> logo.get_n_splits(groups=groups) # 'groups' is always required + 2 + >>> print(logo) + LeaveOneGroupOut() + >>> for i, (train_index, test_index) in enumerate(logo.split(X, y, groups)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}, group={groups[train_index]}") + ... print(f" Test: index={test_index}, group={groups[test_index]}") + Fold 0: + Train: index=[2 3], group=[2 2] + Test: index=[0 1], group=[1 1] + Fold 1: + Train: index=[0 1], group=[1 1] + Test: index=[2 3], group=[2 2] + + See also + -------- + GroupKFold: K-fold iterator variant with non-overlapping groups. + """ + + 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, input_name="groups", copy=True, ensure_2d=False, dtype=None + ) + unique_groups = np.unique(groups) + if len(unique_groups) <= 1: + raise ValueError( + "The groups parameter contains fewer than 2 unique groups " + "(%s). LeaveOneGroupOut expects at least 2." % unique_groups + ) + for i in unique_groups: + yield groups == i + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. This 'groups' parameter must always be specified to + calculate the number of splits, though the other parameters can be + omitted. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + if groups is None: + raise ValueError("The 'groups' parameter should not be 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): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,), default=None + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + return super().split(X, y, groups) + + +class LeavePGroupsOut(GroupsConsumerMixin, BaseCrossValidator): + """Leave P Group(s) Out cross-validator. + + Provides train/test indices to split data according to a third-party + provided group. This group information can be used to encode arbitrary + domain specific stratifications of the samples as integers. + + For instance the groups could be the year of collection of the samples + and thus allow for cross-validation against time-based splits. + + The difference between LeavePGroupsOut and LeaveOneGroupOut is that + the former builds the test sets with all the samples assigned to + ``p`` different values of the groups while the latter uses samples + all assigned the same groups. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_groups : int + Number of groups (``p``) to leave out in the test split. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import LeavePGroupsOut + >>> X = np.array([[1, 2], [3, 4], [5, 6]]) + >>> y = np.array([1, 2, 1]) + >>> groups = np.array([1, 2, 3]) + >>> lpgo = LeavePGroupsOut(n_groups=2) + >>> lpgo.get_n_splits(X, y, groups) + 3 + >>> lpgo.get_n_splits(groups=groups) # 'groups' is always required + 3 + >>> print(lpgo) + LeavePGroupsOut(n_groups=2) + >>> for i, (train_index, test_index) in enumerate(lpgo.split(X, y, groups)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}, group={groups[train_index]}") + ... print(f" Test: index={test_index}, group={groups[test_index]}") + Fold 0: + Train: index=[2], group=[3] + Test: index=[0 1], group=[1 2] + Fold 1: + Train: index=[1], group=[2] + Test: index=[0 2], group=[1 3] + Fold 2: + Train: index=[0], group=[1] + Test: index=[1 2], group=[2 3] + + See Also + -------- + GroupKFold : K-fold iterator variant with non-overlapping groups. + """ + + def __init__(self, n_groups): + self.n_groups = 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, input_name="groups", copy=True, ensure_2d=False, dtype=None + ) + unique_groups = np.unique(groups) + if self.n_groups >= len(unique_groups): + raise ValueError( + "The groups parameter contains fewer than (or equal to) " + "n_groups (%d) numbers of unique groups (%s). LeavePGroupsOut " + "expects that at least n_groups + 1 (%d) unique groups be " + "present" % (self.n_groups, unique_groups, self.n_groups + 1) + ) + combi = combinations(range(len(unique_groups)), self.n_groups) + for indices in combi: + test_index = np.zeros(_num_samples(X), dtype=bool) + for l in unique_groups[np.array(indices)]: + test_index[groups == l] = True + yield test_index + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. This 'groups' parameter must always be specified to + calculate the number of splits, though the other parameters can be + omitted. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + if groups is None: + raise ValueError("The 'groups' parameter should not be 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): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,), default=None + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + return super().split(X, y, groups) + + +class _RepeatedSplits(_MetadataRequester, metaclass=ABCMeta): + """Repeated splits for an arbitrary randomized CV splitter. + + Repeats splits for cross-validators n times with different randomization + in each repetition. + + Parameters + ---------- + cv : callable + Cross-validator class. + + n_repeats : int, default=10 + Number of times cross-validator needs to be repeated. + + random_state : int, RandomState instance or None, default=None + Passes `random_state` to the arbitrary repeating cross validator. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + **cvargs : additional params + Constructor parameters for cv. Must not contain random_state + and shuffle. + """ + + # This indicates that by default CV splitters don't have a "groups" kwarg, + # unless indicated by inheriting from ``GroupsConsumerMixin``. + # This also prevents ``set_split_request`` to be generated for splitters + # which don't support ``groups``. + __metadata_request__split = {"groups": metadata_routing.UNUSED} + + def __init__(self, cv, *, n_repeats=10, random_state=None, **cvargs): + if not isinstance(n_repeats, numbers.Integral): + raise ValueError("Number of repetitions must be of Integral type.") + + if n_repeats <= 0: + raise ValueError("Number of repetitions must be greater than 0.") + + if any(key in cvargs for key in ("random_state", "shuffle")): + raise ValueError("cvargs must not contain random_state or shuffle.") + + self.cv = cv + self.n_repeats = n_repeats + self.random_state = random_state + self.cvargs = cvargs + + def split(self, X, y=None, groups=None): + """Generates indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + n_repeats = self.n_repeats + rng = check_random_state(self.random_state) + + for idx in range(n_repeats): + cv = self.cv(random_state=rng, shuffle=True, **self.cvargs) + for train_index, test_index in cv.split(X, y, groups): + yield train_index, test_index + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + ``np.zeros(n_samples)`` may be used as a placeholder. + + y : object + Always ignored, exists for compatibility. + ``np.zeros(n_samples)`` may be used as a placeholder. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + rng = check_random_state(self.random_state) + cv = self.cv(random_state=rng, shuffle=True, **self.cvargs) + return cv.get_n_splits(X, y, groups) * self.n_repeats + + def __repr__(self): + return _build_repr(self) + + +class RepeatedKFold(_UnsupportedGroupCVMixin, _RepeatedSplits): + """Repeated K-Fold cross validator. + + Repeats K-Fold `n_repeats` times with different randomization in each repetition. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + n_repeats : int, default=10 + Number of times cross-validator needs to be repeated. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of each repeated cross-validation instance. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import RepeatedKFold + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 1, 1]) + >>> rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=2652124) + >>> rkf.get_n_splits(X, y) + 4 + >>> print(rkf) + RepeatedKFold(n_repeats=2, n_splits=2, random_state=2652124) + >>> for i, (train_index, test_index) in enumerate(rkf.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + ... + Fold 0: + Train: index=[0 1] + Test: index=[2 3] + Fold 1: + Train: index=[2 3] + Test: index=[0 1] + Fold 2: + Train: index=[1 2] + Test: index=[0 3] + Fold 3: + Train: index=[0 3] + Test: index=[1 2] + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + + See Also + -------- + RepeatedStratifiedKFold : Repeats Stratified K-Fold n times. + """ + + def __init__(self, *, n_splits=5, n_repeats=10, random_state=None): + super().__init__( + KFold, n_repeats=n_repeats, random_state=random_state, n_splits=n_splits + ) + + +class RepeatedStratifiedKFold(_UnsupportedGroupCVMixin, _RepeatedSplits): + """Repeated class-wise stratified K-Fold cross validator. + + Repeats Stratified K-Fold n times with different randomization in each + repetition. + + Read more in the :ref:`User Guide `. + + .. note:: + + Stratification on the class label solves an engineering problem rather + than a statistical one. See :ref:`stratification` for more details. + + Parameters + ---------- + n_splits : int, default=5 + Number of folds. Must be at least 2. + + n_repeats : int, default=10 + Number of times cross-validator needs to be repeated. + + random_state : int, RandomState instance or None, default=None + Controls the generation of the random states for each repetition. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import RepeatedStratifiedKFold + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 1, 1]) + >>> rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2, + ... random_state=36851234) + >>> rskf.get_n_splits(X, y) + 4 + >>> print(rskf) + RepeatedStratifiedKFold(n_repeats=2, n_splits=2, random_state=36851234) + >>> for i, (train_index, test_index) in enumerate(rskf.split(X, y)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + ... + Fold 0: + Train: index=[1 2] + Test: index=[0 3] + Fold 1: + Train: index=[0 3] + Test: index=[1 2] + Fold 2: + Train: index=[1 3] + Test: index=[0 2] + Fold 3: + Train: index=[0 2] + Test: index=[1 3] + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + + See Also + -------- + RepeatedKFold : Repeats K-Fold n times. + """ + + def __init__(self, *, n_splits=5, n_repeats=10, random_state=None): + super().__init__( + StratifiedKFold, + n_repeats=n_repeats, + random_state=random_state, + n_splits=n_splits, + ) + + def split(self, X, y, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Note that providing ``y`` is sufficient to generate the splits and + hence ``np.zeros(n_samples)`` may be used as a placeholder for + ``X`` instead of actual training data. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + Stratification is done based on the y labels. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + """ + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) + return super().split(X, y, groups=groups) + + +class BaseShuffleSplit(_MetadataRequester, metaclass=ABCMeta): + """Base class for *ShuffleSplit. + + Parameters + ---------- + n_splits : int, default=10 + Number of re-shuffling & splitting iterations. + + test_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the proportion + of the dataset to include in the test split. If int, represents the + absolute number of test samples. If None, the value is set to the + complement of the train size. If ``train_size`` is also None, it will + be set to 0.1. + + train_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the + proportion of the dataset to include in the train split. If + int, represents the absolute number of train samples. If None, + the value is automatically set to the complement of the test size. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the training and testing indices produced. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + """ + + # This indicates that by default CV splitters don't have a "groups" kwarg, + # unless indicated by inheriting from ``GroupsConsumerMixin``. + # This also prevents ``set_split_request`` to be generated for splitters + # which don't support ``groups``. + __metadata_request__split = {"groups": metadata_routing.UNUSED} + + def __init__( + self, n_splits=10, *, test_size=None, train_size=None, random_state=None + ): + self.n_splits = n_splits + self.test_size = test_size + self.train_size = train_size + self.random_state = random_state + self._default_test_size = 0.1 + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,) + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,), default=None + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + """ + X, y, groups = indexable(X, y, groups) + for train, test in self._iter_indices(X, y, groups): + yield train, test + + def _iter_indices(self, X, y=None, groups=None): + """Generate (train, test) indices""" + n_samples = _num_samples(X) + n_train, n_test = _validate_shuffle_split( + n_samples, + self.test_size, + self.train_size, + default_test_size=self._default_test_size, + ) + + rng = check_random_state(self.random_state) + for i in range(self.n_splits): + # random partition + permutation = rng.permutation(n_samples) + ind_test = permutation[:n_test] + ind_train = permutation[n_test : (n_test + n_train)] + yield ind_train, ind_test + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + return self.n_splits + + def __repr__(self): + return _build_repr(self) + + +class ShuffleSplit(_UnsupportedGroupCVMixin, BaseShuffleSplit): + """Random permutation cross-validator. + + Yields indices to split data into training and test sets. + + Note: contrary to other cross-validation strategies, random splits + do not guarantee that test sets across all folds will be mutually exclusive, + and might include overlapping samples. However, this is still very likely for + sizeable datasets. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + Parameters + ---------- + n_splits : int, default=10 + Number of re-shuffling & splitting iterations. + + test_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the proportion + of the dataset to include in the test split. If int, represents the + absolute number of test samples. If None, the value is set to the + complement of the train size. If ``train_size`` is also None, it will + be set to 0.1. + + train_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the + proportion of the dataset to include in the train split. If + int, represents the absolute number of train samples. If None, + the value is automatically set to the complement of the test size. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the training and testing indices produced. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import ShuffleSplit + >>> X = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [3, 4], [5, 6]]) + >>> y = np.array([1, 2, 1, 2, 1, 2]) + >>> rs = ShuffleSplit(n_splits=5, test_size=.25, random_state=0) + >>> rs.get_n_splits(X) + 5 + >>> print(rs) + ShuffleSplit(n_splits=5, random_state=0, test_size=0.25, train_size=None) + >>> for i, (train_index, test_index) in enumerate(rs.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[1 3 0 4] + Test: index=[5 2] + Fold 1: + Train: index=[4 0 2 5] + Test: index=[1 3] + Fold 2: + Train: index=[1 2 4 0] + Test: index=[3 5] + Fold 3: + Train: index=[3 4 1 0] + Test: index=[5 2] + Fold 4: + Train: index=[3 5 1 0] + Test: index=[2 4] + >>> # Specify train and test size + >>> rs = ShuffleSplit(n_splits=5, train_size=0.5, test_size=.25, + ... random_state=0) + >>> for i, (train_index, test_index) in enumerate(rs.split(X)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[1 3 0] + Test: index=[5 2] + Fold 1: + Train: index=[4 0 2] + Test: index=[1 3] + Fold 2: + Train: index=[1 2 4] + Test: index=[3 5] + Fold 3: + Train: index=[3 4 1] + Test: index=[5 2] + Fold 4: + Train: index=[3 5 1] + Test: index=[2 4] + """ + + def __init__( + self, n_splits=10, *, test_size=None, train_size=None, random_state=None + ): + super().__init__( + n_splits=n_splits, + test_size=test_size, + train_size=train_size, + random_state=random_state, + ) + self._default_test_size = 0.1 + + +class GroupShuffleSplit(GroupsConsumerMixin, BaseShuffleSplit): + """Shuffle-Group(s)-Out cross-validation iterator. + + Provides randomized train/test indices to split data according to a + third-party provided group. This group information can be used to encode + arbitrary domain specific stratifications of the samples as integers. + + For instance the groups could be the year of collection of the samples + and thus allow for cross-validation against time-based splits. + + The difference between :class:`LeavePGroupsOut` and ``GroupShuffleSplit`` is that + the former generates splits using all subsets of size ``p`` unique groups, + whereas ``GroupShuffleSplit`` generates a user-determined number of random + test splits, each with a user-determined fraction of unique groups. + + For example, a less computationally intensive alternative to + ``LeavePGroupsOut(p=10)`` would be + ``GroupShuffleSplit(test_size=10, n_splits=100)``. + + Contrary to other cross-validation strategies, the random splits + do not guarantee that test sets across all folds will be mutually exclusive, + and might include overlapping samples. However, this is still very likely for + sizeable datasets. + + Note: The parameters ``test_size`` and ``train_size`` refer to groups, and + not to samples as in :class:`ShuffleSplit`. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + Parameters + ---------- + n_splits : int, default=5 + Number of re-shuffling & splitting iterations. + + test_size : float, int, default=None + If float, should be between 0.0 and 1.0 and represent the proportion + of groups to include in the test split (rounded up). If int, + represents the absolute number of test groups. If None, the value is + set to the complement of the train size. If ``train_size`` is also None, + it will be set to 0.2. + + train_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the + proportion of the groups to include in the train split. If + int, represents the absolute number of train groups. If None, + the value is automatically set to the complement of the test size. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the training and testing indices produced. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import GroupShuffleSplit + >>> X = np.ones(shape=(8, 2)) + >>> y = np.ones(shape=(8, 1)) + >>> groups = np.array([1, 1, 2, 2, 2, 3, 3, 3]) + >>> print(groups.shape) + (8,) + >>> gss = GroupShuffleSplit(n_splits=2, train_size=.7, random_state=42) + >>> gss.get_n_splits() + 2 + >>> print(gss) + GroupShuffleSplit(n_splits=2, random_state=42, test_size=None, train_size=0.7) + >>> for i, (train_index, test_index) in enumerate(gss.split(X, y, groups)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}, group={groups[train_index]}") + ... print(f" Test: index={test_index}, group={groups[test_index]}") + Fold 0: + Train: index=[2 3 4 5 6 7], group=[2 2 2 3 3 3] + Test: index=[0 1], group=[1 1] + Fold 1: + Train: index=[0 1 5 6 7], group=[1 1 3 3 3] + Test: index=[2 3 4], group=[2 2 2] + + See Also + -------- + ShuffleSplit : Shuffles samples to create independent test/train sets. + + LeavePGroupsOut : Train set leaves out all possible subsets of `p` groups. + """ + + def __init__( + self, n_splits=5, *, test_size=None, train_size=None, random_state=None + ): + super().__init__( + n_splits=n_splits, + test_size=test_size, + train_size=train_size, + random_state=random_state, + ) + self._default_test_size = 0.2 + + def _iter_indices(self, X, y, groups): + if groups is None: + raise ValueError("The 'groups' parameter should not be 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 + # invert them into data indices + + train = np.flatnonzero(np.isin(group_indices, group_train)) + test = np.flatnonzero(np.isin(group_indices, group_test)) + + yield train, test + + def split(self, X, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + y : array-like of shape (n_samples,), default=None + The target variable for supervised learning problems. + + groups : array-like of shape (n_samples,) + Group labels for the samples used while splitting the dataset into + train/test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + """ + return super().split(X, y, groups) + + +class StratifiedShuffleSplit(BaseShuffleSplit): + """Class-wise stratified ShuffleSplit cross-validator. + + Provides train/test indices to split data in train/test sets. + + This cross-validation object is a merge of :class:`StratifiedKFold` and + :class:`ShuffleSplit`, which returns stratified randomized folds. The folds + are made by preserving the percentage of samples for each class in `y` in a + binary or multiclass classification setting. + + Note: like the :class:`ShuffleSplit` strategy, stratified random splits + do not guarantee that test sets across all folds will be mutually exclusive, + and might include overlapping samples. However, this is still very likely for + sizeable datasets. + + Read more in the :ref:`User Guide `. + + For visualisation of cross-validation behaviour and + comparison between common scikit-learn split methods + refer to :ref:`sphx_glr_auto_examples_model_selection_plot_cv_indices.py` + + .. note:: + + Stratification on the class label solves an engineering problem rather + than a statistical one. See :ref:`stratification` for more details. + + Parameters + ---------- + n_splits : int, default=10 + Number of re-shuffling & splitting iterations. + + test_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the proportion + of the dataset to include in the test split. If int, represents the + absolute number of test samples. If None, the value is set to the + complement of the train size. If ``train_size`` is also None, it will + be set to 0.1. + + train_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the + proportion of the dataset to include in the train split. If + int, represents the absolute number of train samples. If None, + the value is automatically set to the complement of the test size. + + random_state : int, RandomState instance or None, default=None + Controls the randomness of the training and testing indices produced. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import StratifiedShuffleSplit + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 0, 1, 1, 1]) + >>> sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0) + >>> sss.get_n_splits(X, y) + 5 + >>> print(sss) + StratifiedShuffleSplit(n_splits=5, random_state=0, ...) + >>> for i, (train_index, test_index) in enumerate(sss.split(X, y)): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[5 2 3] + Test: index=[4 1 0] + Fold 1: + Train: index=[5 1 4] + Test: index=[0 2 3] + Fold 2: + Train: index=[5 0 2] + Test: index=[4 3 1] + Fold 3: + Train: index=[4 1 0] + Test: index=[2 3 5] + Fold 4: + Train: index=[0 5 1] + Test: index=[3 4 2] + """ + + def __init__( + self, n_splits=10, *, test_size=None, train_size=None, random_state=None + ): + super().__init__( + n_splits=n_splits, + test_size=test_size, + train_size=train_size, + random_state=random_state, + ) + self._default_test_size = 0.1 + + def _iter_indices(self, X, y, groups=None): + n_samples = _num_samples(X) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) + n_train, n_test = _validate_shuffle_split( + n_samples, + self.test_size, + self.train_size, + default_test_size=self._default_test_size, + ) + + # Convert to numpy as not all operations are supported by the Array API. + # `y` is probably never a very large array, which means that converting it + # should be cheap + xp, _ = get_namespace(y) + y = _convert_to_numpy(y, xp=xp) + + if y.ndim == 2: + # for multi-label y, map each distinct row to a string repr + # using join because str(row) uses an ellipsis if len(row) > 1000 + y = np.array([" ".join(row.astype("str")) for row in y]) + + classes, y_indices = np.unique(y, return_inverse=True) + n_classes = classes.shape[0] + + class_counts = np.bincount(y_indices) + if np.min(class_counts) < 2: + raise ValueError( + "The least populated class in y has only 1" + " member, which is too few. The minimum" + " number of groups for any class cannot" + " be less than 2." + ) + + if n_train < n_classes: + raise ValueError( + "The train_size = %d should be greater or " + "equal to the number of classes = %d" % (n_train, n_classes) + ) + if n_test < n_classes: + raise ValueError( + "The test_size = %d should be greater or " + "equal to the number of classes = %d" % (n_test, n_classes) + ) + + # Find the sorted list of instances for each class: + # (np.unique above performs a sort, so code is O(n logn) already) + class_indices = np.split( + np.argsort(y_indices, kind="mergesort"), np.cumsum(class_counts)[:-1] + ) + + rng = check_random_state(self.random_state) + + for _ in range(self.n_splits): + # if there are ties in the class-counts, we want + # to make sure to break them anew in each iteration + n_i = _approximate_mode(class_counts, n_train, rng) + class_counts_remaining = class_counts - n_i + t_i = _approximate_mode(class_counts_remaining, n_test, rng) + + train = [] + test = [] + + for i in range(n_classes): + permutation = rng.permutation(class_counts[i]) + perm_indices_class_i = class_indices[i].take(permutation, mode="clip") + + train.extend(perm_indices_class_i[: n_i[i]]) + test.extend(perm_indices_class_i[n_i[i] : n_i[i] + t_i[i]]) + + train = rng.permutation(train) + test = rng.permutation(test) + + yield train, test + + def split(self, X, y, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training data, where `n_samples` is the number of samples + and `n_features` is the number of features. + + Note that providing ``y`` is sufficient to generate the splits and + hence ``np.zeros(n_samples)`` may be used as a placeholder for + ``X`` instead of actual training data. + + y : array-like of shape (n_samples,) or (n_samples, n_labels) + The target variable for supervised learning problems. + Stratification is done based on the y labels. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + + Notes + ----- + Randomized CV splitters may return different results for each call of + split. You can make the results identical by setting `random_state` + to an integer. + """ + if groups is not None: + warnings.warn( + f"The groups parameter is ignored by {self.__class__.__name__}", + UserWarning, + ) + y = check_array(y, input_name="y", ensure_2d=False, dtype=None) + return super().split(X, y, groups) + + +def _validate_shuffle_split(n_samples, test_size, train_size, default_test_size=None): + """ + Validation helper to check if the train/test sizes are meaningful w.r.t. the + size of the data (n_samples). + """ + if test_size is None and train_size is None: + test_size = default_test_size + + test_size_type = np.asarray(test_size).dtype.kind + train_size_type = np.asarray(train_size).dtype.kind + + if (test_size_type == "i" and (test_size >= n_samples or test_size <= 0)) or ( + test_size_type == "f" and (test_size <= 0 or test_size >= 1) + ): + raise ValueError( + "test_size={0} should be either positive and smaller" + " than the number of samples {1} or a float in the " + "(0, 1) range".format(test_size, n_samples) + ) + + if (train_size_type == "i" and (train_size >= n_samples or train_size <= 0)) or ( + train_size_type == "f" and (train_size <= 0 or train_size >= 1) + ): + raise ValueError( + "train_size={0} should be either positive and smaller" + " than the number of samples {1} or a float in the " + "(0, 1) range".format(train_size, n_samples) + ) + + if train_size is not None and train_size_type not in ("i", "f"): + raise ValueError("Invalid value for train_size: {}".format(train_size)) + if test_size is not None and test_size_type not in ("i", "f"): + raise ValueError("Invalid value for test_size: {}".format(test_size)) + + if train_size_type == "f" and test_size_type == "f" and train_size + test_size > 1: + raise ValueError( + "The sum of test_size and train_size = {}, should be in the (0, 1)" + " range. Reduce test_size and/or train_size.".format(train_size + test_size) + ) + + if test_size_type == "f": + n_test = ceil(test_size * n_samples) + elif test_size_type == "i": + n_test = float(test_size) + + if train_size_type == "f": + n_train = floor(train_size * n_samples) + elif train_size_type == "i": + n_train = float(train_size) + + if train_size is None: + n_train = n_samples - n_test + elif test_size is None: + n_test = n_samples - n_train + + if n_train + n_test > n_samples: + raise ValueError( + "The sum of train_size and test_size = %d, " + "should be smaller than the number of " + "samples %d. Reduce test_size and/or " + "train_size." % (n_train + n_test, n_samples) + ) + + n_train, n_test = int(n_train), int(n_test) + + if n_train == 0: + raise ValueError( + "With n_samples={}, test_size={} and train_size={}, the " + "resulting train set will be empty. Adjust any of the " + "aforementioned parameters.".format(n_samples, test_size, train_size) + ) + + return n_train, n_test + + +class PredefinedSplit(BaseCrossValidator): + """Predefined split cross-validator. + + Provides train/test indices to split data into train/test sets using a + predefined scheme specified by the user with the ``test_fold`` parameter. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.16 + + Parameters + ---------- + test_fold : array-like of shape (n_samples,) + The entry ``test_fold[i]`` represents the index of the test set that + sample ``i`` belongs to. It is possible to exclude sample ``i`` from + any test set (i.e. include sample ``i`` in every training set) by + setting ``test_fold[i]`` equal to -1. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import PredefinedSplit + >>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]]) + >>> y = np.array([0, 0, 1, 1]) + >>> test_fold = [0, 1, -1, 1] + >>> ps = PredefinedSplit(test_fold) + >>> ps.get_n_splits() + 2 + >>> print(ps) + PredefinedSplit(test_fold=array([ 0, 1, -1, 1])) + >>> for i, (train_index, test_index) in enumerate(ps.split()): + ... print(f"Fold {i}:") + ... print(f" Train: index={train_index}") + ... print(f" Test: index={test_index}") + Fold 0: + Train: index=[1 2 3] + Test: index=[0] + Fold 1: + Train: index=[0 2] + Test: index=[1 3] + """ + + def __init__(self, test_fold): + self.test_fold = np.array(test_fold, dtype=int) + self.test_fold = column_or_1d(self.test_fold) + self.unique_folds = np.unique(self.test_fold) + self.unique_folds = self.unique_folds[self.unique_folds != -1] + + def split(self, X=None, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + if groups is not None: + warnings.warn( + f"The groups parameter is ignored by {self.__class__.__name__}", + UserWarning, + ) + return self._split() + + def _split(self): + """Generate indices to split data into training and test set. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + ind = np.arange(len(self.test_fold)) + for test_index in self._iter_test_masks(): + train_index = ind[np.logical_not(test_index)] + test_index = ind[test_index] + yield train_index, test_index + + def _iter_test_masks(self): + """Generates boolean masks corresponding to test sets.""" + for f in self.unique_folds: + test_index = np.where(self.test_fold == f)[0] + test_mask = np.zeros(len(self.test_fold), dtype=bool) + test_mask[test_index] = True + yield test_mask + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + return len(self.unique_folds) + + +class _CVIterableWrapper(BaseCrossValidator): + """Wrapper class for old style cv objects and iterables.""" + + def __init__(self, cv): + self.cv = list(cv) + + def get_n_splits(self, X=None, y=None, groups=None): + """Returns the number of splitting iterations in the cross-validator. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Returns + ------- + n_splits : int + Returns the number of splitting iterations in the cross-validator. + """ + return len(self.cv) + + def split(self, X=None, y=None, groups=None): + """Generate indices to split data into training and test set. + + Parameters + ---------- + X : object + Always ignored, exists for compatibility. + + y : object + Always ignored, exists for compatibility. + + groups : object + Always ignored, exists for compatibility. + + Yields + ------ + train : ndarray + The training set indices for that split. + + test : ndarray + The testing set indices for that split. + """ + for train, test in self.cv: + yield train, test + + +def check_cv(cv=5, y=None, *, classifier=False): + """Input checker utility for building a cross-validator. + + Parameters + ---------- + cv : int, cross-validation generator, iterable or None, default=5 + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + - None, to use the default 5-fold cross validation, + - integer, to specify the number of folds. + - :term:`CV splitter`, + - An iterable that generates (train, test) splits as arrays of indices. + + For integer/None inputs, if classifier is True and ``y`` is either + binary or multiclass, :class:`StratifiedKFold` is used. In all other + cases, :class:`KFold` is used. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value changed from 3-fold to 5-fold. + + y : array-like, default=None + The target variable for supervised learning problems. + + classifier : bool, default=False + Whether the task is a classification task, in which case + stratified KFold will be used. + + Returns + ------- + checked_cv : a cross-validator instance. + The return value is a cross-validator which generates the train/test + splits via the ``split`` method. + + Examples + -------- + >>> from sklearn.model_selection import check_cv + >>> check_cv(cv=5, y=None, classifier=False) + KFold(...) + >>> check_cv(cv=5, y=[1, 1, 0, 0, 0, 0], classifier=True) + StratifiedKFold(...) + """ + cv = 5 if cv is None else cv + if isinstance(cv, numbers.Integral): + if ( + classifier + and (y is not None) + and (type_of_target(y, input_name="y") in ("binary", "multiclass")) + ): + return StratifiedKFold(cv) + else: + return KFold(cv) + + if not hasattr(cv, "split") or isinstance(cv, str): + if not isinstance(cv, Iterable) or isinstance(cv, str): + raise ValueError( + "Expected cv as an integer, cross-validation " + "object (from sklearn.model_selection) " + "or an iterable. Got %s." % cv + ) + return _CVIterableWrapper(cv) + + return cv # New style cv objects are passed without any modification + + +@validate_params( + { + "test_size": [ + Interval(RealNotInt, 0, 1, closed="neither"), + Interval(numbers.Integral, 1, None, closed="left"), + None, + ], + "train_size": [ + Interval(RealNotInt, 0, 1, closed="neither"), + Interval(numbers.Integral, 1, None, closed="left"), + None, + ], + "random_state": ["random_state"], + "shuffle": ["boolean"], + "stratify": ["array-like", None], + }, + prefer_skip_nested_validation=True, +) +def train_test_split( + *arrays, + test_size=None, + train_size=None, + random_state=None, + shuffle=True, + stratify=None, +): + """Split arrays or matrices into random train and test subsets. + + Quick utility that wraps input validation, + ``next(ShuffleSplit().split(X, y))``, and application to input data + into a single call for splitting (and optionally subsampling) data into a + one-liner. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + *arrays : sequence of indexables with same length / shape[0] + Allowed inputs are lists, numpy arrays, scipy-sparse + matrices or pandas dataframes. + + test_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the proportion + of the dataset to include in the test split. If int, represents the + absolute number of test samples. If None, the value is set to the + complement of the train size. If ``train_size`` is also None, it will + be set to 0.25. + + train_size : float or int, default=None + If float, should be between 0.0 and 1.0 and represent the + proportion of the dataset to include in the train split. If + int, represents the absolute number of train samples. If None, + the value is automatically set to the complement of the test size. + + random_state : int, RandomState instance or None, default=None + Controls the shuffling applied to the data before applying the split. + Pass an int for reproducible output across multiple function calls. + See :term:`Glossary `. + + shuffle : bool, default=True + Whether or not to shuffle the data before splitting. If shuffle=False + then stratify must be None. + + stratify : array-like, default=None + If not None, data is split in a stratified fashion, using this as + the class labels. + Read more in the :ref:`User Guide `. + + Returns + ------- + splitting : list, length=2 * len(arrays) + List containing train-test split of inputs. + + .. versionadded:: 0.16 + If the input is sparse, the output will be a + ``scipy.sparse.csr_matrix``. Else, output type is the same as the + input type. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.model_selection import train_test_split + >>> X, y = np.arange(10).reshape((5, 2)), range(5) + >>> X + array([[0, 1], + [2, 3], + [4, 5], + [6, 7], + [8, 9]]) + >>> list(y) + [0, 1, 2, 3, 4] + + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.33, random_state=42) + ... + >>> X_train + array([[4, 5], + [0, 1], + [6, 7]]) + >>> y_train + [2, 0, 3] + >>> X_test + array([[2, 3], + [8, 9]]) + >>> y_test + [1, 4] + + >>> train_test_split(y, shuffle=False) + [[0, 1, 2], [3, 4]] + + >>> from sklearn import datasets + >>> iris = datasets.load_iris(as_frame=True) + >>> X, y = iris['data'], iris['target'] + >>> X.head() + sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) + 0 5.1 3.5 1.4 0.2 + 1 4.9 3.0 1.4 0.2 + 2 4.7 3.2 1.3 0.2 + 3 4.6 3.1 1.5 0.2 + 4 5.0 3.6 1.4 0.2 + >>> y.head() + 0 0 + 1 0 + 2 0 + 3 0 + 4 0 + ... + + >>> X_train, X_test, y_train, y_test = train_test_split( + ... X, y, test_size=0.33, random_state=42) + ... + >>> X_train.head() + sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) + 96 5.7 2.9 4.2 1.3 + 105 7.6 3.0 6.6 2.1 + 66 5.6 3.0 4.5 1.5 + 0 5.1 3.5 1.4 0.2 + 122 7.7 2.8 6.7 2.0 + >>> y_train.head() + 96 1 + 105 2 + 66 1 + 0 0 + 122 2 + ... + >>> X_test.head() + sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) + 73 6.1 2.8 4.7 1.2 + 18 5.7 3.8 1.7 0.3 + 118 7.7 2.6 6.9 2.3 + 78 6.0 2.9 4.5 1.5 + 76 6.8 2.8 4.8 1.4 + >>> y_test.head() + 73 1 + 18 0 + 118 2 + 78 1 + 76 1 + ... + """ + n_arrays = len(arrays) + if n_arrays == 0: + raise ValueError("At least one array required as input") + + arrays = indexable(*arrays) + + n_samples = _num_samples(arrays[0]) + n_train, n_test = _validate_shuffle_split( + n_samples, test_size, train_size, default_test_size=0.25 + ) + + if shuffle is False: + if stratify is not None: + raise ValueError( + "Stratified train/test split is not implemented for shuffle=False" + ) + + train = np.arange(n_train) + test = np.arange(n_train, n_train + n_test) + + else: + if stratify is not None: + CVClass = StratifiedShuffleSplit + else: + CVClass = ShuffleSplit + + cv = CVClass(test_size=n_test, train_size=n_train, random_state=random_state) + + train, test = next(cv.split(X=arrays[0], y=stratify)) + + train, test = ensure_common_namespace_device(arrays[0], train, test) + + return list( + chain.from_iterable( + (_safe_indexing(a, train), _safe_indexing(a, test)) for a in arrays + ) + ) + + +# Tell nose that train_test_split is not a test. +# (Needed for external libraries that may use nose.) +# Use setattr to avoid mypy errors when monkeypatching. +setattr(train_test_split, "__test__", False) + + +def _pprint(params, offset=0, printer=repr): + """Pretty print the dictionary 'params' + + Parameters + ---------- + params : dict + The dictionary to pretty print + + offset : int, default=0 + The offset in characters to add at the begin of each line. + + printer : callable, default=repr + The function to convert entries to strings, typically + the builtin str or repr + + """ + # Do a multi-line justified repr: + options = np.get_printoptions() + np.set_printoptions(precision=5, threshold=64, edgeitems=2) + params_list = list() + this_line_length = offset + line_sep = ",\n" + (1 + offset // 2) * " " + for i, (k, v) in enumerate(sorted(params.items())): + if isinstance(v, float): + # use str for representing floating point numbers + # this way we get consistent representation across + # architectures and versions. + this_repr = "%s=%s" % (k, str(v)) + else: + # use repr of the rest + this_repr = "%s=%s" % (k, printer(v)) + if len(this_repr) > 500: + this_repr = this_repr[:300] + "..." + this_repr[-100:] + if i > 0: + if this_line_length + len(this_repr) >= 75 or "\n" in this_repr: + params_list.append(line_sep) + this_line_length = len(line_sep) + else: + params_list.append(", ") + this_line_length += 2 + params_list.append(this_repr) + this_line_length += len(this_repr) + + np.set_printoptions(**options) + lines = "".join(params_list) + # Strip trailing space to avoid nightmare in doctests + lines = "\n".join(l.rstrip(" ") for l in lines.split("\n")) + return lines + + +def _build_repr(self): + # XXX This is copied from BaseEstimator's get_params + cls = self.__class__ + init = getattr(cls.__init__, "deprecated_original", cls.__init__) + # Ignore varargs, kw and default values and pop self + init_signature = signature(init) + # Consider the constructor parameters excluding 'self' + if init is object.__init__: + args = [] + else: + args = sorted( + [ + p.name + for p in init_signature.parameters.values() + if p.name != "self" and p.kind != p.VAR_KEYWORD + ] + ) + class_name = self.__class__.__name__ + params = dict() + for key in args: + # We need deprecation warnings to always be on in order to + # catch deprecated param values. + # This is set in utils/__init__.py but it gets overwritten + # when running under python3 somehow. + warnings.simplefilter("always", FutureWarning) + try: + with warnings.catch_warnings(record=True) as w: + value = getattr(self, key, None) + if value is None and hasattr(self, "cvargs"): + value = self.cvargs.get(key, None) + if len(w) and w[0].category is FutureWarning: + # if the parameter is deprecated, don't show it + continue + finally: + warnings.filters.pop(0) + 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/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_validation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a1406e6c2a50e70e366be0fd199795eeb60417 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/_validation.py @@ -0,0 +1,2530 @@ +""" +The :mod:`sklearn.model_selection._validation` module includes classes and +functions to validate the model. +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import numbers +import time +import warnings +from collections import Counter +from contextlib import suppress +from functools import partial +from numbers import Real +from traceback import format_exc + +import numpy as np +import scipy.sparse as sp +from joblib import logger + +from ..base import clone, is_classifier +from ..exceptions import FitFailedWarning, UnsetMetadataPassedError +from ..metrics import check_scoring, get_scorer_names +from ..metrics._scorer import _MultimetricScorer +from ..preprocessing import LabelEncoder +from ..utils import Bunch, _safe_indexing, check_random_state, indexable +from ..utils._array_api import device, get_namespace +from ..utils._param_validation import ( + HasMethods, + Integral, + Interval, + StrOptions, + validate_params, +) +from ..utils.metadata_routing import ( + MetadataRouter, + MethodMapping, + _routing_enabled, + process_routing, +) +from ..utils.metaestimators import _safe_split +from ..utils.parallel import Parallel, delayed +from ..utils.validation import _check_method_params, _num_samples +from ._split import check_cv + +__all__ = [ + "cross_val_predict", + "cross_val_score", + "cross_validate", + "learning_curve", + "permutation_test_score", + "validation_curve", +] + + +def _check_params_groups_deprecation(fit_params, params, groups, version): + """A helper function to check deprecations on `groups` and `fit_params`. + + # TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not + # possible. + """ + if params is not None and fit_params is not None: + raise ValueError( + "`params` and `fit_params` cannot both be provided. Pass parameters " + "via `params`. `fit_params` is deprecated and will be removed in " + f"version {version}." + ) + elif fit_params is not None: + warnings.warn( + ( + "`fit_params` is deprecated and will be removed in version {version}. " + "Pass parameters via `params` instead." + ), + FutureWarning, + ) + params = fit_params + + params = {} if params is None else params + + _check_groups_routing_disabled(groups) + + return params + + +# TODO(SLEP6): To be removed when set_config(enable_metadata_routing=False) is not +# possible. +def _check_groups_routing_disabled(groups): + if groups is not None and _routing_enabled(): + raise ValueError( + "`groups` can only be passed if metadata routing is not enabled via" + " `sklearn.set_config(enable_metadata_routing=True)`. When routing is" + " enabled, pass `groups` alongside other metadata via the `params` argument" + " instead." + ) + + +@validate_params( + { + "estimator": [HasMethods("fit")], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", None], + "groups": ["array-like", None], + "scoring": [ + StrOptions(set(get_scorer_names())), + callable, + list, + tuple, + dict, + None, + ], + "cv": ["cv_object"], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + "params": [dict, None], + "pre_dispatch": [Integral, str], + "return_train_score": ["boolean"], + "return_estimator": ["boolean"], + "return_indices": ["boolean"], + "error_score": [StrOptions({"raise"}), Real], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +def cross_validate( + estimator, + X, + y=None, + *, + groups=None, + scoring=None, + cv=None, + n_jobs=None, + verbose=0, + params=None, + pre_dispatch="2*n_jobs", + return_train_score=False, + return_estimator=False, + return_indices=False, + error_score=np.nan, +): + """Evaluate metric(s) by cross-validation and also record fit/score times. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to fit. Can be for example a list, or an array. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs), default=None + The target variable to try to predict in the case of + supervised 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:`GroupKFold`). + + .. versionchanged:: 1.4 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``cross_validate(..., params={'groups': groups})``. + + scoring : str, callable, list, tuple, or dict, default=None + Strategy to evaluate the performance of the `estimator` across cross-validation + splits. + + If `scoring` represents a single score, one can use: + + - a single string (see :ref:`scoring_string_names`); + - a callable (see :ref:`scoring_callable`) that returns a single value. + - `None`, the `estimator`'s + :ref:`default evaluation criterion ` is used. + + If `scoring` represents multiple scores, one can use: + + - a list or tuple of unique strings; + - a callable returning a dictionary where the keys are the metric + names and the values are the metric scores; + - a dictionary with metric names as keys and callables a values. + + See :ref:`multimetric_grid_search` for an example. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and computing + the score are parallelized over the cross-validation splits. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : int, default=0 + The verbosity level. + + params : dict, default=None + Parameters to pass to the underlying estimator's ``fit``, the scorer, + and the CV splitter. + + .. versionadded:: 1.4 + + pre_dispatch : int or str, default='2*n_jobs' + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - An int, giving the exact number of total jobs that are spawned + - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' + + return_train_score : bool, default=False + Whether to include train 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. + + .. versionadded:: 0.19 + + .. versionchanged:: 0.21 + Default value was changed from ``True`` to ``False`` + + return_estimator : bool, default=False + Whether to return the estimators fitted on each split. + + .. versionadded:: 0.20 + + return_indices : bool, default=False + Whether to return the train-test indices selected for each split. + + .. versionadded:: 1.3 + + 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. + If a numeric value is given, FitFailedWarning is raised. + + .. versionadded:: 0.20 + + Returns + ------- + scores : dict of float arrays of shape (n_splits,) + Array of scores of the estimator for each run of the cross validation. + + A dict of arrays containing the score/time arrays for each scorer is + returned. The possible keys for this ``dict`` are: + + ``test_score`` + The score array for test scores on each cv split. + Suffix ``_score`` in ``test_score`` changes to a specific + metric like ``test_r2`` or ``test_auc`` if there are + multiple scoring metrics in the scoring parameter. + ``train_score`` + The score array for train scores on each cv split. + Suffix ``_score`` in ``train_score`` changes to a specific + metric like ``train_r2`` or ``train_auc`` if there are + multiple scoring metrics in the scoring parameter. + This is available only if ``return_train_score`` parameter + is ``True``. + ``fit_time`` + The time for fitting the estimator on the train + set for each cv split. + ``score_time`` + The time for scoring the estimator on the test set for each + cv split. (Note: time for scoring on the train set is not + included even if ``return_train_score`` is set to ``True``). + ``estimator`` + The estimator objects for each cv split. + This is available only if ``return_estimator`` parameter + is set to ``True``. + ``indices`` + The train/test positional indices for each cv split. A dictionary + is returned where the keys are either `"train"` or `"test"` + and the associated values are a list of integer-dtyped NumPy + arrays with the indices. Available only if `return_indices=True`. + + See Also + -------- + cross_val_score : Run cross-validation for single metric evaluation. + + cross_val_predict : Get predictions from each split of cross-validation for + diagnostic purposes. + + sklearn.metrics.make_scorer : Make a scorer from a performance metric or + loss function. + + Examples + -------- + >>> from sklearn import datasets, linear_model + >>> from sklearn.model_selection import cross_validate + >>> from sklearn.metrics import make_scorer + >>> from sklearn.metrics import confusion_matrix + >>> from sklearn.svm import LinearSVC + >>> diabetes = datasets.load_diabetes() + >>> X = diabetes.data[:150] + >>> y = diabetes.target[:150] + >>> lasso = linear_model.Lasso() + + Single metric evaluation using ``cross_validate`` + + >>> cv_results = cross_validate(lasso, X, y, cv=3) + >>> sorted(cv_results.keys()) + ['fit_time', 'score_time', 'test_score'] + >>> cv_results['test_score'] + array([0.3315057 , 0.08022103, 0.03531816]) + + Multiple metric evaluation using ``cross_validate`` + (please refer the ``scoring`` parameter doc for more information) + + >>> scores = cross_validate(lasso, X, y, cv=3, + ... scoring=('r2', 'neg_mean_squared_error'), + ... return_train_score=True) + >>> print(scores['test_neg_mean_squared_error']) + [-3635.5 -3573.3 -6114.7] + >>> print(scores['train_r2']) + [0.28009951 0.3908844 0.22784907] + """ + _check_groups_routing_disabled(groups) + + X, y = indexable(X, y) + params = {} if params is None else params + cv = check_cv(cv, y, classifier=is_classifier(estimator)) + + scorers = check_scoring( + estimator, scoring=scoring, raise_exc=(error_score == "raise") + ) + + if _routing_enabled(): + # For estimators, a MetadataRouter is created in get_metadata_routing + # methods. For these router methods, we create the router to use + # `process_routing` on it. + router = ( + MetadataRouter(owner="cross_validate") + .add( + splitter=cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + estimator=estimator, + # TODO(SLEP6): also pass metadata to the predict method for + # scoring? + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + .add( + scorer=scorers, + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + ) + try: + routed_params = process_routing(router, "fit", **params) + except UnsetMetadataPassedError as e: + # The default exception would mention `fit` since in the above + # `process_routing` code, we pass `fit` as the caller. However, + # the user is not calling `fit` directly, so we change the message + # to make it more suitable for this case. + raise UnsetMetadataPassedError( + message=str(e).replace("cross_validate.fit", "cross_validate"), + unrequested_params=e.unrequested_params, + routed_params=e.routed_params, + ) + else: + routed_params = Bunch() + routed_params.splitter = Bunch(split={"groups": groups}) + routed_params.estimator = Bunch(fit=params) + routed_params.scorer = Bunch(score={}) + + indices = cv.split(X, y, **routed_params.splitter.split) + if return_indices: + # materialize the indices since we need to store them in the returned dict + indices = list(indices) + + # We clone the estimator to make sure that all the folds are + # independent, and that it is pickle-able. + parallel = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch) + results = parallel( + delayed(_fit_and_score)( + clone(estimator), + X, + y, + scorer=scorers, + train=train, + test=test, + verbose=verbose, + parameters=None, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + return_train_score=return_train_score, + return_times=True, + return_estimator=return_estimator, + error_score=error_score, + ) + for train, test in indices + ) + + _warn_or_raise_about_fit_failures(results, error_score) + + # For callable 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. + if callable(scoring): + _insert_error_scores(results, error_score) + + results = _aggregate_score_dicts(results) + + ret = {} + ret["fit_time"] = results["fit_time"] + ret["score_time"] = results["score_time"] + + if return_estimator: + ret["estimator"] = results["estimator"] + + if return_indices: + ret["indices"] = {} + ret["indices"]["train"], ret["indices"]["test"] = zip(*indices) + + test_scores_dict = _normalize_score_results(results["test_scores"]) + if return_train_score: + train_scores_dict = _normalize_score_results(results["train_scores"]) + + for name in test_scores_dict: + ret["test_%s" % name] = test_scores_dict[name] + if return_train_score: + key = "train_%s" % name + ret[key] = train_scores_dict[name] + + return ret + + +def _insert_error_scores(results, error_score): + """Insert error in `results` by replacing them inplace with `error_score`. + + This only applies to multimetric scores because `_fit_and_score` will + handle the single metric case. + """ + successful_score = None + failed_indices = [] + for i, result in enumerate(results): + if result["fit_error"] is not None: + failed_indices.append(i) + elif successful_score is None: + successful_score = result["test_scores"] + + if isinstance(successful_score, dict): + formatted_error = {name: error_score for name in successful_score} + for i in failed_indices: + results[i]["test_scores"] = formatted_error.copy() + if "train_scores" in results[i]: + results[i]["train_scores"] = formatted_error.copy() + + +def _normalize_score_results(scores, scaler_score_key="score"): + """Creates a scoring dictionary based on the type of `scores`""" + if isinstance(scores[0], dict): + # multimetric scoring + return _aggregate_score_dicts(scores) + # scaler + return {scaler_score_key: scores} + + +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 + ] + 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() + ) + + if num_failed_fits == num_fits: + all_fits_failed_message = ( + f"\nAll the {num_fits} fits failed.\n" + "It 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) + + +@validate_params( + { + "estimator": [HasMethods("fit")], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", None], + "groups": ["array-like", None], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "cv": ["cv_object"], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + "params": [dict, None], + "pre_dispatch": [Integral, str, None], + "error_score": [StrOptions({"raise"}), Real], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +def cross_val_score( + estimator, + X, + y=None, + *, + groups=None, + scoring=None, + cv=None, + n_jobs=None, + verbose=0, + params=None, + pre_dispatch="2*n_jobs", + error_score=np.nan, +): + """Evaluate a score by cross-validation. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to fit. Can be for example a list, or an array. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs), \ + default=None + The target variable to try to predict in the case of + supervised 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:`GroupKFold`). + + .. versionchanged:: 1.4 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``cross_val_score(..., params={'groups': groups})``. + + scoring : str or callable, default=None + Strategy to evaluate the performance of the `estimator` across cross-validation + splits. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``, which should return only a single value. + See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + Similar to the use of `scoring` in :func:`cross_validate` but only a + single metric is permitted. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - `None`, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable that generates (train, test) splits as arrays of indices. + + For `int`/`None` inputs, if the estimator is a classifier and `y` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + `cv` default value if `None` changed from 3-fold to 5-fold. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and computing + the score are parallelized over the cross-validation splits. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : int, default=0 + The verbosity level. + + params : dict, default=None + Parameters to pass to the underlying estimator's ``fit``, the scorer, + and the CV splitter. + + .. versionadded:: 1.4 + + pre_dispatch : int or str, default='2*n_jobs' + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - ``None``, in which case all the jobs are immediately created and spawned. Use + this for lightweight and fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + - An int, giving the exact number of total jobs that are spawned + - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' + + 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. + If a numeric value is given, FitFailedWarning is raised. + + .. versionadded:: 0.20 + + Returns + ------- + scores : ndarray of float of shape=(len(list(cv)),) + Array of scores of the estimator for each run of the cross validation. + + See Also + -------- + cross_validate : To run cross-validation on multiple metrics and also to + return train scores, fit times and score times. + + cross_val_predict : Get predictions from each split of cross-validation for + diagnostic purposes. + + sklearn.metrics.make_scorer : Make a scorer from a performance metric or + loss function. + + Examples + -------- + >>> from sklearn import datasets, linear_model + >>> from sklearn.model_selection import cross_val_score + >>> diabetes = datasets.load_diabetes() + >>> X = diabetes.data[:150] + >>> y = diabetes.target[:150] + >>> lasso = linear_model.Lasso() + >>> print(cross_val_score(lasso, X, y, cv=3)) + [0.3315057 0.08022103 0.03531816] + """ + # To ensure multimetric format is not supported + scorer = check_scoring(estimator, scoring=scoring) + + cv_results = cross_validate( + estimator=estimator, + X=X, + y=y, + groups=groups, + scoring={"score": scorer}, + cv=cv, + n_jobs=n_jobs, + verbose=verbose, + params=params, + pre_dispatch=pre_dispatch, + error_score=error_score, + ) + return cv_results["test_score"] + + +def _fit_and_score( + estimator, + X, + y, + *, + scorer, + train, + test, + verbose, + parameters, + fit_params, + score_params, + return_train_score=False, + return_parameters=False, + return_n_test_samples=False, + return_times=False, + return_estimator=False, + split_progress=None, + candidate_progress=None, + error_score=np.nan, +): + """Fit estimator and compute scores for a given dataset split. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + X : array-like of shape (n_samples, n_features) + The data to fit. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + The target variable to try to predict in the case of + supervised learning. + + scorer : A single callable or dict mapping scorer name to the callable + If it is a single callable, the return value for ``train_scores`` and + ``test_scores`` is a single float. + + For a dict, it should be one mapping the scorer name to the scorer + callable object / function. + + The callable object / fn should have signature + ``scorer(estimator, X, y)``. + + train : array-like of shape (n_train_samples,) + Indices of training samples. + + test : array-like of shape (n_test_samples,) + Indices of test samples. + + verbose : int + The verbosity level. + + 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. + If a numeric value is given, FitFailedWarning is raised. + + parameters : dict or None + Parameters to be set on the estimator. + + fit_params : dict or None + Parameters that will be passed to ``estimator.fit``. + + score_params : dict or None + Parameters that will be passed to the scorer. + + return_train_score : bool, default=False + Compute and return score on training set. + + return_parameters : bool, default=False + Return parameters that has been used for the estimator. + + split_progress : {list, tuple} of int, default=None + A list or tuple of format (, ). + + candidate_progress : {list, tuple} of int, default=None + A list or tuple of format + (, ). + + return_n_test_samples : bool, default=False + Whether to return the ``n_test_samples``. + + return_times : bool, default=False + Whether to return the fit/score times. + + return_estimator : bool, default=False + Whether to return the fitted estimator. + + Returns + ------- + result : dict with the following attributes + train_scores : dict of scorer name -> float + Score on training set (for all the scorers), + returned only if `return_train_score` is `True`. + test_scores : dict of scorer name -> float + Score on testing set (for all the scorers). + n_test_samples : int + Number of test samples. + fit_time : float + Time spent for fitting in seconds. + score_time : float + Time spent for scoring in seconds. + parameters : dict or None + The parameters that have been evaluated. + estimator : estimator object + The fitted estimator. + fit_error : str or None + Traceback str if the fit failed, None if the fit succeeded. + """ + xp, _ = get_namespace(X) + X_device = device(X) + + # Make sure that we can fancy index X even if train and test are provided + # as NumPy arrays by NumPy only cross-validation splitters. + train, test = xp.asarray(train, device=X_device), xp.asarray(test, device=X_device) + + 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: + progress_msg = f" {split_progress[0] + 1}/{split_progress[1]}" + if candidate_progress and verbose > 9: + progress_msg += f"; {candidate_progress[0] + 1}/{candidate_progress[1]}" + + if verbose > 1: + if parameters is None: + params_msg = "" + else: + sorted_keys = sorted(parameters) # Ensure deterministic o/p + params_msg = ", ".join(f"{k}={parameters[k]}" for k in sorted_keys) + if verbose > 9: + start_msg = f"[CV{progress_msg}] START {params_msg}" + print(f"{start_msg}{(80 - len(start_msg)) * '.'}") + + # Adjust length of sample weights + fit_params = fit_params if fit_params is not None else {} + fit_params = _check_method_params(X, params=fit_params, indices=train) + score_params = score_params if score_params is not None else {} + score_params_train = _check_method_params(X, params=score_params, indices=train) + score_params_test = _check_method_params(X, params=score_params, indices=test) + + if parameters is not None: + # here we clone the parameters, since sometimes the parameters + # themselves might be estimators, e.g. when we search over different + # estimators in a pipeline. + # ref: https://github.com/scikit-learn/scikit-learn/pull/26786 + estimator = estimator.set_params(**clone(parameters, safe=False)) + + start_time = time.time() + + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, y_test = _safe_split(estimator, X, y, test, train) + + result = {} + try: + if y_train is None: + estimator.fit(X_train, **fit_params) + else: + estimator.fit(X_train, y_train, **fit_params) + + except Exception: + # Note fit time as time until error + fit_time = time.time() - start_time + score_time = 0.0 + if error_score == "raise": + raise + elif isinstance(error_score, numbers.Number): + if isinstance(scorer, _MultimetricScorer): + test_scores = {name: error_score for name in scorer._scorers} + if return_train_score: + train_scores = test_scores.copy() + else: + test_scores = error_score + if return_train_score: + train_scores = error_score + result["fit_error"] = format_exc() + else: + result["fit_error"] = None + + fit_time = time.time() - start_time + test_scores = _score( + estimator, X_test, y_test, scorer, score_params_test, error_score + ) + score_time = time.time() - start_time - fit_time + if return_train_score: + train_scores = _score( + estimator, X_train, y_train, scorer, score_params_train, error_score + ) + + if verbose > 1: + total_time = score_time + fit_time + end_msg = f"[CV{progress_msg}] END " + result_msg = params_msg + (";" if params_msg else "") + if verbose > 2: + if isinstance(test_scores, dict): + for scorer_name in sorted(test_scores): + result_msg += f" {scorer_name}: (" + if return_train_score: + scorer_scores = train_scores[scorer_name] + result_msg += f"train={scorer_scores:.3f}, " + result_msg += f"test={test_scores[scorer_name]:.3f})" + else: + result_msg += ", score=" + if return_train_score: + result_msg += f"(train={train_scores:.3f}, test={test_scores:.3f})" + else: + result_msg += f"{test_scores:.3f}" + result_msg += f" total time={logger.short_format_time(total_time)}" + + # Right align the result_msg + end_msg += "." * (80 - len(end_msg) - len(result_msg)) + end_msg += result_msg + print(end_msg) + + result["test_scores"] = test_scores + if return_train_score: + result["train_scores"] = train_scores + if return_n_test_samples: + result["n_test_samples"] = _num_samples(X_test) + if return_times: + result["fit_time"] = fit_time + result["score_time"] = score_time + if return_parameters: + result["parameters"] = parameters + if return_estimator: + result["estimator"] = estimator + return result + + +def _score(estimator, X_test, y_test, scorer, score_params, 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 _MultiMetricScorer, otherwise a single + float is returned. + """ + score_params = {} if score_params is None else score_params + + try: + if y_test is None: + scores = scorer(estimator, X_test, **score_params) + else: + scores = scorer(estimator, X_test, y_test, **score_params) + except Exception: + if isinstance(scorer, _MultimetricScorer): + # If `_MultimetricScorer` raises exception, the `error_score` + # parameter is equal to "raise". + raise + else: + if error_score == "raise": + raise + else: + scores = error_score + warnings.warn( + ( + "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, + ) + + # Check non-raised error messages in `_MultimetricScorer` + if isinstance(scorer, _MultimetricScorer): + exception_messages = [ + (name, str_e) for name, str_e in scores.items() if isinstance(str_e, str) + ] + if exception_messages: + # error_score != "raise" + for name, str_e in exception_messages: + scores[name] = error_score + warnings.warn( + ( + "Scoring failed. The score on this train-test partition for " + f"these parameters will be set to {error_score}. Details: \n" + f"{str_e}" + ), + 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"): + with suppress(ValueError): + # e.g. unwrap memmapped scalars + score = score.item() + if not isinstance(score, numbers.Number): + raise ValueError(error_msg % (score, type(score), name)) + scores[name] = score + else: # scalar + if hasattr(scores, "item"): + with suppress(ValueError): + # e.g. unwrap memmapped scalars + scores = scores.item() + if not isinstance(scores, numbers.Number): + raise ValueError(error_msg % (scores, type(scores), scorer)) + return scores + + +@validate_params( + { + "estimator": [HasMethods(["fit", "predict"])], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", "sparse matrix", None], + "groups": ["array-like", None], + "cv": ["cv_object"], + "n_jobs": [Integral, None], + "verbose": ["verbose"], + "params": [dict, None], + "pre_dispatch": [Integral, str, None], + "method": [ + StrOptions( + { + "predict", + "predict_proba", + "predict_log_proba", + "decision_function", + } + ) + ], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +def cross_val_predict( + estimator, + X, + y=None, + *, + groups=None, + cv=None, + n_jobs=None, + verbose=0, + params=None, + pre_dispatch="2*n_jobs", + method="predict", +): + """Generate cross-validated estimates for each input data point. + + The data is split according to the cv parameter. Each sample belongs + to exactly one test set, and its prediction is computed with an + estimator fitted on the corresponding training set. + + Passing these predictions into an evaluation metric may not be a valid + way to measure generalization performance. Results can differ from + :func:`cross_validate` and :func:`cross_val_score` unless all tests sets + have equal size and the metric decomposes over samples. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator + The estimator instance to use to fit the data. It must implement a `fit` + method and the method given by the `method` parameter. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The data to fit. Can be, for example a list, or an array at least 2d. + + y : {array-like, sparse matrix} of shape (n_samples,) or (n_samples, n_outputs), \ + default=None + The target variable to try to predict in the case of + supervised 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:`GroupKFold`). + + .. versionchanged:: 1.4 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``cross_val_predict(..., params={'groups': groups})``. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable that generates (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and + predicting are parallelized over the cross-validation splits. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + verbose : int, default=0 + The verbosity level. + + params : dict, default=None + Parameters to pass to the underlying estimator's ``fit`` and the CV + splitter. + + .. versionadded:: 1.4 + + pre_dispatch : int or str, default='2*n_jobs' + Controls the number of jobs that get dispatched during parallel + execution. Reducing this number can be useful to avoid an + explosion of memory consumption when more jobs get dispatched + than CPUs can process. This parameter can be: + + - None, in which case all the jobs are immediately created and spawned. Use + this for lightweight and fast-running jobs, to avoid delays due to on-demand + spawning of the jobs + - An int, giving the exact number of total jobs that are spawned + - A str, giving an expression as a function of n_jobs, as in '2*n_jobs' + + method : {'predict', 'predict_proba', 'predict_log_proba', \ + 'decision_function'}, default='predict' + The method to be invoked by `estimator`. + + Returns + ------- + predictions : ndarray + This is the result of calling `method`. Shape: + + - When `method` is 'predict' and in special case where `method` is + 'decision_function' and the target is binary: (n_samples,) + - When `method` is one of {'predict_proba', 'predict_log_proba', + 'decision_function'} (unless special case above): + (n_samples, n_classes) + - If `estimator` is :term:`multioutput`, an extra dimension + 'n_outputs' is added to the end of each shape above. + + See Also + -------- + cross_val_score : Calculate score for each CV split. + cross_validate : Calculate one or more scores and timings for each CV + split. + + Notes + ----- + In the case that one or more classes are absent in a training portion, a + default score needs to be assigned to all instances for that class if + ``method`` produces columns per class, as in {'decision_function', + 'predict_proba', 'predict_log_proba'}. For ``predict_proba`` this value is + 0. In order to ensure finite output, we approximate negative infinity by + the minimum finite float value for the dtype in other cases. + + Examples + -------- + >>> from sklearn import datasets, linear_model + >>> from sklearn.model_selection import cross_val_predict + >>> diabetes = datasets.load_diabetes() + >>> X = diabetes.data[:150] + >>> y = diabetes.target[:150] + >>> lasso = linear_model.Lasso() + >>> y_pred = cross_val_predict(lasso, X, y, cv=3) + + For a detailed example of using ``cross_val_predict`` to visualize + prediction errors, please see + :ref:`sphx_glr_auto_examples_model_selection_plot_cv_predict.py`. + """ + _check_groups_routing_disabled(groups) + X, y = indexable(X, y) + params = {} if params is None else params + + if _routing_enabled(): + # For estimators, a MetadataRouter is created in get_metadata_routing + # methods. For these router methods, we create the router to use + # `process_routing` on it. + router = ( + MetadataRouter(owner="cross_val_predict") + .add( + splitter=cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + estimator=estimator, + # TODO(SLEP6): also pass metadata for the predict method. + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + ) + try: + routed_params = process_routing(router, "fit", **params) + except UnsetMetadataPassedError as e: + # The default exception would mention `fit` since in the above + # `process_routing` code, we pass `fit` as the caller. However, + # the user is not calling `fit` directly, so we change the message + # to make it more suitable for this case. + raise UnsetMetadataPassedError( + message=str(e).replace("cross_val_predict.fit", "cross_val_predict"), + unrequested_params=e.unrequested_params, + routed_params=e.routed_params, + ) + else: + routed_params = Bunch() + routed_params.splitter = Bunch(split={"groups": groups}) + routed_params.estimator = Bunch(fit=params) + + cv = check_cv(cv, y, classifier=is_classifier(estimator)) + splits = list(cv.split(X, y, **routed_params.splitter.split)) + + test_indices = np.concatenate([test for _, test in splits]) + if not _check_is_permutation(test_indices, _num_samples(X)): + raise ValueError("cross_val_predict only works for partitions") + + # If classification methods produce multiple columns of output, + # we need to manually encode classes to ensure consistent column ordering. + encode = ( + method in ["decision_function", "predict_proba", "predict_log_proba"] + and y is not None + ) + if encode: + y = np.asarray(y) + if y.ndim == 1: + le = LabelEncoder() + y = le.fit_transform(y) + elif y.ndim == 2: + y_enc = np.zeros_like(y, dtype=int) + for i_label in range(y.shape[1]): + y_enc[:, i_label] = LabelEncoder().fit_transform(y[:, i_label]) + y = y_enc + + # We clone the estimator to make sure that all the folds are + # independent, and that it is pickle-able. + parallel = Parallel(n_jobs=n_jobs, verbose=verbose, pre_dispatch=pre_dispatch) + predictions = parallel( + delayed(_fit_and_predict)( + clone(estimator), + X, + y, + train, + test, + routed_params.estimator.fit, + method, + ) + for train, test in splits + ) + + inv_test_indices = np.empty(len(test_indices), dtype=int) + inv_test_indices[test_indices] = np.arange(len(test_indices)) + + if sp.issparse(predictions[0]): + predictions = sp.vstack(predictions, format=predictions[0].format) + elif encode and isinstance(predictions[0], list): + # `predictions` is a list of method outputs from each fold. + # If each of those is also a list, then treat this as a + # multioutput-multiclass task. We need to separately concatenate + # the method outputs for each label into an `n_labels` long list. + n_labels = y.shape[1] + concat_pred = [] + for i_label in range(n_labels): + label_preds = np.concatenate([p[i_label] for p in predictions]) + concat_pred.append(label_preds) + predictions = concat_pred + else: + predictions = np.concatenate(predictions) + + if isinstance(predictions, list): + return [p[inv_test_indices] for p in predictions] + else: + return predictions[inv_test_indices] + + +def _fit_and_predict(estimator, X, y, train, test, fit_params, method): + """Fit estimator and predict values for a given dataset split. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator object implementing 'fit' and 'predict' + The object to use to fit the data. + + X : array-like of shape (n_samples, n_features) + The data to fit. + + .. versionchanged:: 0.20 + X is only required to be an object with finite length or shape now + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + The target variable to try to predict in the case of + supervised learning. + + train : array-like of shape (n_train_samples,) + Indices of training samples. + + test : array-like of shape (n_test_samples,) + Indices of test samples. + + fit_params : dict or None + Parameters that will be passed to ``estimator.fit``. + + method : str + Invokes the passed method name of the passed estimator. + + Returns + ------- + predictions : sequence + Result of calling 'estimator.method' + """ + # Adjust length of sample weights + fit_params = fit_params if fit_params is not None else {} + fit_params = _check_method_params(X, params=fit_params, indices=train) + + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, _ = _safe_split(estimator, X, y, test, train) + + if y_train is None: + estimator.fit(X_train, **fit_params) + else: + estimator.fit(X_train, y_train, **fit_params) + func = getattr(estimator, method) + predictions = func(X_test) + + encode = ( + method in ["decision_function", "predict_proba", "predict_log_proba"] + and y is not None + ) + + if encode: + if isinstance(predictions, list): + predictions = [ + _enforce_prediction_order( + estimator.classes_[i_label], + predictions[i_label], + n_classes=len(set(y[:, i_label])), + method=method, + ) + for i_label in range(len(predictions)) + ] + else: + # A 2D y array should be a binary label indicator matrix + n_classes = len(set(y)) if y.ndim == 1 else y.shape[1] + predictions = _enforce_prediction_order( + estimator.classes_, predictions, n_classes, method + ) + return predictions + + +def _enforce_prediction_order(classes, predictions, n_classes, method): + """Ensure that prediction arrays have correct column order + + When doing cross-validation, if one or more classes are + not present in the subset of data used for training, + then the output prediction array might not have the same + columns as other folds. Use the list of class names + (assumed to be ints) to enforce the correct column order. + + Note that `classes` is the list of classes in this fold + (a subset of the classes in the full training set) + and `n_classes` is the number of classes in the full training set. + """ + if n_classes != len(classes): + recommendation = ( + "To fix this, use a cross-validation " + "technique resulting in properly " + "stratified folds" + ) + warnings.warn( + "Number of classes in training fold ({}) does " + "not match total number of classes ({}). " + "Results may not be appropriate for your use case. " + "{}".format(len(classes), n_classes, recommendation), + RuntimeWarning, + ) + if method == "decision_function": + if predictions.ndim == 2 and predictions.shape[1] != len(classes): + # This handles the case when the shape of predictions + # does not match the number of classes used to train + # it with. This case is found when sklearn.svm.SVC is + # set to `decision_function_shape='ovo'`. + raise ValueError( + "Output shape {} of {} does not match " + "number of classes ({}) in fold. " + "Irregular decision_function outputs " + "are not currently supported by " + "cross_val_predict".format(predictions.shape, method, len(classes)) + ) + if len(classes) <= 2: + # In this special case, `predictions` contains a 1D array. + raise ValueError( + "Only {} class/es in training fold, but {} " + "in overall dataset. This " + "is not supported for decision_function " + "with imbalanced folds. {}".format( + len(classes), n_classes, recommendation + ) + ) + + float_min = np.finfo(predictions.dtype).min + default_values = { + "decision_function": float_min, + "predict_log_proba": float_min, + "predict_proba": 0, + } + predictions_for_all_classes = np.full( + (_num_samples(predictions), n_classes), + default_values[method], + dtype=predictions.dtype, + ) + predictions_for_all_classes[:, classes] = predictions + predictions = predictions_for_all_classes + return predictions + + +def _check_is_permutation(indices, n_samples): + """Check whether indices is a reordering of the array np.arange(n_samples) + + Parameters + ---------- + indices : ndarray + int array to test + n_samples : int + number of expected elements + + Returns + ------- + is_partition : bool + True iff sorted(indices) is np.arange(n) + """ + if len(indices) != n_samples: + return False + hit = np.zeros(n_samples, dtype=bool) + hit[indices] = True + if not np.all(hit): + return False + return True + + +@validate_params( + { + "estimator": [HasMethods("fit")], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", None], + "groups": ["array-like", None], + "cv": ["cv_object"], + "n_permutations": [Interval(Integral, 1, None, closed="left")], + "n_jobs": [Integral, None], + "random_state": ["random_state"], + "verbose": ["verbose"], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "fit_params": [dict, None], + "params": [dict, None], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +def permutation_test_score( + estimator, + X, + y, + *, + groups=None, + cv=None, + n_permutations=100, + n_jobs=None, + random_state=0, + verbose=0, + scoring=None, + fit_params=None, + 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 + independent. + + The p-value represents the fraction of randomized data sets where the + estimator performed as well or better than on the original data. A small + p-value suggests that there is a real dependency between features and + targets which has been used by the estimator to give good predictions. + A large p-value may be due to lack of real dependency between features + and targets or the estimator was not able to use the dependency to + give good predictions. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : estimator object implementing 'fit' + The object to use to fit the data. + + X : array-like of shape at least 2D + The data to fit. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + The target variable to try to predict in the case of + supervised learning. + + groups : array-like of shape (n_samples,), default=None + Labels to constrain permutation within groups, i.e. ``y`` values + are permuted among samples with the same group identifier. + When not specified, ``y`` values are permuted among all samples. + + When a grouped cross-validator is used, the group labels are + also passed on to the ``split`` method of the cross-validator. The + cross-validator uses them for grouping the samples while splitting + the dataset into train/test set. + + .. versionchanged:: 1.6 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``permutation_test_score(..., params={'groups': groups})``. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - `None`, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For `int`/`None` inputs, if the estimator is a classifier and `y` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + `cv` default value if `None` changed from 3-fold to 5-fold. + + n_permutations : int, default=100 + Number of times to permute ``y``. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and computing + the cross-validated score are parallelized over the permutations. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + random_state : int, RandomState instance or None, default=0 + Pass an int for reproducible output for permutation of + ``y`` values among samples. See :term:`Glossary `. + + verbose : int, default=0 + The verbosity level. + + scoring : str or callable, default=None + Scoring method to use to evaluate the predictions on the validation set. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``, which should return only a single value. + See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + .. deprecated:: 1.6 + This parameter is deprecated and will be removed in version 1.6. Use + ``params`` instead. + + params : dict, default=None + Parameters to pass to the `fit` method of the estimator, the scorer + and the cv splitter. + + - If `enable_metadata_routing=False` (default): Parameters directly passed to + the `fit` method of the estimator. + + - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` + method of the estimator, `cv` object and `scorer`. See :ref:`Metadata Routing + User Guide ` for more details. + + .. versionadded:: 1.6 + + Returns + ------- + score : float + The true score without permuting targets. + + permutation_scores : array of shape (n_permutations,) + The scores obtained for each permutations. + + pvalue : float + The p-value, which approximates the probability that the score would + be obtained by chance. This is calculated as: + + `(C + 1) / (n_permutations + 1)` + + Where C is the number of permutations whose score >= the true score. + + The best possible p-value is 1/(n_permutations + 1), the worst is 1.0. + + Notes + ----- + This function implements Test 1 in: + + Ojala and Garriga. `Permutation Tests for Studying Classifier Performance + `_. The + Journal of Machine Learning Research (2010) vol. 11 + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.linear_model import LogisticRegression + >>> from sklearn.model_selection import permutation_test_score + >>> X, y = make_classification(random_state=0) + >>> estimator = LogisticRegression() + >>> score, permutation_scores, pvalue = permutation_test_score( + ... estimator, X, y, random_state=0 + ... ) + >>> print(f"Original Score: {score:.3f}") + Original Score: 0.810 + >>> print( + ... f"Permutation Scores: {permutation_scores.mean():.3f} +/- " + ... f"{permutation_scores.std():.3f}" + ... ) + Permutation Scores: 0.505 +/- 0.057 + >>> print(f"P-value: {pvalue:.3f}") + P-value: 0.010 + """ + params = _check_params_groups_deprecation(fit_params, params, groups, "1.8") + + X, y, groups = indexable(X, y, groups) + + cv = check_cv(cv, y, classifier=is_classifier(estimator)) + scorer = check_scoring(estimator, scoring=scoring) + random_state = check_random_state(random_state) + + if _routing_enabled(): + router = ( + MetadataRouter(owner="permutation_test_score") + .add( + estimator=estimator, + # TODO(SLEP6): also pass metadata to the predict method for + # scoring? + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + .add( + splitter=cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + scorer=scorer, + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + ) + + try: + routed_params = process_routing(router, "fit", **params) + except UnsetMetadataPassedError as e: + # The default exception would mention `fit` since in the above + # `process_routing` code, we pass `fit` as the caller. However, + # the user is not calling `fit` directly, so we change the message + # to make it more suitable for this case. + raise UnsetMetadataPassedError( + message=str(e).replace( + "permutation_test_score.fit", "permutation_test_score" + ), + unrequested_params=e.unrequested_params, + routed_params=e.routed_params, + ) + + else: + routed_params = Bunch() + routed_params.estimator = Bunch(fit=params) + routed_params.splitter = Bunch(split={"groups": groups}) + routed_params.scorer = Bunch(score={}) + + # 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, + cv, + scorer, + split_params=routed_params.splitter.split, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + ) + permutation_scores = Parallel(n_jobs=n_jobs, verbose=verbose)( + delayed(_permutation_test_score)( + clone(estimator), + X, + _shuffle(y, groups, random_state), + cv, + scorer, + split_params=routed_params.splitter.split, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + ) + 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, cv, scorer, split_params, fit_params, score_params +): + """Auxiliary function for permutation_test_score""" + # Adjust length of sample weights + fit_params = fit_params if fit_params is not None else {} + score_params = score_params if score_params is not None else {} + + avg_score = [] + for train, test in cv.split(X, y, **split_params): + X_train, y_train = _safe_split(estimator, X, y, train) + X_test, y_test = _safe_split(estimator, X, y, test, train) + fit_params_train = _check_method_params(X, params=fit_params, indices=train) + score_params_test = _check_method_params(X, params=score_params, indices=test) + estimator.fit(X_train, y_train, **fit_params_train) + avg_score.append(scorer(estimator, X_test, y_test, **score_params_test)) + return np.mean(avg_score) + + +def _shuffle(y, groups, random_state): + """Return a shuffled copy of y eventually shuffle among same groups.""" + if groups is None: + indices = random_state.permutation(len(y)) + else: + indices = np.arange(len(groups)) + for group in np.unique(groups): + this_mask = groups == group + indices[this_mask] = random_state.permutation(indices[this_mask]) + return _safe_indexing(y, indices) + + +@validate_params( + { + "estimator": [HasMethods(["fit"])], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", None], + "groups": ["array-like", None], + "train_sizes": ["array-like"], + "cv": ["cv_object"], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "exploit_incremental_learning": ["boolean"], + "n_jobs": [Integral, None], + "pre_dispatch": [Integral, str], + "verbose": ["verbose"], + "shuffle": ["boolean"], + "random_state": ["random_state"], + "error_score": [StrOptions({"raise"}), Real], + "return_times": ["boolean"], + "fit_params": [dict, None], + "params": [dict, None], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +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, + fit_params=None, + params=None, +): + """Learning curve. + + Determines cross-validated training and test scores for different training + set sizes. + + A cross-validation generator splits the whole dataset k times in training + and test data. Subsets of the training set with varying sizes will be used + to train the estimator and a score for each training subset size and the + test set will be computed. Afterwards, the scores will be averaged over + all k runs for each training subset size. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object type that implements the "fit" method + An object of that type which is cloned for each validation. It must + also implement "predict" unless `scoring` is a callable that doesn't + rely on "predict" to compute a score. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + 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:`GroupKFold`). + + .. versionchanged:: 1.6 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``learning_curve(..., params={'groups': groups})``. + + train_sizes : array-like of shape (n_ticks,), \ + default=np.linspace(0.1, 1.0, 5) + Relative or absolute numbers of training examples that will be used to + generate the learning curve. If the dtype is float, it is regarded as a + fraction of the maximum size of the training set (that is determined + by the selected validation method), i.e. it has to be within (0, 1]. + Otherwise it is interpreted as absolute sizes of the training sets. + Note that for classification the number of samples usually has to + be big enough to contain at least one sample from each class. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + scoring : str or callable, default=None + Scoring method to use to evaluate the training and test sets. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + exploit_incremental_learning : bool, default=False + If the estimator supports incremental learning, this will be + used to speed up fitting for different training set sizes. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and computing + the score are parallelized over the different training and test sets. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + pre_dispatch : int or str, default='all' + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The str can + be an expression like '2*n_jobs'. + + verbose : int, default=0 + Controls the verbosity: the higher, the more messages. + + shuffle : bool, default=False + Whether to shuffle training data before taking prefixes of it + based on``train_sizes``. + + random_state : int, RandomState instance or None, default=None + Used when ``shuffle`` is True. Pass an int for reproducible + output across multiple function calls. + See :term:`Glossary `. + + 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. + If a numeric value is given, FitFailedWarning is raised. + + .. versionadded:: 0.20 + + return_times : bool, default=False + Whether to return the fit and score times. + + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + .. deprecated:: 1.6 + This parameter is deprecated and will be removed in version 1.8. Use + ``params`` instead. + + params : dict, default=None + Parameters to pass to the `fit` method of the estimator and to the scorer. + + - If `enable_metadata_routing=False` (default): Parameters directly passed to + the `fit` method of the estimator. + + - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` + method of the estimator. See :ref:`Metadata Routing User Guide + ` for more details. + + .. versionadded:: 1.6 + + Returns + ------- + train_sizes_abs : array of shape (n_unique_ticks,) + Numbers of training examples that has been used to generate the + learning curve. Note that the number of ticks might be less + than n_ticks because duplicate entries will be removed. + + train_scores : array of shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : array of shape (n_ticks, n_cv_folds) + Scores on test set. + + fit_times : array of shape (n_ticks, n_cv_folds) + Times spent for fitting in seconds. Only present if ``return_times`` + is True. + + score_times : array of shape (n_ticks, n_cv_folds) + Times spent for scoring in seconds. Only present if ``return_times`` + is True. + + See Also + -------- + LearningCurveDisplay.from_estimator : Plot a learning curve using an + estimator and data. + + Examples + -------- + >>> from sklearn.datasets import make_classification + >>> from sklearn.tree import DecisionTreeClassifier + >>> from sklearn.model_selection import learning_curve + >>> X, y = make_classification(n_samples=100, n_features=10, random_state=42) + >>> tree = DecisionTreeClassifier(max_depth=4, random_state=42) + >>> train_size_abs, train_scores, test_scores = learning_curve( + ... tree, X, y, train_sizes=[0.3, 0.6, 0.9] + ... ) + >>> for train_size, cv_train_scores, cv_test_scores in zip( + ... train_size_abs, train_scores, test_scores + ... ): + ... print(f"{train_size} samples were used to train the model") + ... print(f"The average train accuracy is {cv_train_scores.mean():.2f}") + ... print(f"The average test accuracy is {cv_test_scores.mean():.2f}") + 24 samples were used to train the model + The average train accuracy is 1.00 + The average test accuracy is 0.85 + 48 samples were used to train the model + The average train accuracy is 1.00 + The average test accuracy is 0.90 + 72 samples were used to train the model + The average train accuracy is 1.00 + The average test accuracy is 0.93 + """ + if exploit_incremental_learning and not hasattr(estimator, "partial_fit"): + raise ValueError( + "An estimator must support the partial_fit interface " + "to exploit incremental learning" + ) + + params = _check_params_groups_deprecation(fit_params, params, groups, "1.8") + + X, y, groups = indexable(X, y, groups) + + cv = check_cv(cv, y, classifier=is_classifier(estimator)) + + scorer = check_scoring(estimator, scoring=scoring) + + if _routing_enabled(): + router = ( + MetadataRouter(owner="learning_curve") + .add( + estimator=estimator, + # TODO(SLEP6): also pass metadata to the predict method for + # scoring? + method_mapping=MethodMapping() + .add(caller="fit", callee="fit") + .add(caller="fit", callee="partial_fit"), + ) + .add( + splitter=cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + scorer=scorer, + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + ) + + try: + routed_params = process_routing(router, "fit", **params) + except UnsetMetadataPassedError as e: + # The default exception would mention `fit` since in the above + # `process_routing` code, we pass `fit` as the caller. However, + # the user is not calling `fit` directly, so we change the message + # to make it more suitable for this case. + raise UnsetMetadataPassedError( + message=str(e).replace("learning_curve.fit", "learning_curve"), + unrequested_params=e.unrequested_params, + routed_params=e.routed_params, + ) + + else: + routed_params = Bunch() + routed_params.estimator = Bunch(fit=params, partial_fit=params) + routed_params.splitter = Bunch(split={"groups": groups}) + routed_params.scorer = Bunch(score={}) + + # Store cv as list as we will be iterating over the list multiple times + cv_iter = list(cv.split(X, y, **routed_params.splitter.split)) + + n_max_training_samples = len(cv_iter[0][0]) + # Because the lengths of folds can be significantly different, it is + # not guaranteed that we use all of the available training data when we + # use the first 'n_max_training_samples' samples. + train_sizes_abs = _translate_train_sizes(train_sizes, n_max_training_samples) + n_unique_ticks = train_sizes_abs.shape[0] + if verbose > 0: + print("[learning_curve] Training set sizes: " + str(train_sizes_abs)) + + parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) + + if shuffle: + rng = check_random_state(random_state) + cv_iter = ((rng.permutation(train), test) for train, test in cv_iter) + + if exploit_incremental_learning: + 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, + return_times, + error_score=error_score, + fit_params=routed_params.estimator.partial_fit, + score_params=routed_params.scorer.score, + ) + for train, test in cv_iter + ) + out = np.asarray(out).transpose((2, 1, 0)) + else: + train_test_proportions = [] + for train, test in cv_iter: + for n_train_samples in train_sizes_abs: + train_test_proportions.append((train[:n_train_samples], test)) + + results = parallel( + delayed(_fit_and_score)( + clone(estimator), + X, + y, + scorer=scorer, + train=train, + test=test, + verbose=verbose, + parameters=None, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + return_train_score=True, + error_score=error_score, + return_times=return_times, + ) + for train, test in train_test_proportions + ) + _warn_or_raise_about_fit_failures(results, error_score) + 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 + out = [train_scores, test_scores] + + if return_times: + fit_times = results["fit_time"].reshape(-1, n_unique_ticks).T + score_times = results["score_time"].reshape(-1, n_unique_ticks).T + out.extend([fit_times, score_times]) + + ret = train_sizes_abs, out[0], out[1] + + if return_times: + ret = ret + (out[2], out[3]) + + return ret + + +def _translate_train_sizes(train_sizes, n_max_training_samples): + """Determine absolute sizes of training subsets and validate 'train_sizes'. + + Examples: + _translate_train_sizes([0.5, 1.0], 10) -> [5, 10] + _translate_train_sizes([5, 10], 10) -> [5, 10] + + Parameters + ---------- + train_sizes : array-like of shape (n_ticks,) + Numbers of training examples that will be used to generate the + learning curve. If the dtype is float, it is regarded as a + fraction of 'n_max_training_samples', i.e. it has to be within (0, 1]. + + n_max_training_samples : int + Maximum number of training samples (upper bound of 'train_sizes'). + + Returns + ------- + train_sizes_abs : array of shape (n_unique_ticks,) + Numbers of training examples that will be used to generate the + learning curve. Note that the number of ticks might be less + than n_ticks because duplicate entries will be removed. + """ + train_sizes_abs = np.asarray(train_sizes) + n_ticks = train_sizes_abs.shape[0] + n_min_required_samples = np.min(train_sizes_abs) + n_max_required_samples = np.max(train_sizes_abs) + if np.issubdtype(train_sizes_abs.dtype, np.floating): + if n_min_required_samples <= 0.0 or n_max_required_samples > 1.0: + raise ValueError( + "train_sizes has been interpreted as fractions " + "of the maximum number of training samples and " + "must be within (0, 1], but is within [%f, %f]." + % (n_min_required_samples, n_max_required_samples) + ) + train_sizes_abs = (train_sizes_abs * n_max_training_samples).astype( + dtype=int, copy=False + ) + train_sizes_abs = np.clip(train_sizes_abs, 1, n_max_training_samples) + else: + if ( + n_min_required_samples <= 0 + or n_max_required_samples > n_max_training_samples + ): + raise ValueError( + "train_sizes has been interpreted as absolute " + "numbers of training samples and must be within " + "(0, %d], but is within [%d, %d]." + % ( + n_max_training_samples, + n_min_required_samples, + n_max_required_samples, + ) + ) + + train_sizes_abs = np.unique(train_sizes_abs) + if n_ticks > train_sizes_abs.shape[0]: + warnings.warn( + "Removed duplicate entries from 'train_sizes'. Number " + "of ticks will be less than the size of " + "'train_sizes': %d instead of %d." % (train_sizes_abs.shape[0], n_ticks), + RuntimeWarning, + ) + + return train_sizes_abs + + +def _incremental_fit_estimator( + estimator, + X, + y, + classes, + train, + test, + train_sizes, + scorer, + return_times, + error_score, + fit_params, + score_params, +): + """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]) + if fit_params is None: + fit_params = {} + if classes is None: + partial_fit_func = partial(estimator.partial_fit, **fit_params) + else: + partial_fit_func = partial(estimator.partial_fit, classes=classes, **fit_params) + score_params = score_params if score_params is not None else {} + score_params_train = _check_method_params(X, params=score_params, indices=train) + score_params_test = _check_method_params(X, params=score_params, indices=test) + + for n_train_samples, partial_train in partitions: + train_subset = train[:n_train_samples] + X_train, y_train = _safe_split(estimator, X, y, train_subset) + X_partial_train, y_partial_train = _safe_split(estimator, X, y, partial_train) + X_test, y_test = _safe_split(estimator, X, y, test, train_subset) + start_fit = time.time() + if y_partial_train is None: + partial_fit_func(X_partial_train) + else: + partial_fit_func(X_partial_train, y_partial_train) + fit_time = time.time() - start_fit + fit_times.append(fit_time) + + start_score = time.time() + + test_scores.append( + _score( + estimator, + X_test, + y_test, + scorer, + score_params=score_params_test, + error_score=error_score, + ) + ) + train_scores.append( + _score( + estimator, + X_train, + y_train, + scorer, + score_params=score_params_train, + error_score=error_score, + ) + ) + score_time = time.time() - start_score + score_times.append(score_time) + + ret = ( + (train_scores, test_scores, fit_times, score_times) + if return_times + else (train_scores, test_scores) + ) + + return np.array(ret).T + + +@validate_params( + { + "estimator": [HasMethods(["fit"])], + "X": ["array-like", "sparse matrix"], + "y": ["array-like", None], + "param_name": [str], + "param_range": ["array-like"], + "groups": ["array-like", None], + "cv": ["cv_object"], + "scoring": [StrOptions(set(get_scorer_names())), callable, None], + "n_jobs": [Integral, None], + "pre_dispatch": [Integral, str], + "verbose": ["verbose"], + "error_score": [StrOptions({"raise"}), Real], + "fit_params": [dict, None], + "params": [dict, None], + }, + prefer_skip_nested_validation=False, # estimator is not validated yet +) +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, + fit_params=None, + params=None, +): + """Validation curve. + + Determine training and test scores for varying parameter values. + + Compute scores for an estimator with different values of a specified + parameter. This is similar to grid search with one parameter. However, this + will also compute training scores and is merely a utility for plotting the + results. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + estimator : object type that implements the "fit" method + An object of that type which is cloned for each validation. It must + also implement "predict" unless `scoring` is a callable that doesn't + rely on "predict" to compute a score. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) or None + Target relative to X for classification or regression; + None for unsupervised learning. + + param_name : str + Name of the parameter that will be varied. + + param_range : array-like of shape (n_values,) + The values of the parameter that will be evaluated. + + 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:`GroupKFold`). + + .. versionchanged:: 1.6 + ``groups`` can only be passed if metadata routing is not enabled + via ``sklearn.set_config(enable_metadata_routing=True)``. When routing + is enabled, pass ``groups`` alongside other metadata via the ``params`` + argument instead. E.g.: + ``validation_curve(..., params={'groups': groups})``. + + cv : int, cross-validation generator or an iterable, default=None + Determines the cross-validation splitting strategy. + Possible inputs for cv are: + + - None, to use the default 5-fold cross validation, + - int, to specify the number of folds in a `(Stratified)KFold`, + - :term:`CV splitter`, + - An iterable yielding (train, test) splits as arrays of indices. + + For int/None inputs, if the estimator is a classifier and ``y`` is + either binary or multiclass, :class:`StratifiedKFold` is used. In all + other cases, :class:`KFold` is used. These splitters are instantiated + with `shuffle=False` so the splits will be the same across calls. + + Refer :ref:`User Guide ` for the various + cross-validation strategies that can be used here. + + .. versionchanged:: 0.22 + ``cv`` default value if None changed from 3-fold to 5-fold. + + scoring : str or callable, default=None + Scoring method to use to evaluate the training and test sets. + + - str: see :ref:`scoring_string_names` for options. + - callable: a scorer callable object (e.g., function) with signature + ``scorer(estimator, X, y)``. See :ref:`scoring_callable` for details. + - `None`: the `estimator`'s + :ref:`default evaluation criterion ` is used. + + n_jobs : int, default=None + Number of jobs to run in parallel. Training the estimator and computing + the score are parallelized over the combinations of each parameter + value and each cross-validation split. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + pre_dispatch : int or str, default='all' + Number of predispatched jobs for parallel execution (default is + all). The option can reduce the allocated memory. The str can + be an expression like '2*n_jobs'. + + verbose : int, default=0 + Controls the verbosity: the higher, the more messages. + + 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. + If a numeric value is given, FitFailedWarning is raised. + + .. versionadded:: 0.20 + + fit_params : dict, default=None + Parameters to pass to the fit method of the estimator. + + .. deprecated:: 1.6 + This parameter is deprecated and will be removed in version 1.8. Use + ``params`` instead. + + params : dict, default=None + Parameters to pass to the estimator, scorer and cross-validation object. + + - If `enable_metadata_routing=False` (default): Parameters directly passed to + the `fit` method of the estimator. + + - If `enable_metadata_routing=True`: Parameters safely routed to the `fit` + method of the estimator, to the scorer and to the cross-validation object. + See :ref:`Metadata Routing User Guide ` for more details. + + .. versionadded:: 1.6 + + Returns + ------- + train_scores : array of shape (n_ticks, n_cv_folds) + Scores on training sets. + + test_scores : array of shape (n_ticks, n_cv_folds) + Scores on test set. + + See Also + -------- + ValidationCurveDisplay.from_estimator : Plot the validation curve + given an estimator, the data, and the parameter to vary. + + Notes + ----- + See :ref:`sphx_glr_auto_examples_model_selection_plot_train_error_vs_test_error.py` + + Examples + -------- + >>> import numpy as np + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import validation_curve + >>> from sklearn.linear_model import LogisticRegression + >>> X, y = make_classification(n_samples=1_000, random_state=0) + >>> logistic_regression = LogisticRegression() + >>> param_name, param_range = "C", np.logspace(-8, 3, 10) + >>> train_scores, test_scores = validation_curve( + ... logistic_regression, X, y, param_name=param_name, param_range=param_range + ... ) + >>> print(f"The average train accuracy is {train_scores.mean():.2f}") + The average train accuracy is 0.81 + >>> print(f"The average test accuracy is {test_scores.mean():.2f}") + The average test accuracy is 0.81 + """ + params = _check_params_groups_deprecation(fit_params, params, groups, "1.8") + X, y, groups = indexable(X, y, groups) + + cv = check_cv(cv, y, classifier=is_classifier(estimator)) + scorer = check_scoring(estimator, scoring=scoring) + + if _routing_enabled(): + router = ( + MetadataRouter(owner="validation_curve") + .add( + estimator=estimator, + method_mapping=MethodMapping().add(caller="fit", callee="fit"), + ) + .add( + splitter=cv, + method_mapping=MethodMapping().add(caller="fit", callee="split"), + ) + .add( + scorer=scorer, + method_mapping=MethodMapping().add(caller="fit", callee="score"), + ) + ) + + try: + routed_params = process_routing(router, "fit", **params) + except UnsetMetadataPassedError as e: + # The default exception would mention `fit` since in the above + # `process_routing` code, we pass `fit` as the caller. However, + # the user is not calling `fit` directly, so we change the message + # to make it more suitable for this case. + raise UnsetMetadataPassedError( + message=str(e).replace("validation_curve.fit", "validation_curve"), + unrequested_params=e.unrequested_params, + routed_params=e.routed_params, + ) + + else: + routed_params = Bunch() + routed_params.estimator = Bunch(fit=params) + routed_params.splitter = Bunch(split={"groups": groups}) + routed_params.scorer = Bunch(score={}) + + parallel = Parallel(n_jobs=n_jobs, pre_dispatch=pre_dispatch, verbose=verbose) + results = parallel( + delayed(_fit_and_score)( + clone(estimator), + X, + y, + scorer=scorer, + train=train, + test=test, + verbose=verbose, + parameters={param_name: v}, + fit_params=routed_params.estimator.fit, + score_params=routed_params.scorer.score, + 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, **routed_params.splitter.split) + for v in param_range + ) + n_params = len(param_range) + + results = _aggregate_score_dicts(results) + train_scores = results["train_scores"].reshape(-1, n_params).T + test_scores = results["test_scores"].reshape(-1, n_params).T + + return train_scores, test_scores + + +def _aggregate_score_dicts(scores): + """Aggregate the list of dict to dict of np ndarray + + The aggregated output of _aggregate_score_dicts will be a list of dict + of form [{'prec': 0.1, 'acc':1.0}, {'prec': 0.1, 'acc':1.0}, ...] + Convert it to a dict of array {'prec': np.array([0.1 ...]), ...} + + Parameters + ---------- + + scores : list of dict + List of dicts of the scores for all scorers. This is a flat list, + assumed originally to be of row major order. + + Example + ------- + + >>> scores = [{'a': 1, 'b':10}, {'a': 2, 'b':2}, {'a': 3, 'b':3}, + ... {'a': 10, 'b': 10}] # doctest: +SKIP + >>> _aggregate_score_dicts(scores) # doctest: +SKIP + {'a': array([1, 2, 3, 10]), + 'b': array([10, 2, 3, 10])} + """ + return { + key: ( + np.asarray([score[key] for score in scores]) + if isinstance(scores[0][key], numbers.Number) + else [score[key] for score in scores] + ) + for key in scores[0] + } diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/common.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/common.py new file mode 100644 index 0000000000000000000000000000000000000000..54a993db76933a5e710f0ddd20a4efd0118ecf95 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/common.py @@ -0,0 +1,24 @@ +""" +Common utilities for testing model selection. +""" + +import numpy as np + +from sklearn.model_selection import KFold + + +class OneTimeSplitter: + """A wrapper to make KFold single entry cv iterator""" + + def __init__(self, n_splits=4, n_samples=99): + self.n_splits = n_splits + self.n_samples = n_samples + self.indices = iter(KFold(n_splits=n_splits).split(np.ones(n_samples))) + + def split(self, X=None, y=None, groups=None): + """Split can be called only once""" + for index in self.indices: + yield index + + def get_n_splits(self, X=None, y=None, groups=None): + return self.n_splits diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_classification_threshold.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_classification_threshold.py new file mode 100644 index 0000000000000000000000000000000000000000..1ba4dcea369748622d366df0477e3b7911873593 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_classification_threshold.py @@ -0,0 +1,618 @@ +import numpy as np +import pytest + +from sklearn import config_context +from sklearn.base import clone +from sklearn.datasets import ( + load_breast_cancer, + load_iris, + make_classification, + make_multilabel_classification, +) +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import GradientBoostingClassifier +from sklearn.exceptions import NotFittedError +from sklearn.linear_model import LogisticRegression +from sklearn.metrics import ( + balanced_accuracy_score, + f1_score, + fbeta_score, + make_scorer, +) +from sklearn.metrics._scorer import _CurveScorer +from sklearn.model_selection import ( + FixedThresholdClassifier, + StratifiedShuffleSplit, + TunedThresholdClassifierCV, +) +from sklearn.model_selection._classification_threshold import ( + _fit_and_score_over_thresholds, +) +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils._mocking import CheckingClassifier +from sklearn.utils._testing import ( + _convert_container, + assert_allclose, + assert_array_equal, +) + + +def test_fit_and_score_over_thresholds_curve_scorers(): + """Check that `_fit_and_score_over_thresholds` returns thresholds in ascending order + for the different accepted curve scorers.""" + X, y = make_classification(n_samples=100, random_state=0) + train_idx, val_idx = np.arange(50), np.arange(50, 100) + classifier = LogisticRegression() + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + scores, thresholds = _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params={}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + assert np.all(thresholds[:-1] <= thresholds[1:]) + assert isinstance(scores, np.ndarray) + assert np.logical_and(scores >= 0, scores <= 1).all() + + +def test_fit_and_score_over_thresholds_prefit(): + """Check the behaviour with a prefit classifier.""" + X, y = make_classification(n_samples=100, random_state=0) + + # `train_idx is None` to indicate that the classifier is prefit + train_idx, val_idx = None, np.arange(50, 100) + classifier = DecisionTreeClassifier(random_state=0).fit(X, y) + # make sure that the classifier memorized the full dataset such that + # we get perfect predictions and thus match the expected score + assert classifier.score(X[val_idx], y[val_idx]) == pytest.approx(1.0) + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=2, + kwargs={}, + ) + scores, thresholds = _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params={}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + assert np.all(thresholds[:-1] <= thresholds[1:]) + assert_allclose(scores, [0.5, 1.0]) + + +@config_context(enable_metadata_routing=True) +def test_fit_and_score_over_thresholds_sample_weight(): + """Check that we dispatch the sample-weight to fit and score the classifier.""" + X, y = load_iris(return_X_y=True) + X, y = X[:100], y[:100] # only 2 classes + + # create a dataset and repeat twice the sample of class #0 + X_repeated, y_repeated = np.vstack([X, X[y == 0]]), np.hstack([y, y[y == 0]]) + # create a sample weight vector that is equivalent to the repeated dataset + sample_weight = np.ones_like(y) + sample_weight[:50] *= 2 + + classifier = LogisticRegression() + train_repeated_idx = np.arange(X_repeated.shape[0]) + val_repeated_idx = np.arange(X_repeated.shape[0]) + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + scores_repeated, thresholds_repeated = _fit_and_score_over_thresholds( + classifier, + X_repeated, + y_repeated, + fit_params={}, + train_idx=train_repeated_idx, + val_idx=val_repeated_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + train_idx, val_idx = np.arange(X.shape[0]), np.arange(X.shape[0]) + scores, thresholds = _fit_and_score_over_thresholds( + classifier.set_fit_request(sample_weight=True), + X, + y, + fit_params={"sample_weight": sample_weight}, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer.set_score_request(sample_weight=True), + score_params={"sample_weight": sample_weight}, + ) + + assert_allclose(thresholds_repeated, thresholds) + assert_allclose(scores_repeated, scores) + + +@pytest.mark.parametrize("fit_params_type", ["list", "array"]) +@config_context(enable_metadata_routing=True) +def test_fit_and_score_over_thresholds_fit_params(fit_params_type): + """Check that we pass `fit_params` to the classifier when calling `fit`.""" + X, y = make_classification(n_samples=100, random_state=0) + fit_params = { + "a": _convert_container(y, fit_params_type), + "b": _convert_container(y, fit_params_type), + } + + classifier = CheckingClassifier(expected_fit_params=["a", "b"], random_state=0) + classifier.set_fit_request(a=True, b=True) + train_idx, val_idx = np.arange(50), np.arange(50, 100) + + curve_scorer = _CurveScorer( + score_func=balanced_accuracy_score, + sign=1, + response_method="predict_proba", + thresholds=10, + kwargs={}, + ) + _fit_and_score_over_thresholds( + classifier, + X, + y, + fit_params=fit_params, + train_idx=train_idx, + val_idx=val_idx, + curve_scorer=curve_scorer, + score_params={}, + ) + + +@pytest.mark.parametrize( + "data", + [ + make_classification(n_classes=3, n_clusters_per_class=1, random_state=0), + make_multilabel_classification(random_state=0), + ], +) +def test_tuned_threshold_classifier_no_binary(data): + """Check that we raise an informative error message for non-binary problem.""" + err_msg = "Only binary classification is supported." + with pytest.raises(ValueError, match=err_msg): + TunedThresholdClassifierCV(LogisticRegression()).fit(*data) + + +@pytest.mark.parametrize( + "params, err_type, err_msg", + [ + ( + {"cv": "prefit", "refit": True}, + ValueError, + "When cv='prefit', refit cannot be True.", + ), + ( + {"cv": 10, "refit": False}, + ValueError, + "When cv has several folds, refit cannot be False.", + ), + ( + {"cv": "prefit", "refit": False}, + NotFittedError, + "`estimator` must be fitted.", + ), + ], +) +def test_tuned_threshold_classifier_conflict_cv_refit(params, err_type, err_msg): + """Check that we raise an informative error message when `cv` and `refit` + cannot be used together. + """ + X, y = make_classification(n_samples=100, random_state=0) + with pytest.raises(err_type, match=err_msg): + TunedThresholdClassifierCV(LogisticRegression(), **params).fit(X, y) + + +@pytest.mark.parametrize( + "estimator", + [LogisticRegression(), SVC(), GradientBoostingClassifier(n_estimators=4)], +) +@pytest.mark.parametrize( + "response_method", ["predict_proba", "predict_log_proba", "decision_function"] +) +@pytest.mark.parametrize( + "ThresholdClassifier", [FixedThresholdClassifier, TunedThresholdClassifierCV] +) +def test_threshold_classifier_estimator_response_methods( + ThresholdClassifier, estimator, response_method +): + """Check that `TunedThresholdClassifierCV` exposes the same response methods as the + underlying estimator. + """ + X, y = make_classification(n_samples=100, random_state=0) + + model = ThresholdClassifier(estimator=estimator) + assert hasattr(model, response_method) == hasattr(estimator, response_method) + + model.fit(X, y) + assert hasattr(model, response_method) == hasattr(estimator, response_method) + + if hasattr(model, response_method): + y_pred_cutoff = getattr(model, response_method)(X) + y_pred_underlying_estimator = getattr(model.estimator_, response_method)(X) + + assert_allclose(y_pred_cutoff, y_pred_underlying_estimator) + + +@pytest.mark.parametrize( + "response_method", ["auto", "decision_function", "predict_proba"] +) +def test_tuned_threshold_classifier_without_constraint_value(response_method): + """Check that `TunedThresholdClassifierCV` is optimizing a given objective + metric.""" + X, y = load_breast_cancer(return_X_y=True) + # remove feature to degrade performances + X = X[:, :5] + + # make the problem completely imbalanced such that the balanced accuracy is low + indices_pos = np.flatnonzero(y == 1) + indices_pos = indices_pos[: indices_pos.size // 50] + indices_neg = np.flatnonzero(y == 0) + + X = np.vstack([X[indices_neg], X[indices_pos]]) + y = np.hstack([y[indices_neg], y[indices_pos]]) + + lr = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y) + thresholds = 100 + model = TunedThresholdClassifierCV( + estimator=lr, + scoring="balanced_accuracy", + response_method=response_method, + thresholds=thresholds, + store_cv_results=True, + ) + score_optimized = balanced_accuracy_score(y, model.fit(X, y).predict(X)) + score_baseline = balanced_accuracy_score(y, lr.predict(X)) + assert score_optimized > score_baseline + assert model.cv_results_["thresholds"].shape == (thresholds,) + assert model.cv_results_["scores"].shape == (thresholds,) + + +def test_tuned_threshold_classifier_metric_with_parameter(): + """Check that we can pass a metric with a parameter in addition check that + `f_beta` with `beta=1` is equivalent to `f1` and different from `f_beta` with + `beta=2`. + """ + X, y = load_breast_cancer(return_X_y=True) + lr = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y) + model_fbeta_1 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(fbeta_score, beta=1) + ).fit(X, y) + model_fbeta_2 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(fbeta_score, beta=2) + ).fit(X, y) + model_f1 = TunedThresholdClassifierCV( + estimator=lr, scoring=make_scorer(f1_score) + ).fit(X, y) + + assert model_fbeta_1.best_threshold_ == pytest.approx(model_f1.best_threshold_) + assert model_fbeta_1.best_threshold_ != pytest.approx(model_fbeta_2.best_threshold_) + + +@pytest.mark.parametrize( + "response_method", ["auto", "decision_function", "predict_proba"] +) +@pytest.mark.parametrize( + "metric", + [ + make_scorer(balanced_accuracy_score), + make_scorer(f1_score, pos_label="cancer"), + ], +) +def test_tuned_threshold_classifier_with_string_targets(response_method, metric): + """Check that targets represented by str are properly managed. + Also, check with several metrics to be sure that `pos_label` is properly + dispatched. + """ + X, y = load_breast_cancer(return_X_y=True) + # Encode numeric targets by meaningful strings. We purposely designed the class + # names such that the `pos_label` is the first alphabetically sorted class and thus + # encoded as 0. + classes = np.array(["cancer", "healthy"], dtype=object) + y = classes[y] + model = TunedThresholdClassifierCV( + estimator=make_pipeline(StandardScaler(), LogisticRegression()), + scoring=metric, + response_method=response_method, + thresholds=100, + ).fit(X, y) + assert_array_equal(model.classes_, np.sort(classes)) + y_pred = model.predict(X) + assert_array_equal(np.unique(y_pred), np.sort(classes)) + + +@pytest.mark.parametrize("with_sample_weight", [True, False]) +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_refit(with_sample_weight, global_random_seed): + """Check the behaviour of the `refit` parameter.""" + rng = np.random.RandomState(global_random_seed) + X, y = make_classification(n_samples=100, random_state=0) + if with_sample_weight: + sample_weight = rng.randn(X.shape[0]) + sample_weight = np.abs(sample_weight, out=sample_weight) + else: + sample_weight = None + + # check that `estimator_` if fitted on the full dataset when `refit=True` + estimator = LogisticRegression().set_fit_request(sample_weight=True) + model = TunedThresholdClassifierCV(estimator, refit=True).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is not estimator + estimator.fit(X, y, sample_weight=sample_weight) + assert_allclose(model.estimator_.coef_, estimator.coef_) + assert_allclose(model.estimator_.intercept_, estimator.intercept_) + + # check that `estimator_` was not altered when `refit=False` and `cv="prefit"` + estimator = LogisticRegression().set_fit_request(sample_weight=True) + estimator.fit(X, y, sample_weight=sample_weight) + coef = estimator.coef_.copy() + model = TunedThresholdClassifierCV(estimator, cv="prefit", refit=False).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is estimator + assert_allclose(model.estimator_.coef_, coef) + + # check that we train `estimator_` on the training split of a given cross-validation + estimator = LogisticRegression().set_fit_request(sample_weight=True) + cv = [ + (np.arange(50), np.arange(50, 100)), + ] # single split + model = TunedThresholdClassifierCV(estimator, cv=cv, refit=False).fit( + X, y, sample_weight=sample_weight + ) + + assert model.estimator_ is not estimator + if with_sample_weight: + sw_train = sample_weight[cv[0][0]] + else: + sw_train = None + estimator.fit(X[cv[0][0]], y[cv[0][0]], sample_weight=sw_train) + assert_allclose(model.estimator_.coef_, estimator.coef_) + + +@pytest.mark.parametrize("fit_params_type", ["list", "array"]) +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_fit_params(fit_params_type): + """Check that we pass `fit_params` to the classifier when calling `fit`.""" + X, y = make_classification(n_samples=100, random_state=0) + fit_params = { + "a": _convert_container(y, fit_params_type), + "b": _convert_container(y, fit_params_type), + } + + classifier = CheckingClassifier(expected_fit_params=["a", "b"], random_state=0) + classifier.set_fit_request(a=True, b=True) + model = TunedThresholdClassifierCV(classifier) + model.fit(X, y, **fit_params) + + +@config_context(enable_metadata_routing=True) +def test_tuned_threshold_classifier_cv_zeros_sample_weights_equivalence(): + """Check that passing removing some sample from the dataset `X` is + equivalent to passing a `sample_weight` with a factor 0.""" + X, y = load_iris(return_X_y=True) + # Scale the data to avoid any convergence issue + X = StandardScaler().fit_transform(X) + # Only use 2 classes and select samples such that 2-fold cross-validation + # split will lead to an equivalence with a `sample_weight` of 0 + X = np.vstack((X[:40], X[50:90])) + y = np.hstack((y[:40], y[50:90])) + sample_weight = np.zeros_like(y) + sample_weight[::2] = 1 + + estimator = LogisticRegression().set_fit_request(sample_weight=True) + model_without_weights = TunedThresholdClassifierCV(estimator, cv=2) + model_with_weights = clone(model_without_weights) + + model_with_weights.fit(X, y, sample_weight=sample_weight) + model_without_weights.fit(X[::2], y[::2]) + + assert_allclose( + model_with_weights.estimator_.coef_, model_without_weights.estimator_.coef_ + ) + + y_pred_with_weights = model_with_weights.predict_proba(X) + y_pred_without_weights = model_without_weights.predict_proba(X) + assert_allclose(y_pred_with_weights, y_pred_without_weights) + + +def test_tuned_threshold_classifier_thresholds_array(): + """Check that we can pass an array to `thresholds` and it is used as candidate + threshold internally.""" + X, y = make_classification(random_state=0) + estimator = LogisticRegression() + thresholds = np.linspace(0, 1, 11) + tuned_model = TunedThresholdClassifierCV( + estimator, + thresholds=thresholds, + response_method="predict_proba", + store_cv_results=True, + ).fit(X, y) + assert_allclose(tuned_model.cv_results_["thresholds"], thresholds) + + +@pytest.mark.parametrize("store_cv_results", [True, False]) +def test_tuned_threshold_classifier_store_cv_results(store_cv_results): + """Check that if `cv_results_` exists depending on `store_cv_results`.""" + X, y = make_classification(random_state=0) + estimator = LogisticRegression() + tuned_model = TunedThresholdClassifierCV( + estimator, store_cv_results=store_cv_results + ).fit(X, y) + if store_cv_results: + assert hasattr(tuned_model, "cv_results_") + else: + assert not hasattr(tuned_model, "cv_results_") + + +def test_tuned_threshold_classifier_cv_float(): + """Check the behaviour when `cv` is set to a float.""" + X, y = make_classification(random_state=0) + + # case where `refit=False` and cv is a float: the underlying estimator will be fit + # on the training set given by a ShuffleSplit. We check that we get the same model + # coefficients. + test_size = 0.3 + estimator = LogisticRegression() + tuned_model = TunedThresholdClassifierCV( + estimator, cv=test_size, refit=False, random_state=0 + ).fit(X, y) + tuned_model.fit(X, y) + + cv = StratifiedShuffleSplit(n_splits=1, test_size=test_size, random_state=0) + train_idx, val_idx = next(cv.split(X, y)) + cloned_estimator = clone(estimator).fit(X[train_idx], y[train_idx]) + + assert_allclose(tuned_model.estimator_.coef_, cloned_estimator.coef_) + + # case where `refit=True`, then the underlying estimator is fitted on the full + # dataset. + tuned_model.set_params(refit=True).fit(X, y) + cloned_estimator = clone(estimator).fit(X, y) + + assert_allclose(tuned_model.estimator_.coef_, cloned_estimator.coef_) + + +def test_tuned_threshold_classifier_error_constant_predictor(): + """Check that we raise a ValueError if the underlying classifier returns constant + probabilities such that we cannot find any threshold. + """ + X, y = make_classification(random_state=0) + estimator = DummyClassifier(strategy="constant", constant=1) + tuned_model = TunedThresholdClassifierCV(estimator, response_method="predict_proba") + err_msg = "The provided estimator makes constant predictions" + with pytest.raises(ValueError, match=err_msg): + tuned_model.fit(X, y) + + +@pytest.mark.parametrize( + "response_method", ["auto", "predict_proba", "decision_function"] +) +def test_fixed_threshold_classifier_equivalence_default(response_method): + """Check that `FixedThresholdClassifier` has the same behaviour as the vanilla + classifier. + """ + X, y = make_classification(random_state=0) + classifier = LogisticRegression().fit(X, y) + classifier_default_threshold = FixedThresholdClassifier( + estimator=clone(classifier), response_method=response_method + ) + classifier_default_threshold.fit(X, y) + + # emulate the response method that should take into account the `pos_label` + if response_method in ("auto", "predict_proba"): + y_score = classifier_default_threshold.predict_proba(X)[:, 1] + threshold = 0.5 + else: # response_method == "decision_function" + y_score = classifier_default_threshold.decision_function(X) + threshold = 0.0 + + y_pred_lr = (y_score >= threshold).astype(int) + assert_allclose(classifier_default_threshold.predict(X), y_pred_lr) + + +@pytest.mark.parametrize( + "response_method, threshold", [("predict_proba", 0.7), ("decision_function", 2.0)] +) +@pytest.mark.parametrize("pos_label", [0, 1]) +def test_fixed_threshold_classifier(response_method, threshold, pos_label): + """Check that applying `predict` lead to the same prediction as applying the + threshold to the output of the response method. + """ + X, y = make_classification(n_samples=50, random_state=0) + logistic_regression = LogisticRegression().fit(X, y) + model = FixedThresholdClassifier( + estimator=clone(logistic_regression), + threshold=threshold, + response_method=response_method, + pos_label=pos_label, + ).fit(X, y) + + # check that the underlying estimator is the same + assert_allclose(model.estimator_.coef_, logistic_regression.coef_) + + # emulate the response method that should take into account the `pos_label` + if response_method == "predict_proba": + y_score = model.predict_proba(X)[:, pos_label] + else: # response_method == "decision_function" + y_score = model.decision_function(X) + y_score = y_score if pos_label == 1 else -y_score + + # create a mapping from boolean values to class labels + map_to_label = np.array([0, 1]) if pos_label == 1 else np.array([1, 0]) + y_pred_lr = map_to_label[(y_score >= threshold).astype(int)] + assert_allclose(model.predict(X), y_pred_lr) + + for method in ("predict_proba", "predict_log_proba", "decision_function"): + assert_allclose( + getattr(model, method)(X), getattr(logistic_regression, method)(X) + ) + assert_allclose( + getattr(model.estimator_, method)(X), + getattr(logistic_regression, method)(X), + ) + + +@config_context(enable_metadata_routing=True) +def test_fixed_threshold_classifier_metadata_routing(): + """Check that everything works with metadata routing.""" + X, y = make_classification(random_state=0) + sample_weight = np.ones_like(y) + sample_weight[::2] = 2 + classifier = LogisticRegression().set_fit_request(sample_weight=True) + classifier.fit(X, y, sample_weight=sample_weight) + classifier_default_threshold = FixedThresholdClassifier(estimator=clone(classifier)) + classifier_default_threshold.fit(X, y, sample_weight=sample_weight) + assert_allclose(classifier_default_threshold.estimator_.coef_, classifier.coef_) + + +@pytest.mark.parametrize( + "method", ["predict_proba", "decision_function", "predict", "predict_log_proba"] +) +def test_fixed_threshold_classifier_fitted_estimator(method): + """Check that if the underlying estimator is already fitted, no fit is required.""" + X, y = make_classification(random_state=0) + classifier = LogisticRegression().fit(X, y) + fixed_threshold_classifier = FixedThresholdClassifier(estimator=classifier) + # This should not raise an error + getattr(fixed_threshold_classifier, method)(X) + + +def test_fixed_threshold_classifier_classes_(): + """Check that the classes_ attribute is properly set.""" + X, y = make_classification(random_state=0) + with pytest.raises( + AttributeError, match="The underlying estimator is not fitted yet." + ): + FixedThresholdClassifier(estimator=LogisticRegression()).classes_ + + classifier = LogisticRegression().fit(X, y) + fixed_threshold_classifier = FixedThresholdClassifier(estimator=classifier) + assert_array_equal(fixed_threshold_classifier.classes_, classifier.classes_) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_plot.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_plot.py new file mode 100644 index 0000000000000000000000000000000000000000..4e884755174545ababe24d423fd84cf7882104cb --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_plot.py @@ -0,0 +1,572 @@ +import numpy as np +import pytest + +from sklearn.datasets import load_iris +from sklearn.model_selection import ( + LearningCurveDisplay, + ValidationCurveDisplay, + learning_curve, + validation_curve, +) +from sklearn.tree import DecisionTreeClassifier +from sklearn.utils import shuffle +from sklearn.utils._testing import assert_allclose, assert_array_equal + + +@pytest.fixture +def data(): + return shuffle(*load_iris(return_X_y=True), random_state=0) + + +@pytest.mark.parametrize( + "params, err_type, err_msg", + [ + ({"std_display_style": "invalid"}, ValueError, "Unknown std_display_style:"), + ({"score_type": "invalid"}, ValueError, "Unknown score_type:"), + ], +) +@pytest.mark.parametrize( + "CurveDisplay, specific_params", + [ + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + (LearningCurveDisplay, {"train_sizes": [0.3, 0.6, 0.9]}), + ], +) +def test_curve_display_parameters_validation( + pyplot, data, params, err_type, err_msg, CurveDisplay, specific_params +): + """Check that we raise a proper error when passing invalid parameters.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + with pytest.raises(err_type, match=err_msg): + CurveDisplay.from_estimator(estimator, X, y, **specific_params, **params) + + +def test_learning_curve_display_default_usage(pyplot, data): + """Check the default usage of the LearningCurveDisplay class.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + train_sizes = [0.3, 0.6, 0.9] + display = LearningCurveDisplay.from_estimator( + estimator, X, y, train_sizes=train_sizes + ) + + import matplotlib as mpl + + assert display.errorbar_ is None + + assert isinstance(display.lines_, list) + for line in display.lines_: + assert isinstance(line, mpl.lines.Line2D) + + assert isinstance(display.fill_between_, list) + for fill in display.fill_between_: + assert isinstance(fill, mpl.collections.PolyCollection) + assert fill.get_alpha() == 0.5 + + assert display.score_name == "Score" + assert display.ax_.get_xlabel() == "Number of samples in the training set" + assert display.ax_.get_ylabel() == "Score" + + _, legend_labels = display.ax_.get_legend_handles_labels() + assert legend_labels == ["Train", "Test"] + + train_sizes_abs, train_scores, test_scores = learning_curve( + estimator, X, y, train_sizes=train_sizes + ) + + assert_array_equal(display.train_sizes, train_sizes_abs) + assert_allclose(display.train_scores, train_scores) + assert_allclose(display.test_scores, test_scores) + + +def test_validation_curve_display_default_usage(pyplot, data): + """Check the default usage of the ValidationCurveDisplay class.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + param_name, param_range = "max_depth", [1, 3, 5] + display = ValidationCurveDisplay.from_estimator( + estimator, X, y, param_name=param_name, param_range=param_range + ) + + import matplotlib as mpl + + assert display.errorbar_ is None + + assert isinstance(display.lines_, list) + for line in display.lines_: + assert isinstance(line, mpl.lines.Line2D) + + assert isinstance(display.fill_between_, list) + for fill in display.fill_between_: + assert isinstance(fill, mpl.collections.PolyCollection) + assert fill.get_alpha() == 0.5 + + assert display.score_name == "Score" + assert display.ax_.get_xlabel() == f"{param_name}" + assert display.ax_.get_ylabel() == "Score" + + _, legend_labels = display.ax_.get_legend_handles_labels() + assert legend_labels == ["Train", "Test"] + + train_scores, test_scores = validation_curve( + estimator, X, y, param_name=param_name, param_range=param_range + ) + + assert_array_equal(display.param_range, param_range) + assert_allclose(display.train_scores, train_scores) + assert_allclose(display.test_scores, test_scores) + + +@pytest.mark.parametrize( + "CurveDisplay, specific_params", + [ + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + (LearningCurveDisplay, {"train_sizes": [0.3, 0.6, 0.9]}), + ], +) +def test_curve_display_negate_score(pyplot, data, CurveDisplay, specific_params): + """Check the behaviour of the `negate_score` parameter calling `from_estimator` and + `plot`. + """ + X, y = data + estimator = DecisionTreeClassifier(max_depth=1, random_state=0) + + negate_score = False + display = CurveDisplay.from_estimator( + estimator, X, y, **specific_params, negate_score=negate_score + ) + + positive_scores = display.lines_[0].get_data()[1] + assert (positive_scores >= 0).all() + assert display.ax_.get_ylabel() == "Score" + + negate_score = True + display = CurveDisplay.from_estimator( + estimator, X, y, **specific_params, negate_score=negate_score + ) + + negative_scores = display.lines_[0].get_data()[1] + assert (negative_scores <= 0).all() + assert_allclose(negative_scores, -positive_scores) + assert display.ax_.get_ylabel() == "Negative score" + + negate_score = False + display = CurveDisplay.from_estimator( + estimator, X, y, **specific_params, negate_score=negate_score + ) + assert display.ax_.get_ylabel() == "Score" + display.plot(negate_score=not negate_score) + assert display.ax_.get_ylabel() == "Score" + assert (display.lines_[0].get_data()[1] < 0).all() + + +@pytest.mark.parametrize( + "score_name, ylabel", [(None, "Score"), ("Accuracy", "Accuracy")] +) +@pytest.mark.parametrize( + "CurveDisplay, specific_params", + [ + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + (LearningCurveDisplay, {"train_sizes": [0.3, 0.6, 0.9]}), + ], +) +def test_curve_display_score_name( + pyplot, data, score_name, ylabel, CurveDisplay, specific_params +): + """Check that we can overwrite the default score name shown on the y-axis.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + display = CurveDisplay.from_estimator( + estimator, X, y, **specific_params, score_name=score_name + ) + + assert display.ax_.get_ylabel() == ylabel + X, y = data + estimator = DecisionTreeClassifier(max_depth=1, random_state=0) + + display = CurveDisplay.from_estimator( + estimator, X, y, **specific_params, score_name=score_name + ) + + assert display.score_name == ylabel + + +@pytest.mark.parametrize("std_display_style", (None, "errorbar")) +def test_learning_curve_display_score_type(pyplot, data, std_display_style): + """Check the behaviour of setting the `score_type` parameter.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + train_sizes = [0.3, 0.6, 0.9] + train_sizes_abs, train_scores, test_scores = learning_curve( + estimator, X, y, train_sizes=train_sizes + ) + + score_type = "train" + display = LearningCurveDisplay.from_estimator( + estimator, + X, + y, + train_sizes=train_sizes, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Train"] + + if std_display_style is None: + assert len(display.lines_) == 1 + assert display.errorbar_ is None + x_data, y_data = display.lines_[0].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 1 + x_data, y_data = display.errorbar_[0].lines[0].get_data() + + assert_array_equal(x_data, train_sizes_abs) + assert_allclose(y_data, train_scores.mean(axis=1)) + + score_type = "test" + display = LearningCurveDisplay.from_estimator( + estimator, + X, + y, + train_sizes=train_sizes, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Test"] + + if std_display_style is None: + assert len(display.lines_) == 1 + assert display.errorbar_ is None + x_data, y_data = display.lines_[0].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 1 + x_data, y_data = display.errorbar_[0].lines[0].get_data() + + assert_array_equal(x_data, train_sizes_abs) + assert_allclose(y_data, test_scores.mean(axis=1)) + + score_type = "both" + display = LearningCurveDisplay.from_estimator( + estimator, + X, + y, + train_sizes=train_sizes, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Train", "Test"] + + if std_display_style is None: + assert len(display.lines_) == 2 + assert display.errorbar_ is None + x_data_train, y_data_train = display.lines_[0].get_data() + x_data_test, y_data_test = display.lines_[1].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 2 + x_data_train, y_data_train = display.errorbar_[0].lines[0].get_data() + x_data_test, y_data_test = display.errorbar_[1].lines[0].get_data() + + assert_array_equal(x_data_train, train_sizes_abs) + assert_allclose(y_data_train, train_scores.mean(axis=1)) + assert_array_equal(x_data_test, train_sizes_abs) + assert_allclose(y_data_test, test_scores.mean(axis=1)) + + +@pytest.mark.parametrize("std_display_style", (None, "errorbar")) +def test_validation_curve_display_score_type(pyplot, data, std_display_style): + """Check the behaviour of setting the `score_type` parameter.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + param_name, param_range = "max_depth", [1, 3, 5] + train_scores, test_scores = validation_curve( + estimator, X, y, param_name=param_name, param_range=param_range + ) + + score_type = "train" + display = ValidationCurveDisplay.from_estimator( + estimator, + X, + y, + param_name=param_name, + param_range=param_range, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Train"] + + if std_display_style is None: + assert len(display.lines_) == 1 + assert display.errorbar_ is None + x_data, y_data = display.lines_[0].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 1 + x_data, y_data = display.errorbar_[0].lines[0].get_data() + + assert_array_equal(x_data, param_range) + assert_allclose(y_data, train_scores.mean(axis=1)) + + score_type = "test" + display = ValidationCurveDisplay.from_estimator( + estimator, + X, + y, + param_name=param_name, + param_range=param_range, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Test"] + + if std_display_style is None: + assert len(display.lines_) == 1 + assert display.errorbar_ is None + x_data, y_data = display.lines_[0].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 1 + x_data, y_data = display.errorbar_[0].lines[0].get_data() + + assert_array_equal(x_data, param_range) + assert_allclose(y_data, test_scores.mean(axis=1)) + + score_type = "both" + display = ValidationCurveDisplay.from_estimator( + estimator, + X, + y, + param_name=param_name, + param_range=param_range, + score_type=score_type, + std_display_style=std_display_style, + ) + + _, legend_label = display.ax_.get_legend_handles_labels() + assert legend_label == ["Train", "Test"] + + if std_display_style is None: + assert len(display.lines_) == 2 + assert display.errorbar_ is None + x_data_train, y_data_train = display.lines_[0].get_data() + x_data_test, y_data_test = display.lines_[1].get_data() + else: + assert display.lines_ is None + assert len(display.errorbar_) == 2 + x_data_train, y_data_train = display.errorbar_[0].lines[0].get_data() + x_data_test, y_data_test = display.errorbar_[1].lines[0].get_data() + + assert_array_equal(x_data_train, param_range) + assert_allclose(y_data_train, train_scores.mean(axis=1)) + assert_array_equal(x_data_test, param_range) + assert_allclose(y_data_test, test_scores.mean(axis=1)) + + +@pytest.mark.parametrize( + "CurveDisplay, specific_params, expected_xscale", + [ + ( + ValidationCurveDisplay, + {"param_name": "max_depth", "param_range": np.arange(1, 5)}, + "linear", + ), + (LearningCurveDisplay, {"train_sizes": np.linspace(0.1, 0.9, num=5)}, "linear"), + ( + ValidationCurveDisplay, + { + "param_name": "max_depth", + "param_range": np.round(np.logspace(0, 2, num=5)).astype(np.int64), + }, + "log", + ), + (LearningCurveDisplay, {"train_sizes": np.logspace(-1, 0, num=5)}, "log"), + ], +) +def test_curve_display_xscale_auto( + pyplot, data, CurveDisplay, specific_params, expected_xscale +): + """Check the behaviour of the x-axis scaling depending on the data provided.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + display = CurveDisplay.from_estimator(estimator, X, y, **specific_params) + assert display.ax_.get_xscale() == expected_xscale + + +@pytest.mark.parametrize( + "CurveDisplay, specific_params", + [ + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + (LearningCurveDisplay, {"train_sizes": [0.3, 0.6, 0.9]}), + ], +) +def test_curve_display_std_display_style(pyplot, data, CurveDisplay, specific_params): + """Check the behaviour of the parameter `std_display_style`.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + import matplotlib as mpl + + std_display_style = None + display = CurveDisplay.from_estimator( + estimator, + X, + y, + **specific_params, + std_display_style=std_display_style, + ) + + assert len(display.lines_) == 2 + for line in display.lines_: + assert isinstance(line, mpl.lines.Line2D) + assert display.errorbar_ is None + assert display.fill_between_ is None + _, legend_label = display.ax_.get_legend_handles_labels() + assert len(legend_label) == 2 + + std_display_style = "fill_between" + display = CurveDisplay.from_estimator( + estimator, + X, + y, + **specific_params, + std_display_style=std_display_style, + ) + + assert len(display.lines_) == 2 + for line in display.lines_: + assert isinstance(line, mpl.lines.Line2D) + assert display.errorbar_ is None + assert len(display.fill_between_) == 2 + for fill_between in display.fill_between_: + assert isinstance(fill_between, mpl.collections.PolyCollection) + _, legend_label = display.ax_.get_legend_handles_labels() + assert len(legend_label) == 2 + + std_display_style = "errorbar" + display = CurveDisplay.from_estimator( + estimator, + X, + y, + **specific_params, + std_display_style=std_display_style, + ) + + assert display.lines_ is None + assert len(display.errorbar_) == 2 + for errorbar in display.errorbar_: + assert isinstance(errorbar, mpl.container.ErrorbarContainer) + assert display.fill_between_ is None + _, legend_label = display.ax_.get_legend_handles_labels() + assert len(legend_label) == 2 + + +@pytest.mark.parametrize( + "CurveDisplay, specific_params", + [ + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + (LearningCurveDisplay, {"train_sizes": [0.3, 0.6, 0.9]}), + ], +) +def test_curve_display_plot_kwargs(pyplot, data, CurveDisplay, specific_params): + """Check the behaviour of the different plotting keyword arguments: `line_kw`, + `fill_between_kw`, and `errorbar_kw`.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + std_display_style = "fill_between" + line_kw = {"color": "red"} + fill_between_kw = {"color": "red", "alpha": 1.0} + display = CurveDisplay.from_estimator( + estimator, + X, + y, + **specific_params, + std_display_style=std_display_style, + line_kw=line_kw, + fill_between_kw=fill_between_kw, + ) + + assert display.lines_[0].get_color() == "red" + assert_allclose( + display.fill_between_[0].get_facecolor(), + [[1.0, 0.0, 0.0, 1.0]], # trust me, it's red + ) + + std_display_style = "errorbar" + errorbar_kw = {"color": "red"} + display = CurveDisplay.from_estimator( + estimator, + X, + y, + **specific_params, + std_display_style=std_display_style, + errorbar_kw=errorbar_kw, + ) + + assert display.errorbar_[0].lines[0].get_color() == "red" + + +@pytest.mark.parametrize( + "param_range, xscale", + [([5, 10, 15], "linear"), ([-50, 5, 50, 500], "symlog"), ([5, 50, 500], "log")], +) +def test_validation_curve_xscale_from_param_range_provided_as_a_list( + pyplot, data, param_range, xscale +): + """Check the induced xscale from the provided param_range values.""" + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + param_name = "max_depth" + display = ValidationCurveDisplay.from_estimator( + estimator, + X, + y, + param_name=param_name, + param_range=param_range, + ) + + assert display.ax_.get_xscale() == xscale + + +@pytest.mark.parametrize( + "Display, params", + [ + (LearningCurveDisplay, {}), + (ValidationCurveDisplay, {"param_name": "max_depth", "param_range": [1, 3, 5]}), + ], +) +def test_subclassing_displays(pyplot, data, Display, params): + """Check that named constructors return the correct type when subclassed. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/pull/27675 + """ + X, y = data + estimator = DecisionTreeClassifier(random_state=0) + + class SubclassOfDisplay(Display): + pass + + display = SubclassOfDisplay.from_estimator(estimator, X, y, **params) + assert isinstance(display, SubclassOfDisplay) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_search.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_search.py new file mode 100644 index 0000000000000000000000000000000000000000..7888dd2d1766b411549f29c995ac9bd58595158d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_search.py @@ -0,0 +1,2966 @@ +"""Test the search module""" + +import pickle +import re +import sys +import warnings +from collections.abc import Iterable, Sized +from functools import partial +from io import StringIO +from itertools import chain, product +from types import GeneratorType + +import numpy as np +import pytest +from scipy.stats import bernoulli, expon, uniform + +from sklearn import config_context +from sklearn.base import BaseEstimator, ClassifierMixin, clone, is_classifier +from sklearn.cluster import KMeans +from sklearn.compose import ColumnTransformer +from sklearn.datasets import ( + make_blobs, + make_classification, + make_multilabel_classification, +) +from sklearn.discriminant_analysis import LinearDiscriminantAnalysis +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import HistGradientBoostingClassifier +from sklearn.exceptions import FitFailedWarning +from sklearn.experimental import enable_halving_search_cv # noqa: F401 +from sklearn.feature_extraction.text import TfidfVectorizer +from sklearn.impute import SimpleImputer +from sklearn.linear_model import ( + LinearRegression, + LogisticRegression, + Ridge, + SGDClassifier, +) +from sklearn.metrics import ( + accuracy_score, + confusion_matrix, + f1_score, + make_scorer, + r2_score, + recall_score, + roc_auc_score, +) +from sklearn.metrics.pairwise import euclidean_distances +from sklearn.model_selection import ( + GridSearchCV, + GroupKFold, + GroupShuffleSplit, + HalvingGridSearchCV, + KFold, + LeaveOneGroupOut, + LeavePGroupsOut, + ParameterGrid, + ParameterSampler, + RandomizedSearchCV, + StratifiedKFold, + StratifiedShuffleSplit, + train_test_split, +) +from sklearn.model_selection._search import ( + BaseSearchCV, + _yield_masked_array_for_each_param, +) +from sklearn.model_selection.tests.common import OneTimeSplitter +from sklearn.naive_bayes import ComplementNB +from sklearn.neighbors import KernelDensity, KNeighborsClassifier, LocalOutlierFactor +from sklearn.pipeline import Pipeline, make_pipeline +from sklearn.preprocessing import ( + OneHotEncoder, + OrdinalEncoder, + SplineTransformer, + StandardScaler, +) +from sklearn.svm import SVC, LinearSVC +from sklearn.tests.metadata_routing_common import ( + ConsumingScorer, + _Registry, + check_recorded_metadata, +) +from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor +from sklearn.utils._array_api import ( + _get_namespace_device_dtype_ids, + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._mocking import CheckingClassifier, MockDataFrame +from sklearn.utils._testing import ( + MinimalClassifier, + MinimalRegressor, + MinimalTransformer, + _array_api_for_tests, + assert_allclose, + assert_allclose_dense_sparse, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, + set_random_state, +) +from sklearn.utils.estimator_checks import _enforce_estimator_tags_y +from sklearn.utils.fixes import CSR_CONTAINERS +from sklearn.utils.validation import _num_samples + + +# Neither of the following two estimators inherit from BaseEstimator, +# to test hyperparameter search on user-defined classifiers. +class MockClassifier(ClassifierMixin, BaseEstimator): + """Dummy classifier to test the parameter search algorithms""" + + def __init__(self, foo_param=0): + self.foo_param = foo_param + + def fit(self, X, Y): + assert len(X) == len(Y) + self.classes_ = np.unique(Y) + return self + + def predict(self, T): + return T.shape[0] + + def transform(self, X): + return X + self.foo_param + + def inverse_transform(self, X): + return X - self.foo_param + + predict_proba = predict + predict_log_proba = predict + decision_function = predict + + def score(self, X=None, Y=None): + if self.foo_param > 1: + score = 1.0 + else: + score = 0.0 + return score + + def get_params(self, deep=False): + return {"foo_param": self.foo_param} + + def set_params(self, **params): + self.foo_param = params["foo_param"] + return self + + +class LinearSVCNoScore(LinearSVC): + """A LinearSVC classifier that has no score method.""" + + @property + def score(self): + raise AttributeError + + +X = np.array([[-1, -1], [-2, -1], [1, 1], [2, 1]]) +y = np.array([1, 1, 2, 2]) + + +def assert_grid_iter_equals_getitem(grid): + assert list(grid) == [grid[i] for i in range(len(grid))] + + +@pytest.mark.parametrize("klass", [ParameterGrid, partial(ParameterSampler, n_iter=10)]) +@pytest.mark.parametrize( + "input, error_type, error_message", + [ + (0, TypeError, r"Parameter .* a dict or a list, got: 0 of type int"), + ([{"foo": [0]}, 0], TypeError, r"Parameter .* is not a dict \(0\)"), + ( + {"foo": 0}, + TypeError, + r"Parameter (grid|distribution) for parameter 'foo' (is not|needs to be) " + r"(a list or a numpy array|iterable or a distribution).*", + ), + ], +) +def test_validate_parameter_input(klass, input, error_type, error_message): + with pytest.raises(error_type, match=error_message): + klass(input) + + +def test_parameter_grid(): + # Test basic properties of ParameterGrid. + params1 = {"foo": [1, 2, 3]} + grid1 = ParameterGrid(params1) + assert isinstance(grid1, Iterable) + assert isinstance(grid1, Sized) + assert len(grid1) == 3 + assert_grid_iter_equals_getitem(grid1) + + params2 = {"foo": [4, 2], "bar": ["ham", "spam", "eggs"]} + grid2 = ParameterGrid(params2) + assert len(grid2) == 6 + + # loop to assert we can iterate over the grid multiple times + for i in range(2): + # tuple + chain transforms {"a": 1, "b": 2} to ("a", 1, "b", 2) + points = set(tuple(chain(*(sorted(p.items())))) for p in grid2) + assert points == set( + ("bar", x, "foo", y) for x, y in product(params2["bar"], params2["foo"]) + ) + assert_grid_iter_equals_getitem(grid2) + + # Special case: empty grid (useful to get default estimator settings) + empty = ParameterGrid({}) + assert len(empty) == 1 + assert list(empty) == [{}] + assert_grid_iter_equals_getitem(empty) + with pytest.raises(IndexError): + empty[1] + + has_empty = ParameterGrid([{"C": [1, 10]}, {}, {"C": [0.5]}]) + assert len(has_empty) == 4 + assert list(has_empty) == [{"C": 1}, {"C": 10}, {}, {"C": 0.5}] + assert_grid_iter_equals_getitem(has_empty) + + +def test_grid_search(): + # Test that the best estimator contains the right value for foo_param + clf = MockClassifier() + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, cv=2, verbose=3) + # make sure it selects the smallest parameter in case of ties + old_stdout = sys.stdout + sys.stdout = StringIO() + grid_search.fit(X, y) + sys.stdout = old_stdout + assert grid_search.best_estimator_.foo_param == 2 + + assert_array_equal(grid_search.cv_results_["param_foo_param"].data, [1, 2, 3]) + + # Smoke test the score etc: + grid_search.score(X, y) + grid_search.predict_proba(X) + grid_search.decision_function(X) + grid_search.transform(X) + + # Test exception handling on scoring + grid_search.scoring = "sklearn" + with pytest.raises(ValueError): + grid_search.fit(X, y) + + +def test_grid_search_pipeline_steps(): + # check that parameters that are estimators are cloned before fitting + pipe = Pipeline([("regressor", LinearRegression())]) + param_grid = {"regressor": [LinearRegression(), Ridge()]} + grid_search = GridSearchCV(pipe, param_grid, cv=2) + grid_search.fit(X, y) + regressor_results = grid_search.cv_results_["param_regressor"] + assert isinstance(regressor_results[0], LinearRegression) + assert isinstance(regressor_results[1], Ridge) + assert not hasattr(regressor_results[0], "coef_") + assert not hasattr(regressor_results[1], "coef_") + assert regressor_results[0] is not grid_search.best_estimator_ + assert regressor_results[1] is not grid_search.best_estimator_ + # check that we didn't modify the parameter grid that was passed + assert not hasattr(param_grid["regressor"][0], "coef_") + assert not hasattr(param_grid["regressor"][1], "coef_") + + +@pytest.mark.parametrize("SearchCV", [GridSearchCV, RandomizedSearchCV]) +def test_SearchCV_with_fit_params(SearchCV): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_fit_params=["spam", "eggs"]) + searcher = SearchCV(clf, {"foo_param": [1, 2, 3]}, cv=2, error_score="raise") + + # The CheckingClassifier generates an assertion error if + # a parameter is missing or has length != len(X). + err_msg = r"Expected fit parameter\(s\) \['eggs'\] not seen." + with pytest.raises(AssertionError, match=err_msg): + searcher.fit(X, y, spam=np.ones(10)) + + err_msg = "Fit parameter spam has length 1; expected" + with pytest.raises(AssertionError, match=err_msg): + searcher.fit(X, y, spam=np.ones(1), eggs=np.zeros(10)) + searcher.fit(X, y, spam=np.ones(10), eggs=np.zeros(10)) + + +def test_grid_search_no_score(): + # Test grid-search on classifier that has no score function. + clf = LinearSVC(random_state=0) + X, y = make_blobs(random_state=0, centers=2) + Cs = [0.1, 1, 10] + clf_no_score = LinearSVCNoScore(random_state=0) + grid_search = GridSearchCV(clf, {"C": Cs}, scoring="accuracy") + grid_search.fit(X, y) + + grid_search_no_score = GridSearchCV(clf_no_score, {"C": Cs}, scoring="accuracy") + # smoketest grid search + grid_search_no_score.fit(X, y) + + # check that best params are equal + assert grid_search_no_score.best_params_ == grid_search.best_params_ + # check that we can call score and that it gives the correct result + assert grid_search.score(X, y) == grid_search_no_score.score(X, y) + + # giving no scoring function raises an error + grid_search_no_score = GridSearchCV(clf_no_score, {"C": Cs}) + with pytest.raises(TypeError, match="no scoring"): + grid_search_no_score.fit([[1]]) + + +def test_grid_search_score_method(): + X, y = make_classification(n_samples=100, n_classes=2, flip_y=0.2, random_state=0) + clf = LinearSVC(random_state=0) + grid = {"C": [0.1]} + + search_no_scoring = GridSearchCV(clf, grid, scoring=None).fit(X, y) + search_accuracy = GridSearchCV(clf, grid, scoring="accuracy").fit(X, y) + search_no_score_method_auc = GridSearchCV( + LinearSVCNoScore(), grid, scoring="roc_auc" + ).fit(X, y) + search_auc = GridSearchCV(clf, grid, scoring="roc_auc").fit(X, y) + + # Check warning only occurs in situation where behavior changed: + # estimator requires score method to compete with scoring parameter + score_no_scoring = search_no_scoring.score(X, y) + score_accuracy = search_accuracy.score(X, y) + score_no_score_auc = search_no_score_method_auc.score(X, y) + score_auc = search_auc.score(X, y) + + # ensure the test is sane + assert score_auc < 1.0 + assert score_accuracy < 1.0 + assert score_auc != score_accuracy + + assert_almost_equal(score_accuracy, score_no_scoring) + assert_almost_equal(score_auc, score_no_score_auc) + + +def test_grid_search_groups(): + # Check if ValueError (when groups is None) propagates to GridSearchCV + # And also check if groups is correctly passed to the cv object + rng = np.random.RandomState(0) + + X, y = make_classification(n_samples=15, n_classes=2, random_state=0) + groups = rng.randint(0, 3, 15) + + clf = LinearSVC(random_state=0) + grid = {"C": [1]} + + group_cvs = [ + LeaveOneGroupOut(), + LeavePGroupsOut(2), + GroupKFold(n_splits=3), + GroupShuffleSplit(), + ] + error_msg = "The 'groups' parameter should not be None." + for cv in group_cvs: + gs = GridSearchCV(clf, grid, cv=cv) + with pytest.raises(ValueError, match=error_msg): + gs.fit(X, y) + gs.fit(X, y, groups=groups) + + non_group_cvs = [StratifiedKFold(), StratifiedShuffleSplit()] + for cv in non_group_cvs: + gs = GridSearchCV(clf, grid, cv=cv) + # Should not raise an error + gs.fit(X, y) + + +def test_classes__property(): + # Test that classes_ property matches best_estimator_.classes_ + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + Cs = [0.1, 1, 10] + + grid_search = GridSearchCV(LinearSVC(random_state=0), {"C": Cs}) + grid_search.fit(X, y) + assert_array_equal(grid_search.best_estimator_.classes_, grid_search.classes_) + + # Test that regressors do not have a classes_ attribute + grid_search = GridSearchCV(Ridge(), {"alpha": [1.0, 2.0]}) + grid_search.fit(X, y) + assert not hasattr(grid_search, "classes_") + + # Test that the grid searcher has no classes_ attribute before it's fit + grid_search = GridSearchCV(LinearSVC(random_state=0), {"C": Cs}) + assert not hasattr(grid_search, "classes_") + + # Test that the grid searcher has no classes_ attribute without a refit + grid_search = GridSearchCV(LinearSVC(random_state=0), {"C": Cs}, refit=False) + grid_search.fit(X, y) + assert not hasattr(grid_search, "classes_") + + +def test_trivial_cv_results_attr(): + # Test search over a "grid" with only one point. + clf = MockClassifier() + grid_search = GridSearchCV(clf, {"foo_param": [1]}, cv=2) + grid_search.fit(X, y) + assert hasattr(grid_search, "cv_results_") + + random_search = RandomizedSearchCV(clf, {"foo_param": [0]}, n_iter=1, cv=2) + random_search.fit(X, y) + assert hasattr(grid_search, "cv_results_") + + +def test_no_refit(): + # Test that GSCV can be used for model selection alone without refitting + clf = MockClassifier() + for scoring in [None, ["accuracy", "precision"]]: + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, refit=False, cv=2) + grid_search.fit(X, y) + assert ( + not hasattr(grid_search, "best_estimator_") + and hasattr(grid_search, "best_index_") + and hasattr(grid_search, "best_params_") + ) + + # Make sure the functions predict/transform etc. raise meaningful + # error messages + for fn_name in ( + "predict", + "predict_proba", + "predict_log_proba", + "transform", + "inverse_transform", + ): + outer_msg = f"has no attribute '{fn_name}'" + inner_msg = ( + f"`refit=False`. {fn_name} is available only after " + "refitting on the best parameters" + ) + with pytest.raises(AttributeError, match=outer_msg) as exec_info: + getattr(grid_search, fn_name)(X) + + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg in str(exec_info.value.__cause__) + + # Test that an invalid refit param raises appropriate error messages + error_msg = ( + "For multi-metric scoring, the parameter refit must be set to a scorer key" + ) + for refit in [True, "recall", "accuracy"]: + with pytest.raises(ValueError, match=error_msg): + GridSearchCV( + clf, {}, refit=refit, scoring={"acc": "accuracy", "prec": "precision"} + ).fit(X, y) + + +def test_grid_search_error(): + # Test that grid search will capture errors on data with different length + X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) + + clf = LinearSVC() + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}) + with pytest.raises(ValueError): + cv.fit(X_[:180], y_) + + +def test_grid_search_one_grid_point(): + X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) + param_dict = {"C": [1.0], "kernel": ["rbf"], "gamma": [0.1]} + + clf = SVC(gamma="auto") + cv = GridSearchCV(clf, param_dict) + cv.fit(X_, y_) + + clf = SVC(C=1.0, kernel="rbf", gamma=0.1) + clf.fit(X_, y_) + + assert_array_equal(clf.dual_coef_, cv.best_estimator_.dual_coef_) + + +def test_grid_search_when_param_grid_includes_range(): + # Test that the best estimator contains the right value for foo_param + clf = MockClassifier() + grid_search = None + grid_search = GridSearchCV(clf, {"foo_param": range(1, 4)}, cv=2) + grid_search.fit(X, y) + assert grid_search.best_estimator_.foo_param == 2 + + +def test_grid_search_bad_param_grid(): + X, y = make_classification(n_samples=10, n_features=5, random_state=0) + param_dict = {"C": 1} + clf = SVC(gamma="auto") + error_msg = re.escape( + "Parameter grid for parameter 'C' needs to be a list or " + "a numpy array, but got 1 (of type int) instead. Single " + "values need to be wrapped in a list with one element." + ) + search = GridSearchCV(clf, param_dict) + with pytest.raises(TypeError, match=error_msg): + search.fit(X, y) + + param_dict = {"C": []} + clf = SVC() + error_msg = re.escape( + "Parameter grid for parameter 'C' need to be a non-empty sequence, got: []" + ) + search = GridSearchCV(clf, param_dict) + with pytest.raises(ValueError, match=error_msg): + search.fit(X, y) + + param_dict = {"C": "1,2,3"} + clf = SVC(gamma="auto") + error_msg = re.escape( + "Parameter grid for parameter 'C' needs to be a list or a numpy array, " + "but got '1,2,3' (of type str) instead. Single values need to be " + "wrapped in a list with one element." + ) + search = GridSearchCV(clf, param_dict) + with pytest.raises(TypeError, match=error_msg): + search.fit(X, y) + + param_dict = {"C": np.ones((3, 2))} + clf = SVC() + search = GridSearchCV(clf, param_dict) + with pytest.raises(ValueError): + search.fit(X, y) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_grid_search_sparse(csr_container): + # Test that grid search works with both dense and sparse matrices + X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) + + clf = LinearSVC() + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}) + cv.fit(X_[:180], y_[:180]) + y_pred = cv.predict(X_[180:]) + C = cv.best_estimator_.C + + X_ = csr_container(X_) + clf = LinearSVC() + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}) + cv.fit(X_[:180].tocoo(), y_[:180]) + y_pred2 = cv.predict(X_[180:]) + C2 = cv.best_estimator_.C + + assert np.mean(y_pred == y_pred2) >= 0.9 + assert C == C2 + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_grid_search_sparse_scoring(csr_container): + X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) + + clf = LinearSVC() + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}, scoring="f1") + cv.fit(X_[:180], y_[:180]) + y_pred = cv.predict(X_[180:]) + C = cv.best_estimator_.C + + X_ = csr_container(X_) + clf = LinearSVC() + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}, scoring="f1") + cv.fit(X_[:180], y_[:180]) + y_pred2 = cv.predict(X_[180:]) + C2 = cv.best_estimator_.C + + assert_array_equal(y_pred, y_pred2) + assert C == C2 + # Smoke test the score + # np.testing.assert_allclose(f1_score(cv.predict(X_[:180]), y[:180]), + # cv.score(X_[:180], y[:180])) + + # test loss where greater is worse + def f1_loss(y_true_, y_pred_): + return -f1_score(y_true_, y_pred_) + + F1Loss = make_scorer(f1_loss, greater_is_better=False) + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}, scoring=F1Loss) + cv.fit(X_[:180], y_[:180]) + y_pred3 = cv.predict(X_[180:]) + C3 = cv.best_estimator_.C + + assert C == C3 + assert_array_equal(y_pred, y_pred3) + + +def test_grid_search_precomputed_kernel(): + # Test that grid search works when the input features are given in the + # form of a precomputed kernel matrix + X_, y_ = make_classification(n_samples=200, n_features=100, random_state=0) + + # compute the training kernel matrix corresponding to the linear kernel + K_train = np.dot(X_[:180], X_[:180].T) + y_train = y_[:180] + + clf = SVC(kernel="precomputed") + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}) + cv.fit(K_train, y_train) + + assert cv.best_score_ >= 0 + + # compute the test kernel matrix + K_test = np.dot(X_[180:], X_[:180].T) + y_test = y_[180:] + + y_pred = cv.predict(K_test) + + assert np.mean(y_pred == y_test) >= 0 + + # test error is raised when the precomputed kernel is not array-like + # or sparse + with pytest.raises(ValueError): + cv.fit(K_train.tolist(), y_train) + + +def test_grid_search_precomputed_kernel_error_nonsquare(): + # Test that grid search returns an error with a non-square precomputed + # training kernel matrix + K_train = np.zeros((10, 20)) + y_train = np.ones((10,)) + clf = SVC(kernel="precomputed") + cv = GridSearchCV(clf, {"C": [0.1, 1.0]}) + with pytest.raises(ValueError): + cv.fit(K_train, y_train) + + +class BrokenClassifier(BaseEstimator): + """Broken classifier that cannot be fit twice""" + + def __init__(self, parameter=None): + self.parameter = parameter + + def fit(self, X, y): + assert not hasattr(self, "has_been_fit_") + self.has_been_fit_ = True + + def predict(self, X): + return np.zeros(X.shape[0]) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.UndefinedMetricWarning") +def test_refit(): + # Regression test for bug in refitting + # Simulates re-fitting a broken estimator; this used to break with + # sparse SVMs. + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + clf = GridSearchCV( + BrokenClassifier(), [{"parameter": [0, 1]}], scoring="precision", refit=True + ) + clf.fit(X, y) + + +def test_refit_callable(): + """ + Test refit=callable, which adds flexibility in identifying the + "best" estimator. + """ + + def refit_callable(cv_results): + """ + A dummy function tests `refit=callable` interface. + Return the index of a model that has the least + `mean_test_score`. + """ + # Fit a dummy clf with `refit=True` to get a list of keys in + # clf.cv_results_. + X, y = make_classification(n_samples=100, n_features=4, random_state=42) + clf = GridSearchCV( + LinearSVC(random_state=42), + {"C": [0.01, 0.1, 1]}, + scoring="precision", + refit=True, + ) + clf.fit(X, y) + # Ensure that `best_index_ != 0` for this dummy clf + assert clf.best_index_ != 0 + + # Assert every key matches those in `cv_results` + for key in clf.cv_results_.keys(): + assert key in cv_results + + return cv_results["mean_test_score"].argmin() + + X, y = make_classification(n_samples=100, n_features=4, random_state=42) + clf = GridSearchCV( + LinearSVC(random_state=42), + {"C": [0.01, 0.1, 1]}, + scoring="precision", + refit=refit_callable, + ) + clf.fit(X, y) + + assert clf.best_index_ == 0 + # Ensure `best_score_` is disabled when using `refit=callable` + assert not hasattr(clf, "best_score_") + + +def test_refit_callable_invalid_type(): + """ + Test implementation catches the errors when 'best_index_' returns an + invalid result. + """ + + def refit_callable_invalid_type(cv_results): + """ + A dummy function tests when returned 'best_index_' is not integer. + """ + return None + + X, y = make_classification(n_samples=100, n_features=4, random_state=42) + + clf = GridSearchCV( + LinearSVC(random_state=42), + {"C": [0.1, 1]}, + scoring="precision", + refit=refit_callable_invalid_type, + ) + with pytest.raises(TypeError, match="best_index_ returned is not an integer"): + clf.fit(X, y) + + +@pytest.mark.parametrize("out_bound_value", [-1, 2]) +@pytest.mark.parametrize("search_cv", [RandomizedSearchCV, GridSearchCV]) +def test_refit_callable_out_bound(out_bound_value, search_cv): + """ + Test implementation catches the errors when 'best_index_' returns an + out of bound result. + """ + + def refit_callable_out_bound(cv_results): + """ + A dummy function tests when returned 'best_index_' is out of bounds. + """ + return out_bound_value + + X, y = make_classification(n_samples=100, n_features=4, random_state=42) + + clf = search_cv( + LinearSVC(random_state=42), + {"C": [0.1, 1]}, + scoring="precision", + refit=refit_callable_out_bound, + ) + with pytest.raises(IndexError, match="best_index_ index out of range"): + clf.fit(X, y) + + +def test_refit_callable_multi_metric(): + """ + Test refit=callable in multiple metric evaluation setting + """ + + def refit_callable(cv_results): + """ + A dummy function tests `refit=callable` interface. + Return the index of a model that has the least + `mean_test_prec`. + """ + assert "mean_test_prec" in cv_results + return cv_results["mean_test_prec"].argmin() + + X, y = make_classification(n_samples=100, n_features=4, random_state=42) + scoring = {"Accuracy": make_scorer(accuracy_score), "prec": "precision"} + clf = GridSearchCV( + LinearSVC(random_state=42), + {"C": [0.01, 0.1, 1]}, + scoring=scoring, + refit=refit_callable, + ) + clf.fit(X, y) + + assert clf.best_index_ == 0 + # Ensure `best_score_` is disabled when using `refit=callable` + assert not hasattr(clf, "best_score_") + + +def test_gridsearch_nd(): + # Pass X as list in GridSearchCV + X_4d = np.arange(10 * 5 * 3 * 2).reshape(10, 5, 3, 2) + y_3d = np.arange(10 * 7 * 11).reshape(10, 7, 11) + + def check_X(x): + return x.shape[1:] == (5, 3, 2) + + def check_y(x): + return x.shape[1:] == (7, 11) + + clf = CheckingClassifier( + check_X=check_X, + check_y=check_y, + methods_to_check=["fit"], + ) + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}) + grid_search.fit(X_4d, y_3d).score(X, y) + assert hasattr(grid_search, "cv_results_") + + +def test_X_as_list(): + # Pass X as list in GridSearchCV + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + clf = CheckingClassifier( + check_X=lambda x: isinstance(x, list), + methods_to_check=["fit"], + ) + cv = KFold(n_splits=3) + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, cv=cv) + grid_search.fit(X.tolist(), y).score(X, y) + assert hasattr(grid_search, "cv_results_") + + +def test_y_as_list(): + # Pass y as list in GridSearchCV + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + clf = CheckingClassifier( + check_y=lambda x: isinstance(x, list), + methods_to_check=["fit"], + ) + cv = KFold(n_splits=3) + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, cv=cv) + grid_search.fit(X, y.tolist()).score(X, y) + assert hasattr(grid_search, "cv_results_") + + +def test_pandas_input(): + # check cross_val_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import DataFrame, Series + + types.append((DataFrame, Series)) + except ImportError: + pass + + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + + for InputFeatureType, TargetType in types: + # X dataframe, y series + X_df, y_ser = InputFeatureType(X), TargetType(y) + + def check_df(x): + return isinstance(x, InputFeatureType) + + def check_series(x): + return isinstance(x, TargetType) + + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}) + grid_search.fit(X_df, y_ser).score(X_df, y_ser) + grid_search.predict(X_df) + assert hasattr(grid_search, "cv_results_") + + +def test_unsupervised_grid_search(): + # test grid-search with unsupervised estimator + X, y = make_blobs(n_samples=50, random_state=0) + km = KMeans(random_state=0, init="random", n_init=1) + + # Multi-metric evaluation unsupervised + scoring = ["adjusted_rand_score", "fowlkes_mallows_score"] + for refit in ["adjusted_rand_score", "fowlkes_mallows_score"]: + grid_search = GridSearchCV( + km, param_grid=dict(n_clusters=[2, 3, 4]), scoring=scoring, refit=refit + ) + grid_search.fit(X, y) + # Both ARI and FMS can find the right number :) + assert grid_search.best_params_["n_clusters"] == 3 + + # Single metric evaluation unsupervised + grid_search = GridSearchCV( + km, param_grid=dict(n_clusters=[2, 3, 4]), scoring="fowlkes_mallows_score" + ) + grid_search.fit(X, y) + assert grid_search.best_params_["n_clusters"] == 3 + + # Now without a score, and without y + grid_search = GridSearchCV(km, param_grid=dict(n_clusters=[2, 3, 4])) + grid_search.fit(X) + assert grid_search.best_params_["n_clusters"] == 4 + + +def test_gridsearch_no_predict(): + # test grid-search with an estimator without predict. + # slight duplication of a test from KDE + def custom_scoring(estimator, X): + return 42 if estimator.bandwidth == 0.1 else 0 + + X, _ = make_blobs(cluster_std=0.1, random_state=1, centers=[[0, 1], [1, 0], [0, 0]]) + search = GridSearchCV( + KernelDensity(), + param_grid=dict(bandwidth=[0.01, 0.1, 1]), + scoring=custom_scoring, + ) + search.fit(X) + assert search.best_params_["bandwidth"] == 0.1 + assert search.best_score_ == 42 + + +def test_param_sampler(): + # test basic properties of param sampler + param_distributions = {"kernel": ["rbf", "linear"], "C": uniform(0, 1)} + sampler = ParameterSampler( + param_distributions=param_distributions, n_iter=10, random_state=0 + ) + samples = [x for x in sampler] + assert len(samples) == 10 + for sample in samples: + assert sample["kernel"] in ["rbf", "linear"] + assert 0 <= sample["C"] <= 1 + + # test that repeated calls yield identical parameters + param_distributions = {"C": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]} + sampler = ParameterSampler( + param_distributions=param_distributions, n_iter=3, random_state=0 + ) + assert [x for x in sampler] == [x for x in sampler] + + param_distributions = {"C": uniform(0, 1)} + sampler = ParameterSampler( + param_distributions=param_distributions, n_iter=10, random_state=0 + ) + assert [x for x in sampler] == [x for x in sampler] + + +def check_cv_results_array_types( + search, param_keys, score_keys, expected_cv_results_kinds +): + # Check if the search `cv_results`'s array are of correct types + cv_results = search.cv_results_ + assert all(isinstance(cv_results[param], np.ma.MaskedArray) for param in param_keys) + assert { + key: cv_results[key].dtype.kind for key in param_keys + } == expected_cv_results_kinds + assert not any(isinstance(cv_results[key], np.ma.MaskedArray) for key in score_keys) + assert all( + cv_results[key].dtype == np.float64 + for key in score_keys + if not key.startswith("rank") + ) + + scorer_keys = search.scorer_.keys() if search.multimetric_ else ["score"] + + for key in scorer_keys: + assert cv_results["rank_test_%s" % key].dtype == np.int32 + + +def check_cv_results_keys(cv_results, param_keys, score_keys, n_cand, extra_keys=()): + # Test the search.cv_results_ contains all the required results + all_keys = param_keys + score_keys + extra_keys + assert_array_equal(sorted(cv_results.keys()), sorted(all_keys + ("params",))) + assert all(cv_results[key].shape == (n_cand,) for key in param_keys + score_keys) + + +def test_grid_search_cv_results(): + X, y = make_classification(n_samples=50, n_features=4, random_state=42) + + n_grid_points = 6 + params = [ + dict( + kernel=[ + "rbf", + ], + C=[1, 10], + gamma=[0.1, 1], + ), + dict( + kernel=[ + "poly", + ], + degree=[1, 2], + ), + ] + + param_keys = ("param_C", "param_degree", "param_gamma", "param_kernel") + score_keys = ( + "mean_test_score", + "mean_train_score", + "rank_test_score", + "split0_test_score", + "split1_test_score", + "split2_test_score", + "split0_train_score", + "split1_train_score", + "split2_train_score", + "std_test_score", + "std_train_score", + "mean_fit_time", + "std_fit_time", + "mean_score_time", + "std_score_time", + ) + n_candidates = n_grid_points + + search = GridSearchCV(SVC(), cv=3, param_grid=params, return_train_score=True) + search.fit(X, y) + cv_results = search.cv_results_ + # Check if score and timing are reasonable + assert all(cv_results["rank_test_score"] >= 1) + assert (all(cv_results[k] >= 0) for k in score_keys if k != "rank_test_score") + assert ( + all(cv_results[k] <= 1) + for k in score_keys + if "time" not in k and k != "rank_test_score" + ) + # Check cv_results structure + expected_cv_results_kinds = { + "param_C": "i", + "param_degree": "i", + "param_gamma": "f", + "param_kernel": "O", + } + check_cv_results_array_types( + search, param_keys, score_keys, expected_cv_results_kinds + ) + check_cv_results_keys(cv_results, param_keys, score_keys, n_candidates) + # Check masking + cv_results = search.cv_results_ + + poly_results = [ + ( + cv_results["param_C"].mask[i] + and cv_results["param_gamma"].mask[i] + and not cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "poly" + ] + assert all(poly_results) + assert len(poly_results) == 2 + + rbf_results = [ + ( + not cv_results["param_C"].mask[i] + and not cv_results["param_gamma"].mask[i] + and cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "rbf" + ] + assert all(rbf_results) + assert len(rbf_results) == 4 + + +def test_random_search_cv_results(): + X, y = make_classification(n_samples=50, n_features=4, random_state=42) + + n_search_iter = 30 + + params = [ + {"kernel": ["rbf"], "C": expon(scale=10), "gamma": expon(scale=0.1)}, + {"kernel": ["poly"], "degree": [2, 3]}, + ] + param_keys = ("param_C", "param_degree", "param_gamma", "param_kernel") + score_keys = ( + "mean_test_score", + "mean_train_score", + "rank_test_score", + "split0_test_score", + "split1_test_score", + "split2_test_score", + "split0_train_score", + "split1_train_score", + "split2_train_score", + "std_test_score", + "std_train_score", + "mean_fit_time", + "std_fit_time", + "mean_score_time", + "std_score_time", + ) + n_candidates = n_search_iter + + search = RandomizedSearchCV( + SVC(), + n_iter=n_search_iter, + cv=3, + param_distributions=params, + return_train_score=True, + ) + search.fit(X, y) + cv_results = search.cv_results_ + # Check results structure + expected_cv_results_kinds = { + "param_C": "f", + "param_degree": "i", + "param_gamma": "f", + "param_kernel": "O", + } + check_cv_results_array_types( + search, param_keys, score_keys, expected_cv_results_kinds + ) + check_cv_results_keys(cv_results, param_keys, score_keys, n_candidates) + assert all( + ( + cv_results["param_C"].mask[i] + and cv_results["param_gamma"].mask[i] + and not cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "poly" + ) + assert all( + ( + not cv_results["param_C"].mask[i] + and not cv_results["param_gamma"].mask[i] + and cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "rbf" + ) + + +@pytest.mark.parametrize( + "SearchCV, specialized_params", + [ + (GridSearchCV, {"param_grid": {"C": [1, 10]}}), + (RandomizedSearchCV, {"param_distributions": {"C": [1, 10]}, "n_iter": 2}), + ], +) +def test_search_default_iid(SearchCV, specialized_params): + # Test the IID parameter TODO: Clearly this test does something else??? + # noise-free simple 2d-data + X, y = make_blobs( + centers=[[0, 0], [1, 0], [0, 1], [1, 1]], + random_state=0, + cluster_std=0.1, + shuffle=False, + n_samples=80, + ) + # split dataset into two folds that are not iid + # first one contains data of all 4 blobs, second only from two. + mask = np.ones(X.shape[0], dtype=bool) + mask[np.where(y == 1)[0][::2]] = 0 + mask[np.where(y == 2)[0][::2]] = 0 + # this leads to perfect classification on one fold and a score of 1/3 on + # the other + # create "cv" for splits + cv = [[mask, ~mask], [~mask, mask]] + + common_params = {"estimator": SVC(), "cv": cv, "return_train_score": True} + search = SearchCV(**common_params, **specialized_params) + search.fit(X, y) + + test_cv_scores = np.array( + [ + search.cv_results_["split%d_test_score" % s][0] + for s in range(search.n_splits_) + ] + ) + test_mean = search.cv_results_["mean_test_score"][0] + test_std = search.cv_results_["std_test_score"][0] + + train_cv_scores = np.array( + [ + search.cv_results_["split%d_train_score" % s][0] + for s in range(search.n_splits_) + ] + ) + train_mean = search.cv_results_["mean_train_score"][0] + train_std = search.cv_results_["std_train_score"][0] + + assert search.cv_results_["param_C"][0] == 1 + # scores are the same as above + assert_allclose(test_cv_scores, [1, 1.0 / 3.0]) + assert_allclose(train_cv_scores, [1, 1]) + # Unweighted mean/std is used + assert test_mean == pytest.approx(np.mean(test_cv_scores)) + assert test_std == pytest.approx(np.std(test_cv_scores)) + + # For the train scores, we do not take a weighted mean irrespective of + # i.i.d. or not + assert train_mean == pytest.approx(1) + assert train_std == pytest.approx(0) + + +def test_grid_search_cv_results_multimetric(): + X, y = make_classification(n_samples=50, n_features=4, random_state=42) + + n_splits = 3 + params = [ + dict( + kernel=[ + "rbf", + ], + C=[1, 10], + gamma=[0.1, 1], + ), + dict( + kernel=[ + "poly", + ], + degree=[1, 2], + ), + ] + + grid_searches = [] + for scoring in ( + {"accuracy": make_scorer(accuracy_score), "recall": make_scorer(recall_score)}, + "accuracy", + "recall", + ): + grid_search = GridSearchCV( + SVC(), cv=n_splits, param_grid=params, scoring=scoring, refit=False + ) + grid_search.fit(X, y) + grid_searches.append(grid_search) + + compare_cv_results_multimetric_with_single(*grid_searches) + + +def test_random_search_cv_results_multimetric(): + X, y = make_classification(n_samples=50, n_features=4, random_state=42) + + n_splits = 3 + n_search_iter = 30 + + # Scipy 0.12's stats dists do not accept seed, hence we use param grid + params = dict(C=np.logspace(-4, 1, 3), gamma=np.logspace(-5, 0, 3, base=0.1)) + for refit in (True, False): + random_searches = [] + for scoring in (("accuracy", "recall"), "accuracy", "recall"): + # If True, for multi-metric pass refit='accuracy' + if refit: + probability = True + refit = "accuracy" if isinstance(scoring, tuple) else refit + else: + probability = False + clf = SVC(probability=probability, random_state=42) + random_search = RandomizedSearchCV( + clf, + n_iter=n_search_iter, + cv=n_splits, + param_distributions=params, + scoring=scoring, + refit=refit, + random_state=0, + ) + random_search.fit(X, y) + random_searches.append(random_search) + + compare_cv_results_multimetric_with_single(*random_searches) + compare_refit_methods_when_refit_with_acc( + random_searches[0], random_searches[1], refit + ) + + +def compare_cv_results_multimetric_with_single(search_multi, search_acc, search_rec): + """Compare multi-metric cv_results with the ensemble of multiple + single metric cv_results from single metric grid/random search""" + + assert search_multi.multimetric_ + assert_array_equal(sorted(search_multi.scorer_), ("accuracy", "recall")) + + cv_results_multi = search_multi.cv_results_ + cv_results_acc_rec = { + re.sub("_score$", "_accuracy", k): v for k, v in search_acc.cv_results_.items() + } + cv_results_acc_rec.update( + {re.sub("_score$", "_recall", k): v for k, v in search_rec.cv_results_.items()} + ) + + # Check if score and timing are reasonable, also checks if the keys + # are present + assert all( + ( + np.all(cv_results_multi[k] <= 1) + for k in ( + "mean_score_time", + "std_score_time", + "mean_fit_time", + "std_fit_time", + ) + ) + ) + + # Compare the keys, other than time keys, among multi-metric and + # single metric grid search results. np.testing.assert_equal performs a + # deep nested comparison of the two cv_results dicts + np.testing.assert_equal( + {k: v for k, v in cv_results_multi.items() if not k.endswith("_time")}, + {k: v for k, v in cv_results_acc_rec.items() if not k.endswith("_time")}, + ) + + +def compare_refit_methods_when_refit_with_acc(search_multi, search_acc, refit): + """Compare refit multi-metric search methods with single metric methods""" + assert search_acc.refit == refit + if refit: + assert search_multi.refit == "accuracy" + else: + assert not search_multi.refit + return # search cannot predict/score without refit + + X, y = make_blobs(n_samples=100, n_features=4, random_state=42) + for method in ("predict", "predict_proba", "predict_log_proba"): + assert_almost_equal( + getattr(search_multi, method)(X), getattr(search_acc, method)(X) + ) + assert_almost_equal(search_multi.score(X, y), search_acc.score(X, y)) + for key in ("best_index_", "best_score_", "best_params_"): + assert getattr(search_multi, key) == getattr(search_acc, key) + + +@pytest.mark.parametrize( + "search_cv", + [ + RandomizedSearchCV( + estimator=DecisionTreeClassifier(), + param_distributions={"max_depth": [5, 10]}, + ), + GridSearchCV( + estimator=DecisionTreeClassifier(), param_grid={"max_depth": [5, 10]} + ), + ], +) +def test_search_cv_score_samples_error(search_cv): + X, y = make_blobs(n_samples=100, n_features=4, random_state=42) + search_cv.fit(X, y) + + # Make sure to error out when underlying estimator does not implement + # the method `score_samples` + outer_msg = f"'{search_cv.__class__.__name__}' has no attribute 'score_samples'" + inner_msg = "'DecisionTreeClassifier' object has no attribute 'score_samples'" + + with pytest.raises(AttributeError, match=outer_msg) as exec_info: + search_cv.score_samples(X) + assert isinstance(exec_info.value.__cause__, AttributeError) + assert inner_msg == str(exec_info.value.__cause__) + + +def test_unsupported_sample_weight_scorer(): + """Checks that fitting with sample_weight raises a warning if the scorer does not + support sample_weight""" + + def fake_score_func(y_true, y_pred): + "Fake scoring function that does not support sample_weight" + return 0.5 + + fake_scorer = make_scorer(fake_score_func) + + X, y = make_classification(n_samples=10, n_features=4, random_state=42) + sw = np.ones_like(y) + search_cv = GridSearchCV(estimator=LogisticRegression(), param_grid={"C": [1, 10]}) + # function + search_cv.set_params(scoring=fake_score_func) + with pytest.warns(UserWarning, match="does not support sample_weight"): + search_cv.fit(X, y, sample_weight=sw) + # scorer + search_cv.set_params(scoring=fake_scorer) + with pytest.warns(UserWarning, match="does not support sample_weight"): + search_cv.fit(X, y, sample_weight=sw) + # multi-metric evaluation + search_cv.set_params( + scoring=dict(fake=fake_scorer, accuracy="accuracy"), refit=False + ) + # only fake scorer does not support sample_weight + with pytest.warns( + UserWarning, match=r"The scoring fake=.* does not support sample_weight" + ): + search_cv.fit(X, y, sample_weight=sw) + + +@pytest.mark.parametrize( + "estimator", + [ + GridSearchCV(estimator=LogisticRegression(), param_grid={"C": [1, 10, 100]}), + RandomizedSearchCV( + estimator=Ridge(), param_distributions={"alpha": [1, 0.1, 0.01]} + ), + ], +) +def test_search_cv_sample_weight_equivalence(estimator): + estimator_weighted = clone(estimator) + estimator_repeated = clone(estimator) + set_random_state(estimator_weighted, random_state=0) + set_random_state(estimator_repeated, random_state=0) + + rng = np.random.RandomState(42) + n_classes = 3 + n_samples_per_group = 30 + n_groups = 4 + n_samples = n_groups * n_samples_per_group + X = rng.rand(n_samples, n_samples * 2) + y = rng.randint(0, n_classes, size=n_samples) + sw = rng.randint(0, 5, size=n_samples) + # we use groups with LeaveOneGroupOut to ensure that + # the splits are the same in the repeated/weighted datasets + groups = np.tile(np.arange(n_groups), n_samples_per_group) + + X_weighted = X + y_weighted = y + groups_weighted = groups + splits_weighted = list(LeaveOneGroupOut().split(X_weighted, groups=groups_weighted)) + estimator_weighted.set_params(cv=splits_weighted) + # repeat samples according to weights + X_repeated = X_weighted.repeat(repeats=sw, axis=0) + y_repeated = y_weighted.repeat(repeats=sw) + groups_repeated = groups_weighted.repeat(repeats=sw) + splits_repeated = list(LeaveOneGroupOut().split(X_repeated, groups=groups_repeated)) + estimator_repeated.set_params(cv=splits_repeated) + + y_weighted = _enforce_estimator_tags_y(estimator_weighted, y_weighted) + y_repeated = _enforce_estimator_tags_y(estimator_repeated, y_repeated) + + estimator_repeated.fit(X_repeated, y=y_repeated, sample_weight=None) + estimator_weighted.fit(X_weighted, y=y_weighted, sample_weight=sw) + + # check that scores stored in cv_results_ + # are equal for the weighted/repeated datasets + score_keys = [ + key for key in estimator_repeated.cv_results_ if key.endswith("score") + ] + for key in score_keys: + s1 = estimator_repeated.cv_results_[key] + s2 = estimator_weighted.cv_results_[key] + err_msg = f"{key} values are not equal for weighted/repeated datasets" + assert_allclose(s1, s2, err_msg=err_msg) + + for key in ["best_score_", "best_index_"]: + s1 = getattr(estimator_repeated, key) + s2 = getattr(estimator_weighted, key) + err_msg = f"{key} values are not equal for weighted/repeated datasets" + assert_almost_equal(s1, s2, err_msg=err_msg) + + for method in ["predict_proba", "decision_function", "predict", "transform"]: + if hasattr(estimator, method): + s1 = getattr(estimator_repeated, method)(X) + s2 = getattr(estimator_weighted, method)(X) + err_msg = ( + f"Comparing the output of {method} revealed that fitting " + "with `sample_weight` is not equivalent to fitting with removed " + "or repeated data points." + ) + assert_allclose_dense_sparse(s1, s2, err_msg=err_msg) + + +@pytest.mark.parametrize( + "search_cv", + [ + RandomizedSearchCV( + estimator=LocalOutlierFactor(novelty=True), + param_distributions={"n_neighbors": [5, 10]}, + scoring="precision", + ), + GridSearchCV( + estimator=LocalOutlierFactor(novelty=True), + param_grid={"n_neighbors": [5, 10]}, + scoring="precision", + ), + ], +) +def test_search_cv_score_samples_method(search_cv): + # Set parameters + rng = np.random.RandomState(42) + n_samples = 300 + outliers_fraction = 0.15 + n_outliers = int(outliers_fraction * n_samples) + n_inliers = n_samples - n_outliers + + # Create dataset + X = make_blobs( + n_samples=n_inliers, + n_features=2, + centers=[[0, 0], [0, 0]], + cluster_std=0.5, + random_state=0, + )[0] + # Add some noisy points + X = np.concatenate([X, rng.uniform(low=-6, high=6, size=(n_outliers, 2))], axis=0) + + # Define labels to be able to score the estimator with `search_cv` + y_true = np.array([1] * n_samples) + y_true[-n_outliers:] = -1 + + # Fit on data + search_cv.fit(X, y_true) + + # Verify that the stand alone estimator yields the same results + # as the ones obtained with *SearchCV + assert_allclose( + search_cv.score_samples(X), search_cv.best_estimator_.score_samples(X) + ) + + +def test_search_cv_results_rank_tie_breaking(): + X, y = make_blobs(n_samples=50, random_state=42) + + # The two C values are close enough to give similar models + # which would result in a tie of their mean cv-scores + param_grid = {"C": [1, 1.001, 0.001]} + + grid_search = GridSearchCV(SVC(), param_grid=param_grid, return_train_score=True) + random_search = RandomizedSearchCV( + SVC(), n_iter=3, param_distributions=param_grid, return_train_score=True + ) + + for search in (grid_search, random_search): + search.fit(X, y) + cv_results = search.cv_results_ + # Check tie breaking strategy - + # Check that there is a tie in the mean scores between + # candidates 1 and 2 alone + assert_almost_equal( + cv_results["mean_test_score"][0], cv_results["mean_test_score"][1] + ) + assert_almost_equal( + cv_results["mean_train_score"][0], cv_results["mean_train_score"][1] + ) + assert not np.allclose( + cv_results["mean_test_score"][1], cv_results["mean_test_score"][2] + ) + assert not np.allclose( + cv_results["mean_train_score"][1], cv_results["mean_train_score"][2] + ) + # 'min' rank should be assigned to the tied candidates + assert_almost_equal(search.cv_results_["rank_test_score"], [1, 1, 3]) + + +def test_search_cv_results_none_param(): + X, y = [[1], [2], [3], [4], [5]], [0, 0, 0, 0, 1] + estimators = (DecisionTreeRegressor(), DecisionTreeClassifier()) + est_parameters = {"random_state": [0, None]} + cv = KFold() + + for est in estimators: + grid_search = GridSearchCV( + est, + est_parameters, + cv=cv, + ).fit(X, y) + assert_array_equal(grid_search.cv_results_["param_random_state"], [0, None]) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.FitFailedWarning") +def test_search_cv_timing(): + svc = LinearSVC(random_state=0) + + X = [ + [ + 1, + ], + [ + 2, + ], + [ + 3, + ], + [ + 4, + ], + ] + y = [0, 1, 1, 0] + + gs = GridSearchCV(svc, {"C": [0, 1]}, cv=2, error_score=0) + rs = RandomizedSearchCV(svc, {"C": [0, 1]}, cv=2, error_score=0, n_iter=2) + + for search in (gs, rs): + search.fit(X, y) + for key in ["mean_fit_time", "std_fit_time"]: + # NOTE The precision of time.time in windows is not high + # enough for the fit/score times to be non-zero for trivial X and y + assert np.all(search.cv_results_[key] >= 0) + assert np.all(search.cv_results_[key] < 1) + + for key in ["mean_score_time", "std_score_time"]: + assert search.cv_results_[key][1] >= 0 + assert search.cv_results_[key][0] == 0.0 + assert np.all(search.cv_results_[key] < 1) + + assert hasattr(search, "refit_time_") + assert isinstance(search.refit_time_, float) + assert search.refit_time_ >= 0 + + +def test_grid_search_correct_score_results(): + # test that correct scores are used + n_splits = 3 + clf = LinearSVC(random_state=0) + X, y = make_blobs(random_state=0, centers=2) + Cs = [0.1, 1, 10] + for score in ["f1", "roc_auc"]: + grid_search = GridSearchCV(clf, {"C": Cs}, scoring=score, cv=n_splits) + cv_results = grid_search.fit(X, y).cv_results_ + + # Test scorer names + result_keys = list(cv_results.keys()) + expected_keys = ("mean_test_score", "rank_test_score") + tuple( + "split%d_test_score" % cv_i for cv_i in range(n_splits) + ) + assert all(np.isin(expected_keys, result_keys)) + + cv = StratifiedKFold(n_splits=n_splits) + n_splits = grid_search.n_splits_ + for candidate_i, C in enumerate(Cs): + clf.set_params(C=C) + cv_scores = np.array( + [ + grid_search.cv_results_["split%d_test_score" % s][candidate_i] + for s in range(n_splits) + ] + ) + for i, (train, test) in enumerate(cv.split(X, y)): + clf.fit(X[train], y[train]) + if score == "f1": + correct_score = f1_score(y[test], clf.predict(X[test])) + elif score == "roc_auc": + dec = clf.decision_function(X[test]) + correct_score = roc_auc_score(y[test], dec) + assert_almost_equal(correct_score, cv_scores[i]) + + +def test_pickle(): + # Test that a fit search can be pickled + clf = MockClassifier() + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, refit=True, cv=2) + grid_search.fit(X, y) + grid_search_pickled = pickle.loads(pickle.dumps(grid_search)) + assert_array_almost_equal(grid_search.predict(X), grid_search_pickled.predict(X)) + + random_search = RandomizedSearchCV( + clf, {"foo_param": [1, 2, 3]}, refit=True, n_iter=3, cv=2 + ) + random_search.fit(X, y) + random_search_pickled = pickle.loads(pickle.dumps(random_search)) + assert_array_almost_equal( + random_search.predict(X), random_search_pickled.predict(X) + ) + + +def test_grid_search_with_multioutput_data(): + # Test search with multi-output estimator + + X, y = make_multilabel_classification(return_indicator=True, random_state=0) + + est_parameters = {"max_depth": [1, 2, 3, 4]} + cv = KFold() + + estimators = [ + DecisionTreeRegressor(random_state=0), + DecisionTreeClassifier(random_state=0), + ] + + # Test with grid search cv + for est in estimators: + grid_search = GridSearchCV(est, est_parameters, cv=cv) + grid_search.fit(X, y) + res_params = grid_search.cv_results_["params"] + for cand_i in range(len(res_params)): + est.set_params(**res_params[cand_i]) + + for i, (train, test) in enumerate(cv.split(X, y)): + est.fit(X[train], y[train]) + correct_score = est.score(X[test], y[test]) + assert_almost_equal( + correct_score, + grid_search.cv_results_["split%d_test_score" % i][cand_i], + ) + + # Test with a randomized search + for est in estimators: + random_search = RandomizedSearchCV(est, est_parameters, cv=cv, n_iter=3) + random_search.fit(X, y) + res_params = random_search.cv_results_["params"] + for cand_i in range(len(res_params)): + est.set_params(**res_params[cand_i]) + + for i, (train, test) in enumerate(cv.split(X, y)): + est.fit(X[train], y[train]) + correct_score = est.score(X[test], y[test]) + assert_almost_equal( + correct_score, + random_search.cv_results_["split%d_test_score" % i][cand_i], + ) + + +def test_predict_proba_disabled(): + # Test predict_proba when disabled on estimator. + X = np.arange(20).reshape(5, -1) + y = [0, 0, 1, 1, 1] + clf = SVC(probability=False) + gs = GridSearchCV(clf, {}, cv=2).fit(X, y) + assert not hasattr(gs, "predict_proba") + + +def test_grid_search_allows_nans(): + # Test GridSearchCV with SimpleImputer + X = np.arange(20, dtype=np.float64).reshape(5, -1) + X[2, :] = np.nan + y = [0, 0, 1, 1, 1] + p = Pipeline( + [ + ("imputer", SimpleImputer(strategy="mean", missing_values=np.nan)), + ("classifier", MockClassifier()), + ] + ) + GridSearchCV(p, {"classifier__foo_param": [1, 2, 3]}, cv=2).fit(X, y) + + +class FailingClassifier(BaseEstimator): + """Classifier that raises a ValueError on fit()""" + + FAILING_PARAMETER = 2 + + def __init__(self, parameter=None): + self.parameter = parameter + + def fit(self, X, y=None): + if self.parameter == FailingClassifier.FAILING_PARAMETER: + raise ValueError("Failing classifier failed as required") + + def predict(self, X): + return np.zeros(X.shape[0]) + + def score(self, X=None, Y=None): + return 0.0 + + +def test_grid_search_failing_classifier(): + # GridSearchCV with on_error != 'raise' + # Ensures that a warning is raised and score reset where appropriate. + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + # refit=False because we only want to check that errors caused by fits + # to individual folds will be caught and warnings raised instead. If + # refit was done, then an exception would be raised on refit and not + # caught by grid_search (expected behavior), and this would cause an + # error in this test. + gs = GridSearchCV( + clf, + [{"parameter": [0, 1, 2]}], + scoring="accuracy", + refit=False, + error_score=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) + n_candidates = len(gs.cv_results_["params"]) + + # Ensure that grid scores were set to zero as required for those fits + # that are expected to fail. + def get_cand_scores(i): + return np.array( + [gs.cv_results_["split%d_test_score" % s][i] for s in range(gs.n_splits_)] + ) + + assert all( + ( + np.all(get_cand_scores(cand_i) == 0.0) + for cand_i in range(n_candidates) + if gs.cv_results_["param_parameter"][cand_i] + == FailingClassifier.FAILING_PARAMETER + ) + ) + + gs = GridSearchCV( + clf, + [{"parameter": [0, 1, 2]}], + scoring="accuracy", + refit=False, + error_score=float("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) + n_candidates = len(gs.cv_results_["params"]) + assert all( + np.all(np.isnan(get_cand_scores(cand_i))) + for cand_i in range(n_candidates) + if gs.cv_results_["param_parameter"][cand_i] + == FailingClassifier.FAILING_PARAMETER + ) + + ranks = gs.cv_results_["rank_test_score"] + + # Check that succeeded estimators have lower ranks + assert ranks[0] <= 2 and ranks[1] <= 2 + # Check that failed estimator has the highest rank + assert ranks[clf.FAILING_PARAMETER] == 3 + 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 + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + # refit=False because we want to test the behaviour of the grid search part + gs = GridSearchCV( + clf, + [{"parameter": [0, 1, 2]}], + scoring="accuracy", + refit=False, + error_score="raise", + ) + + # FailingClassifier issues a ValueError so this is what we look for. + with pytest.raises(ValueError): + gs.fit(X, y) + + +def test_parameters_sampler_replacement(): + # raise warning if n_iter is bigger than total parameter space + params = [ + {"first": [0, 1], "second": ["a", "b", "c"]}, + {"third": ["two", "values"]}, + ] + sampler = ParameterSampler(params, n_iter=9) + n_iter = 9 + grid_size = 8 + expected_warning = ( + "The total space of parameters %d is smaller " + "than n_iter=%d. Running %d iterations. For " + "exhaustive searches, use GridSearchCV." % (grid_size, n_iter, grid_size) + ) + with pytest.warns(UserWarning, match=expected_warning): + list(sampler) + + # degenerates to GridSearchCV if n_iter the same as grid_size + sampler = ParameterSampler(params, n_iter=8) + samples = list(sampler) + assert len(samples) == 8 + for values in ParameterGrid(params): + assert values in samples + assert len(ParameterSampler(params, n_iter=1000)) == 8 + + # test sampling without replacement in a large grid + params = {"a": range(10), "b": range(10), "c": range(10)} + sampler = ParameterSampler(params, n_iter=99, random_state=42) + samples = list(sampler) + assert len(samples) == 99 + hashable_samples = ["a%db%dc%d" % (p["a"], p["b"], p["c"]) for p in samples] + assert len(set(hashable_samples)) == 99 + + # doesn't go into infinite loops + params_distribution = {"first": bernoulli(0.5), "second": ["a", "b", "c"]} + sampler = ParameterSampler(params_distribution, n_iter=7) + samples = list(sampler) + assert len(samples) == 7 + + +def test_stochastic_gradient_loss_param(): + # Make sure the predict_proba works when loss is specified + # as one of the parameters in the param_grid. + param_grid = { + "loss": ["log_loss"], + } + X = np.arange(24).reshape(6, -1) + y = [0, 0, 0, 1, 1, 1] + clf = GridSearchCV( + estimator=SGDClassifier(loss="hinge"), param_grid=param_grid, cv=3 + ) + + # When the estimator is not fitted, `predict_proba` is not available as the + # loss is 'hinge'. + assert not hasattr(clf, "predict_proba") + clf.fit(X, y) + clf.predict_proba(X) + clf.predict_log_proba(X) + + # Make sure `predict_proba` is not available when setting loss=['hinge'] + # in param_grid + param_grid = { + "loss": ["hinge"], + } + clf = GridSearchCV( + estimator=SGDClassifier(loss="hinge"), param_grid=param_grid, cv=3 + ) + assert not hasattr(clf, "predict_proba") + clf.fit(X, y) + assert not hasattr(clf, "predict_proba") + + +def test_search_train_scores_set_to_false(): + X = np.arange(6).reshape(6, -1) + y = [0, 0, 0, 1, 1, 1] + clf = LinearSVC(random_state=0) + + gs = GridSearchCV(clf, param_grid={"C": [0.1, 0.2]}, cv=3) + gs.fit(X, y) + + +def test_grid_search_cv_splits_consistency(): + # Check if a one time iterable is accepted as a cv parameter. + n_samples = 100 + n_splits = 5 + X, y = make_classification(n_samples=n_samples, random_state=0) + + gs = GridSearchCV( + LinearSVC(random_state=0), + param_grid={"C": [0.1, 0.2, 0.3]}, + cv=OneTimeSplitter(n_splits=n_splits, n_samples=n_samples), + return_train_score=True, + ) + gs.fit(X, y) + + gs2 = GridSearchCV( + LinearSVC(random_state=0), + param_grid={"C": [0.1, 0.2, 0.3]}, + cv=KFold(n_splits=n_splits), + return_train_score=True, + ) + gs2.fit(X, y) + + # Give generator as a cv parameter + assert isinstance( + KFold(n_splits=n_splits, shuffle=True, random_state=0).split(X, y), + GeneratorType, + ) + gs3 = GridSearchCV( + LinearSVC(random_state=0), + param_grid={"C": [0.1, 0.2, 0.3]}, + cv=KFold(n_splits=n_splits, shuffle=True, random_state=0).split(X, y), + return_train_score=True, + ) + gs3.fit(X, y) + + gs4 = GridSearchCV( + LinearSVC(random_state=0), + param_grid={"C": [0.1, 0.2, 0.3]}, + cv=KFold(n_splits=n_splits, shuffle=True, random_state=0), + return_train_score=True, + ) + gs4.fit(X, y) + + def _pop_time_keys(cv_results): + for key in ( + "mean_fit_time", + "std_fit_time", + "mean_score_time", + "std_score_time", + ): + cv_results.pop(key) + return cv_results + + # Check if generators are supported as cv and + # that the splits are consistent + np.testing.assert_equal( + _pop_time_keys(gs3.cv_results_), _pop_time_keys(gs4.cv_results_) + ) + + # OneTimeSplitter is a non-re-entrant cv where split can be called only + # once if ``cv.split`` is called once per param setting in GridSearchCV.fit + # the 2nd and 3rd parameter will not be evaluated as no train/test indices + # will be generated for the 2nd and subsequent cv.split calls. + # This is a check to make sure cv.split is not called once per param + # setting. + np.testing.assert_equal( + {k: v for k, v in gs.cv_results_.items() if not k.endswith("_time")}, + {k: v for k, v in gs2.cv_results_.items() if not k.endswith("_time")}, + ) + + # Check consistency of folds across the parameters + gs = GridSearchCV( + LinearSVC(random_state=0), + param_grid={"C": [0.1, 0.1, 0.2, 0.2]}, + cv=KFold(n_splits=n_splits, shuffle=True), + return_train_score=True, + ) + gs.fit(X, y) + + # As the first two param settings (C=0.1) and the next two param + # settings (C=0.2) are same, the test and train scores must also be + # same as long as the same train/test indices are generated for all + # the cv splits, for both param setting + for score_type in ("train", "test"): + per_param_scores = {} + for param_i in range(4): + per_param_scores[param_i] = [ + gs.cv_results_["split%d_%s_score" % (s, score_type)][param_i] + for s in range(5) + ] + + assert_array_almost_equal(per_param_scores[0], per_param_scores[1]) + assert_array_almost_equal(per_param_scores[2], per_param_scores[3]) + + +def test_transform_inverse_transform_round_trip(): + clf = MockClassifier() + grid_search = GridSearchCV(clf, {"foo_param": [1, 2, 3]}, cv=2, verbose=3) + + grid_search.fit(X, y) + X_round_trip = grid_search.inverse_transform(grid_search.transform(X)) + assert_array_equal(X, X_round_trip) + + +def test_custom_run_search(): + def check_results(results, gscv): + exp_results = gscv.cv_results_ + assert sorted(results.keys()) == sorted(exp_results) + for k in results: + if not k.endswith("_time"): + # XXX: results['params'] is a list :| + results[k] = np.asanyarray(results[k]) + if results[k].dtype.kind == "O": + assert_array_equal( + exp_results[k], results[k], err_msg="Checking " + k + ) + else: + assert_allclose(exp_results[k], results[k], err_msg="Checking " + k) + + def fit_grid(param_grid): + return GridSearchCV(clf, param_grid, return_train_score=True).fit(X, y) + + class CustomSearchCV(BaseSearchCV): + def __init__(self, estimator, **kwargs): + super().__init__(estimator, **kwargs) + + def _run_search(self, evaluate): + results = evaluate([{"max_depth": 1}, {"max_depth": 2}]) + check_results(results, fit_grid({"max_depth": [1, 2]})) + results = evaluate([{"min_samples_split": 5}, {"min_samples_split": 10}]) + check_results( + results, + fit_grid([{"max_depth": [1, 2]}, {"min_samples_split": [5, 10]}]), + ) + + # Using regressor to make sure each score differs + clf = DecisionTreeRegressor(random_state=0) + X, y = make_classification(n_samples=100, n_informative=4, random_state=0) + mycv = CustomSearchCV(clf, return_train_score=True).fit(X, y) + gscv = fit_grid([{"max_depth": [1, 2]}, {"min_samples_split": [5, 10]}]) + + results = mycv.cv_results_ + check_results(results, gscv) + for attr in dir(gscv): + if ( + attr[0].islower() + and attr[-1:] == "_" + and attr + not in { + "cv_results_", + "best_estimator_", + "refit_time_", + "classes_", + "scorer_", + } + ): + assert getattr(gscv, attr) == getattr(mycv, attr), ( + "Attribute %s not equal" % attr + ) + + +def test__custom_fit_no_run_search(): + class NoRunSearchSearchCV(BaseSearchCV): + def __init__(self, estimator, **kwargs): + super().__init__(estimator, **kwargs) + + def fit(self, X, y=None, groups=None, **fit_params): + return self + + # this should not raise any exceptions + NoRunSearchSearchCV(SVC()).fit(X, y) + + class BadSearchCV(BaseSearchCV): + def __init__(self, estimator, **kwargs): + super().__init__(estimator, **kwargs) + + with pytest.raises(NotImplementedError, match="_run_search not implemented."): + # this should raise a NotImplementedError + BadSearchCV(SVC()).fit(X, y) + + +def test_empty_cv_iterator_error(): + # Use global X, y + + # create cv + cv = KFold(n_splits=3).split(X) + + # pop all of it, this should cause the expected ValueError + [u for u in cv] + # cv is empty now + + train_size = 100 + ridge = RandomizedSearchCV(Ridge(), {"alpha": [1e-3, 1e-2, 1e-1]}, cv=cv, n_jobs=4) + + # assert that this raises an error + with pytest.raises( + ValueError, + match=( + "No fits were performed. " + "Was the CV iterator empty\\? " + "Were there no candidates\\?" + ), + ): + ridge.fit(X[:train_size], y[:train_size]) + + +def test_random_search_bad_cv(): + # Use global X, y + + class BrokenKFold(KFold): + def get_n_splits(self, *args, **kw): + return 1 + + # create bad cv + cv = BrokenKFold(n_splits=3) + + train_size = 100 + ridge = RandomizedSearchCV(Ridge(), {"alpha": [1e-3, 1e-2, 1e-1]}, cv=cv, n_jobs=4) + + # assert that this raises an error + with pytest.raises( + ValueError, + match=( + "cv.split and cv.get_n_splits returned " + "inconsistent results. Expected \\d+ " + "splits, got \\d+" + ), + ): + ridge.fit(X[:train_size], y[:train_size]) + + +@pytest.mark.parametrize("return_train_score", [False, True]) +@pytest.mark.parametrize( + "SearchCV, specialized_params", + [ + (GridSearchCV, {"param_grid": {"max_depth": [2, 3, 5, 8]}}), + ( + RandomizedSearchCV, + {"param_distributions": {"max_depth": [2, 3, 5, 8]}, "n_iter": 4}, + ), + ], +) +def test_searchcv_raise_warning_with_non_finite_score( + SearchCV, specialized_params, return_train_score +): + # Non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/10529 + # Check that we raise a UserWarning when a non-finite score is + # computed in the SearchCV + X, y = make_classification(n_classes=2, random_state=0) + + class FailingScorer: + """Scorer that will fail for some split but not all.""" + + def __init__(self): + self.n_counts = 0 + + def __call__(self, estimator, X, y): + self.n_counts += 1 + if self.n_counts % 5 == 0: + return np.nan + return 1 + + grid = SearchCV( + DecisionTreeClassifier(), + scoring=FailingScorer(), + cv=3, + return_train_score=return_train_score, + **specialized_params, + ) + + with pytest.warns(UserWarning) as warn_msg: + grid.fit(X, y) + + set_with_warning = ["test", "train"] if return_train_score else ["test"] + assert len(warn_msg) == len(set_with_warning) + for msg, dataset in zip(warn_msg, set_with_warning): + assert f"One or more of the {dataset} scores are non-finite" in str(msg.message) + + # all non-finite scores should be equally ranked last + last_rank = grid.cv_results_["rank_test_score"].max() + non_finite_mask = np.isnan(grid.cv_results_["mean_test_score"]) + assert_array_equal(grid.cv_results_["rank_test_score"][non_finite_mask], last_rank) + # all finite scores should be better ranked than the non-finite scores + assert np.all(grid.cv_results_["rank_test_score"][~non_finite_mask] < last_rank) + + +def test_callable_multimetric_confusion_matrix(): + # Test callable with many metrics inserts the correct names and metrics + # into the search cv object + def custom_scorer(clf, X, y): + y_pred = clf.predict(X) + cm = confusion_matrix(y, y_pred) + return {"tn": cm[0, 0], "fp": cm[0, 1], "fn": cm[1, 0], "tp": cm[1, 1]} + + X, y = make_classification(n_samples=40, n_features=4, random_state=42) + est = LinearSVC(random_state=42) + search = GridSearchCV(est, {"C": [0.1, 1]}, scoring=custom_scorer, refit="fp") + + search.fit(X, y) + + score_names = ["tn", "fp", "fn", "tp"] + for name in score_names: + assert "mean_test_{}".format(name) in search.cv_results_ + + y_pred = search.predict(X) + cm = confusion_matrix(y, y_pred) + assert search.score(X, y) == pytest.approx(cm[0, 1]) + + +def test_callable_multimetric_same_as_list_of_strings(): + # Test callable multimetric is the same as a list of strings + def custom_scorer(est, X, y): + y_pred = est.predict(X) + return { + "recall": recall_score(y, y_pred), + "accuracy": accuracy_score(y, y_pred), + } + + X, y = make_classification(n_samples=40, n_features=4, random_state=42) + est = LinearSVC(random_state=42) + search_callable = GridSearchCV( + est, {"C": [0.1, 1]}, scoring=custom_scorer, refit="recall" + ) + search_str = GridSearchCV( + est, {"C": [0.1, 1]}, scoring=["recall", "accuracy"], refit="recall" + ) + + search_callable.fit(X, y) + search_str.fit(X, y) + + assert search_callable.best_score_ == pytest.approx(search_str.best_score_) + assert search_callable.best_index_ == search_str.best_index_ + assert search_callable.score(X, y) == pytest.approx(search_str.score(X, y)) + + +def test_callable_single_metric_same_as_single_string(): + # Tests callable scorer is the same as scoring with a single string + def custom_scorer(est, X, y): + y_pred = est.predict(X) + return recall_score(y, y_pred) + + X, y = make_classification(n_samples=40, n_features=4, random_state=42) + est = LinearSVC(random_state=42) + search_callable = GridSearchCV( + est, {"C": [0.1, 1]}, scoring=custom_scorer, refit=True + ) + search_str = GridSearchCV(est, {"C": [0.1, 1]}, scoring="recall", refit="recall") + search_list_str = GridSearchCV( + est, {"C": [0.1, 1]}, scoring=["recall"], refit="recall" + ) + search_callable.fit(X, y) + search_str.fit(X, y) + search_list_str.fit(X, y) + + assert search_callable.best_score_ == pytest.approx(search_str.best_score_) + assert search_callable.best_index_ == search_str.best_index_ + assert search_callable.score(X, y) == pytest.approx(search_str.score(X, y)) + + assert search_list_str.best_score_ == pytest.approx(search_str.best_score_) + assert search_list_str.best_index_ == search_str.best_index_ + assert search_list_str.score(X, y) == pytest.approx(search_str.score(X, y)) + + +def test_callable_multimetric_error_on_invalid_key(): + # Raises when the callable scorer does not return a dict with `refit` key. + def bad_scorer(est, X, y): + return {"bad_name": 1} + + X, y = make_classification(n_samples=40, n_features=4, random_state=42) + clf = GridSearchCV( + LinearSVC(random_state=42), + {"C": [0.1, 1]}, + scoring=bad_scorer, + refit="good_name", + ) + + msg = ( + "For multi-metric scoring, the parameter refit must be set to a " + "scorer key or a callable to refit" + ) + with pytest.raises(ValueError, match=msg): + clf.fit(X, y) + + +def test_callable_multimetric_error_failing_clf(): + # Warns when there is an estimator the fails to fit with a float + # error_score + def custom_scorer(est, X, y): + return {"acc": 1} + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + gs = GridSearchCV( + clf, + [{"parameter": [0, 1, 2]}], + scoring=custom_scorer, + refit=False, + error_score=0.1, + ) + + 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]) + + +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} + + X, y = make_classification(n_samples=20, n_features=10, random_state=0) + + clf = FailingClassifier() + + gs = GridSearchCV( + clf, + [{"parameter": [FailingClassifier.FAILING_PARAMETER] * 3}], + scoring=custom_scorer, + refit=False, + error_score=0.1, + ) + + 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) + + +def test_n_features_in(): + # make sure grid search and random search delegate n_features_in to the + # best estimator + n_features = 4 + X, y = make_classification(n_features=n_features) + gbdt = HistGradientBoostingClassifier() + param_grid = {"max_iter": [3, 4]} + gs = GridSearchCV(gbdt, param_grid) + rs = RandomizedSearchCV(gbdt, param_grid, n_iter=1) + assert not hasattr(gs, "n_features_in_") + assert not hasattr(rs, "n_features_in_") + gs.fit(X, y) + rs.fit(X, y) + assert gs.n_features_in_ == n_features + assert rs.n_features_in_ == n_features + + +@pytest.mark.parametrize("pairwise", [True, False]) +def test_search_cv_pairwise_property_delegated_to_base_estimator(pairwise): + """ + Test implementation of BaseSearchCV has the pairwise tag + which matches the pairwise tag of its estimator. + This test make sure pairwise tag is delegated to the base estimator. + + Non-regression test for issue #13920. + """ + + class TestEstimator(BaseEstimator): + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = pairwise + return tags + + est = TestEstimator() + attr_message = "BaseSearchCV pairwise tag must match estimator" + cv = GridSearchCV(est, {"n_neighbors": [10]}) + assert pairwise == cv.__sklearn_tags__().input_tags.pairwise, attr_message + + +def test_search_cv__pairwise_property_delegated_to_base_estimator(): + """ + Test implementation of BaseSearchCV has the pairwise property + which matches the pairwise tag of its estimator. + This test make sure pairwise tag is delegated to the base estimator. + + Non-regression test for issue #13920. + """ + + class EstimatorPairwise(BaseEstimator): + def __init__(self, pairwise=True): + self.pairwise = pairwise + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.pairwise = self.pairwise + return tags + + est = EstimatorPairwise() + attr_message = "BaseSearchCV _pairwise property must match estimator" + + for _pairwise_setting in [True, False]: + est.set_params(pairwise=_pairwise_setting) + cv = GridSearchCV(est, {"n_neighbors": [10]}) + assert _pairwise_setting == cv.__sklearn_tags__().input_tags.pairwise, ( + attr_message + ) + + +def test_search_cv_pairwise_property_equivalence_of_precomputed(): + """ + Test implementation of BaseSearchCV has the pairwise tag + which matches the pairwise tag of its estimator. + This test ensures the equivalence of 'precomputed'. + + Non-regression test for issue #13920. + """ + n_samples = 50 + n_splits = 2 + X, y = make_classification(n_samples=n_samples, random_state=0) + grid_params = {"n_neighbors": [10]} + + # defaults to euclidean metric (minkowski p = 2) + clf = KNeighborsClassifier() + cv = GridSearchCV(clf, grid_params, cv=n_splits) + cv.fit(X, y) + preds_original = cv.predict(X) + + # precompute euclidean metric to validate pairwise is working + X_precomputed = euclidean_distances(X) + clf = KNeighborsClassifier(metric="precomputed") + cv = GridSearchCV(clf, grid_params, cv=n_splits) + cv.fit(X_precomputed, y) + preds_precomputed = cv.predict(X_precomputed) + + attr_message = "GridSearchCV not identical with precomputed metric" + assert (preds_original == preds_precomputed).all(), attr_message + + +@pytest.mark.parametrize( + "SearchCV, param_search", + [(GridSearchCV, {"a": [0.1, 0.01]}), (RandomizedSearchCV, {"a": uniform(1, 3)})], +) +def test_scalar_fit_param(SearchCV, param_search): + # unofficially sanctioned tolerance for scalar values in fit_params + # non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/15805 + class TestEstimator(ClassifierMixin, BaseEstimator): + def __init__(self, a=None): + self.a = a + + def fit(self, X, y, r=None): + self.r_ = r + + def predict(self, X): + return np.zeros(shape=(len(X))) + + model = SearchCV(TestEstimator(), param_search) + X, y = make_classification(random_state=42) + model.fit(X, y, r=42) + assert model.best_estimator_.r_ == 42 + + +@pytest.mark.parametrize( + "SearchCV, param_search", + [ + (GridSearchCV, {"alpha": [0.1, 0.01]}), + (RandomizedSearchCV, {"alpha": uniform(0.01, 0.1)}), + ], +) +def test_scalar_fit_param_compat(SearchCV, param_search): + # check support for scalar values in fit_params, for instance in LightGBM + # that do not exactly respect the scikit-learn API contract but that we do + # not want to break without an explicit deprecation cycle and API + # recommendations for implementing early stopping with a user provided + # validation set. non-regression test for: + # https://github.com/scikit-learn/scikit-learn/issues/15805 + X_train, X_valid, y_train, y_valid = train_test_split( + *make_classification(random_state=42), random_state=42 + ) + + class _FitParamClassifier(SGDClassifier): + def fit( + self, + X, + y, + sample_weight=None, + tuple_of_arrays=None, + scalar_param=None, + callable_param=None, + ): + super().fit(X, y, sample_weight=sample_weight) + assert scalar_param > 0 + assert callable(callable_param) + + # The tuple of arrays should be preserved as tuple. + assert isinstance(tuple_of_arrays, tuple) + assert tuple_of_arrays[0].ndim == 2 + assert tuple_of_arrays[1].ndim == 1 + return self + + def _fit_param_callable(): + pass + + model = SearchCV(_FitParamClassifier(), param_search) + + # NOTE: `fit_params` should be data dependent (e.g. `sample_weight`) which + # is not the case for the following parameters. But this abuse is common in + # popular third-party libraries and we should tolerate this behavior for + # now and be careful not to break support for those without following + # proper deprecation cycle. + fit_params = { + "tuple_of_arrays": (X_valid, y_valid), + "callable_param": _fit_param_callable, + "scalar_param": 42, + } + model.fit(X_train, y_train, **fit_params) + + +# FIXME: Replace this test with a full `check_estimator` once we have API only +# checks. +@pytest.mark.filterwarnings("ignore:The total space of parameters 4 is") +@pytest.mark.parametrize("SearchCV", [GridSearchCV, RandomizedSearchCV]) +@pytest.mark.parametrize("Predictor", [MinimalRegressor, MinimalClassifier]) +def test_search_cv_using_minimal_compatible_estimator(SearchCV, Predictor): + # Check that third-party library can run tests without inheriting from + # BaseEstimator. + rng = np.random.RandomState(0) + X, y = rng.randn(25, 2), np.array([0] * 5 + [1] * 20) + + model = Pipeline( + [("transformer", MinimalTransformer()), ("predictor", Predictor())] + ) + + params = { + "transformer__param": [1, 10], + "predictor__parama": [1, 10], + } + search = SearchCV(model, params, error_score="raise") + search.fit(X, y) + + assert search.best_params_.keys() == params.keys() + + y_pred = search.predict(X) + if is_classifier(search): + assert_array_equal(y_pred, 1) + assert search.score(X, y) == pytest.approx(accuracy_score(y, y_pred)) + else: + assert_allclose(y_pred, y.mean()) + assert search.score(X, y) == pytest.approx(r2_score(y, y_pred)) + + +@pytest.mark.parametrize("return_train_score", [True, False]) +def test_search_cv_verbose_3(capsys, return_train_score): + """Check that search cv with verbose>2 shows the score for single + metrics. non-regression test for #19658.""" + X, y = make_classification(n_samples=100, n_classes=2, flip_y=0.2, random_state=0) + clf = LinearSVC(random_state=0) + grid = {"C": [0.1]} + + GridSearchCV( + clf, + grid, + scoring="accuracy", + verbose=3, + cv=3, + return_train_score=return_train_score, + ).fit(X, y) + captured = capsys.readouterr().out + if return_train_score: + match = re.findall(r"score=\(train=[\d\.]+, test=[\d.]+\)", captured) + else: + match = re.findall(r"score=[\d\.]+", captured) + assert len(match) == 3 + + +@pytest.mark.parametrize( + "SearchCV, param_search", + [ + (GridSearchCV, "param_grid"), + (RandomizedSearchCV, "param_distributions"), + (HalvingGridSearchCV, "param_grid"), + ], +) +def test_search_estimator_param(SearchCV, param_search): + # test that SearchCV object doesn't change the object given in the parameter grid + X, y = make_classification(random_state=42) + + params = {"clf": [LinearSVC()], "clf__C": [0.01]} + orig_C = params["clf"][0].C + + pipe = Pipeline([("trs", MinimalTransformer()), ("clf", None)]) + + param_grid_search = {param_search: params} + gs = SearchCV(pipe, refit=True, cv=2, scoring="accuracy", **param_grid_search).fit( + X, y + ) + + # testing that the original object in params is not changed + assert params["clf"][0].C == orig_C + # testing that the GS is setting the parameter of the step correctly + assert gs.best_estimator_.named_steps["clf"].C == 0.01 + + +def test_search_with_2d_array(): + parameter_grid = { + "vect__ngram_range": ((1, 1), (1, 2)), # unigrams or bigrams + "vect__norm": ("l1", "l2"), + } + pipeline = Pipeline( + [ + ("vect", TfidfVectorizer()), + ("clf", ComplementNB()), + ] + ) + random_search = RandomizedSearchCV( + estimator=pipeline, + param_distributions=parameter_grid, + n_iter=3, + random_state=0, + n_jobs=2, + verbose=1, + cv=3, + ) + data_train = ["one", "two", "three", "four", "five"] + data_target = [0, 0, 1, 0, 1] + random_search.fit(data_train, data_target) + result = random_search.cv_results_["param_vect__ngram_range"] + expected_data = np.empty(3, dtype=object) + expected_data[:] = [(1, 2), (1, 2), (1, 1)] + np.testing.assert_array_equal(result.data, expected_data) + + +def test_search_html_repr(): + """Test different HTML representations for GridSearchCV.""" + X, y = make_classification(random_state=42) + + pipeline = Pipeline([("scale", StandardScaler()), ("clf", DummyClassifier())]) + param_grid = {"clf": [DummyClassifier(), LogisticRegression()]} + + # Unfitted shows the original pipeline + search_cv = GridSearchCV(pipeline, param_grid=param_grid, refit=False) + with config_context(display="diagram"): + repr_html = search_cv._repr_html_() + assert "
DummyClassifier
" in repr_html + + # Fitted with `refit=False` shows the original pipeline + search_cv.fit(X, y) + with config_context(display="diagram"): + repr_html = search_cv._repr_html_() + assert "
DummyClassifier
" in repr_html + + # Fitted with `refit=True` shows the best estimator + search_cv = GridSearchCV(pipeline, param_grid=param_grid, refit=True) + search_cv.fit(X, y) + with config_context(display="diagram"): + repr_html = search_cv._repr_html_() + assert "
DummyClassifier
" not in repr_html + assert "
LogisticRegression
" in repr_html + + +# Metadata Routing Tests +# ====================== + + +@pytest.mark.parametrize( + "SearchCV, param_search", + [ + (GridSearchCV, "param_grid"), + (RandomizedSearchCV, "param_distributions"), + ], +) +@config_context(enable_metadata_routing=True) +def test_multi_metric_search_forwards_metadata(SearchCV, param_search): + """Test that *SearchCV forwards metadata correctly when passed multiple metrics.""" + X, y = make_classification(random_state=42) + n_samples = _num_samples(X) + rng = np.random.RandomState(0) + score_weights = rng.rand(n_samples) + score_metadata = rng.rand(n_samples) + + est = LinearSVC() + param_grid_search = {param_search: {"C": [1]}} + + scorer_registry = _Registry() + scorer = ConsumingScorer(registry=scorer_registry).set_score_request( + sample_weight="score_weights", metadata="score_metadata" + ) + scoring = dict(my_scorer=scorer, accuracy="accuracy") + SearchCV(est, refit="accuracy", cv=2, scoring=scoring, **param_grid_search).fit( + X, y, score_weights=score_weights, score_metadata=score_metadata + ) + assert len(scorer_registry) + for _scorer in scorer_registry: + check_recorded_metadata( + obj=_scorer, + method="score", + parent="_score", + split_params=("sample_weight", "metadata"), + sample_weight=score_weights, + metadata=score_metadata, + ) + + +@pytest.mark.parametrize( + "SearchCV, param_search", + [ + (GridSearchCV, "param_grid"), + (RandomizedSearchCV, "param_distributions"), + (HalvingGridSearchCV, "param_grid"), + ], +) +def test_score_rejects_params_with_no_routing_enabled(SearchCV, param_search): + """*SearchCV should reject **params when metadata routing is not enabled + since this is added only when routing is enabled.""" + X, y = make_classification(random_state=42) + est = LinearSVC() + param_grid_search = {param_search: {"C": [1]}} + + gs = SearchCV(est, cv=2, **param_grid_search).fit(X, y) + + with pytest.raises(ValueError, match="is only supported if"): + gs.score(X, y, metadata=1) + + +# End of Metadata Routing Tests +# ============================= + + +def test_cv_results_dtype_issue_29074(): + """Non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29074""" + + class MetaEstimator(BaseEstimator, ClassifierMixin): + def __init__( + self, + base_clf, + parameter1=None, + parameter2=None, + parameter3=None, + parameter4=None, + ): + self.base_clf = base_clf + self.parameter1 = parameter1 + self.parameter2 = parameter2 + self.parameter3 = parameter3 + self.parameter4 = parameter4 + + def fit(self, X, y=None): + self.base_clf.fit(X, y) + return self + + def score(self, X, y): + return self.base_clf.score(X, y) + + # Values of param_grid are such that np.result_type gives slightly + # different errors, in particular ValueError and TypeError + param_grid = { + "parameter1": [None, {"option": "A"}, {"option": "B"}], + "parameter2": [None, [1, 2]], + "parameter3": [{"a": 1}], + "parameter4": ["str1", "str2"], + } + grid_search = GridSearchCV( + estimator=MetaEstimator(LogisticRegression()), + param_grid=param_grid, + cv=3, + ) + + X, y = make_blobs(random_state=0) + grid_search.fit(X, y) + for param in param_grid: + assert grid_search.cv_results_[f"param_{param}"].dtype == object + + +def test_search_with_estimators_issue_29157(): + """Check cv_results_ for estimators with a `dtype` parameter, e.g. OneHotEncoder.""" + pd = pytest.importorskip("pandas") + df = pd.DataFrame( + { + "numeric_1": [1, 2, 3, 4, 5], + "object_1": ["a", "a", "a", "a", "a"], + "target": [1.0, 4.1, 2.0, 3.0, 1.0], + } + ) + X = df.drop("target", axis=1) + y = df["target"] + enc = ColumnTransformer( + [("enc", OneHotEncoder(sparse_output=False), ["object_1"])], + remainder="passthrough", + ) + pipe = Pipeline( + [ + ("enc", enc), + ("regressor", LinearRegression()), + ] + ) + grid_params = { + "enc__enc": [ + OneHotEncoder(sparse_output=False), + OrdinalEncoder(), + ] + } + grid_search = GridSearchCV(pipe, grid_params, cv=2) + grid_search.fit(X, y) + assert grid_search.cv_results_["param_enc__enc"].dtype == object + + +def test_cv_results_multi_size_array(): + """Check that GridSearchCV works with params that are arrays of different sizes. + + Non-regression test for #29277. + """ + n_features = 10 + X, y = make_classification(n_features=10) + + spline_reg_pipe = make_pipeline( + SplineTransformer(extrapolation="periodic"), + LogisticRegression(), + ) + + n_knots_list = [n_features * i for i in [10, 11, 12]] + knots_list = [ + np.linspace(0, np.pi * 2, n_knots).reshape((-1, n_features)) + for n_knots in n_knots_list + ] + spline_reg_pipe_cv = GridSearchCV( + estimator=spline_reg_pipe, + param_grid={ + "splinetransformer__knots": knots_list, + }, + ) + + spline_reg_pipe_cv.fit(X, y) + assert ( + spline_reg_pipe_cv.cv_results_["param_splinetransformer__knots"].dtype == object + ) + + +@pytest.mark.parametrize( + "array_namespace, device, dtype", + yield_namespace_device_dtype_combinations(), + ids=_get_namespace_device_dtype_ids, +) +@pytest.mark.parametrize("SearchCV", [GridSearchCV, RandomizedSearchCV]) +def test_array_api_search_cv_classifier(SearchCV, array_namespace, device, dtype): + xp = _array_api_for_tests(array_namespace, device) + + X = np.arange(100).reshape((10, 10)) + X_np = X.astype(dtype) + X_xp = xp.asarray(X_np, device=device) + + # y should always be an integer, no matter what `dtype` is + y_np = np.array([0] * 5 + [1] * 5) + y_xp = xp.asarray(y_np, device=device) + + with config_context(array_api_dispatch=True): + searcher = SearchCV( + LinearDiscriminantAnalysis(), + {"tol": [1e-2, 1e-3, 1e-4, 1e-5, 1e-6, 1e-7]}, + cv=2, + error_score="raise", + ) + searcher.fit(X_xp, y_xp) + searcher.score(X_xp, y_xp) + + +# Construct these outside the tests so that the same object is used +# for both input and `expected` +one_hot_encoder = OneHotEncoder() +ordinal_encoder = OrdinalEncoder() + +# If we construct this directly via `MaskedArray`, the list of tuples +# gets auto-converted to a 2D array. +ma_with_tuples = np.ma.MaskedArray(np.empty(2), mask=True, dtype=object) # type: ignore[var-annotated] +ma_with_tuples[0] = (1, 2) +ma_with_tuples[1] = (3, 4) + + +@pytest.mark.parametrize( + ("candidate_params", "expected"), + [ + pytest.param( + [{"foo": 1}, {"foo": 2}], + [ + ("param_foo", np.ma.MaskedArray(np.array([1, 2]))), + ], + id="simple numeric, single param", + ), + pytest.param( + [{"foo": 1, "bar": 3}, {"foo": 2, "bar": 4}, {"foo": 3}], + [ + ("param_foo", np.ma.MaskedArray(np.array([1, 2, 3]))), + ( + "param_bar", + np.ma.MaskedArray(np.array([3, 4, 0]), mask=[False, False, True]), + ), + ], + id="simple numeric, one param is missing in one round", + ), + pytest.param( + [{"foo": [[1], [2], [3]]}, {"foo": [[1], [2]]}], + [ + ( + "param_foo", + np.ma.MaskedArray([[[1], [2], [3]], [[1], [2]]], dtype=object), + ), + ], + id="lists of different lengths", + ), + pytest.param( + [{"foo": (1, 2)}, {"foo": (3, 4)}], + [ + ( + "param_foo", + ma_with_tuples, + ), + ], + id="lists tuples", + ), + pytest.param( + [{"foo": ordinal_encoder}, {"foo": one_hot_encoder}], + [ + ( + "param_foo", + np.ma.MaskedArray([ordinal_encoder, one_hot_encoder], dtype=object), + ), + ], + id="estimators", + ), + ], +) +def test_yield_masked_array_for_each_param(candidate_params, expected): + result = list(_yield_masked_array_for_each_param(candidate_params)) + for (key, value), (expected_key, expected_value) in zip(result, expected): + assert key == expected_key + assert value.dtype == expected_value.dtype + np.testing.assert_array_equal(value, expected_value) + np.testing.assert_array_equal(value.mask, expected_value.mask) + + +def test_yield_masked_array_no_runtime_warning(): + # non-regression test for https://github.com/scikit-learn/scikit-learn/issues/29929 + candidate_params = [{"param": i} for i in range(1000)] + with warnings.catch_warnings(): + warnings.simplefilter("error", RuntimeWarning) + list(_yield_masked_array_for_each_param(candidate_params)) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_split.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_split.py new file mode 100644 index 0000000000000000000000000000000000000000..0f31055d9b7f959c36888efbd4adae01f0a06822 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_split.py @@ -0,0 +1,2102 @@ +"""Test the split module""" + +import re +import warnings +from itertools import combinations, combinations_with_replacement, permutations + +import numpy as np +import pytest +from scipy import stats +from scipy.sparse import issparse +from scipy.special import comb + +from sklearn import config_context +from sklearn.datasets import load_digits, make_classification +from sklearn.dummy import DummyClassifier +from sklearn.model_selection import ( + GridSearchCV, + GroupKFold, + GroupShuffleSplit, + KFold, + LeaveOneGroupOut, + LeaveOneOut, + LeavePGroupsOut, + LeavePOut, + PredefinedSplit, + RepeatedKFold, + RepeatedStratifiedKFold, + ShuffleSplit, + StratifiedGroupKFold, + StratifiedKFold, + StratifiedShuffleSplit, + TimeSeriesSplit, + check_cv, + cross_val_score, + train_test_split, +) +from sklearn.model_selection._split import ( + _build_repr, + _validate_shuffle_split, + _yields_constant_splits, +) +from sklearn.svm import SVC +from sklearn.tests.metadata_routing_common import assert_request_is_empty +from sklearn.utils._array_api import ( + _convert_to_numpy, + _get_namespace_device_dtype_ids, + get_namespace, + yield_namespace_device_dtype_combinations, +) +from sklearn.utils._array_api import ( + device as array_api_device, +) +from sklearn.utils._mocking import MockDataFrame +from sklearn.utils._testing import ( + assert_allclose, + assert_array_almost_equal, + assert_array_equal, + ignore_warnings, +) +from sklearn.utils.estimator_checks import ( + _array_api_for_tests, +) +from sklearn.utils.fixes import COO_CONTAINERS, CSC_CONTAINERS, CSR_CONTAINERS +from sklearn.utils.validation import _num_samples + +NO_GROUP_SPLITTERS = [ + KFold(), + StratifiedKFold(), + TimeSeriesSplit(), + LeaveOneOut(), + LeavePOut(p=2), + ShuffleSplit(), + StratifiedShuffleSplit(test_size=0.5), + PredefinedSplit([1, 1, 2, 2]), + RepeatedKFold(), + RepeatedStratifiedKFold(), +] + +GROUP_SPLITTERS = [ + GroupKFold(), + LeavePGroupsOut(n_groups=1), + StratifiedGroupKFold(), + LeaveOneGroupOut(), + GroupShuffleSplit(), +] +GROUP_SPLITTER_NAMES = set(splitter.__class__.__name__ for splitter in GROUP_SPLITTERS) + +ALL_SPLITTERS = NO_GROUP_SPLITTERS + GROUP_SPLITTERS # type: ignore[list-item] + +SPLITTERS_REQUIRING_TARGET = [ + StratifiedKFold(), + StratifiedShuffleSplit(), + RepeatedStratifiedKFold(), +] + +X = np.ones(10) +y = np.arange(10) // 2 +test_groups = ( + np.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]), + np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), + np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]), + np.array([1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4]), + [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3], + ["1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "3", "3"], +) +digits = load_digits() + +pytestmark = pytest.mark.filterwarnings( + "error:The groups parameter:UserWarning:sklearn.*" +) + + +def _split(splitter, X, y, groups): + if splitter.__class__.__name__ in GROUP_SPLITTER_NAMES: + return splitter.split(X, y, groups=groups) + else: + return splitter.split(X, y) + + +def test_cross_validator_with_default_params(): + n_samples = 4 + n_unique_groups = 4 + n_splits = 2 + p = 2 + n_shuffle_splits = 10 # (the default value) + + X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) + X_1d = np.array([1, 2, 3, 4]) + y = np.array([1, 1, 2, 2]) + groups = np.array([1, 2, 3, 4]) + loo = LeaveOneOut() + lpo = LeavePOut(p) + kf = KFold(n_splits) + skf = StratifiedKFold(n_splits) + lolo = LeaveOneGroupOut() + 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)" + kf_repr = "KFold(n_splits=2, random_state=None, shuffle=False)" + skf_repr = "StratifiedKFold(n_splits=2, random_state=None, shuffle=False)" + lolo_repr = "LeaveOneGroupOut()" + lopo_repr = "LeavePGroupsOut(n_groups=2)" + 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_splits, + ] + + for i, (cv, cv_repr) in enumerate( + zip( + [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, + sgkf_repr, + ], + ) + ): + # Test if get_n_splits works correctly + assert n_splits_expected[i] == cv.get_n_splits(X, y, groups) + + # Test if the cross-validator works as expected even if + # the data is 1d + np.testing.assert_equal( + list(_split(cv, X, y, groups)), list(_split(cv, X_1d, y, groups)) + ) + # Test that train, test indices returned are integers + for train, test in _split(cv, X, y, groups): + assert np.asarray(train).dtype.kind == "i" + assert np.asarray(test).dtype.kind == "i" + + # Test if the repr works without any errors + assert cv_repr == repr(cv) + + # ValueError for get_n_splits methods + msg = "The 'X' parameter should not be None." + with pytest.raises(ValueError, match=msg): + loo.get_n_splits(None, y, groups) + with pytest.raises(ValueError, match=msg): + lpo.get_n_splits(None, y, groups) + + +def test_2d_y(): + # smoke test for 2d y and multi-label + n_samples = 30 + rng = np.random.RandomState(1) + X = rng.randint(0, 3, size=(n_samples, 2)) + y = rng.randint(0, 3, size=(n_samples,)) + y_2d = y.reshape(-1, 1) + y_multilabel = rng.randint(0, 2, size=(n_samples, 3)) + groups = rng.randint(0, 3, size=(n_samples,)) + splitters = [ + LeaveOneOut(), + LeavePOut(p=2), + KFold(), + StratifiedKFold(), + RepeatedKFold(), + RepeatedStratifiedKFold(), + StratifiedGroupKFold(), + ShuffleSplit(), + StratifiedShuffleSplit(test_size=0.5), + GroupShuffleSplit(), + LeaveOneGroupOut(), + LeavePGroupsOut(n_groups=2), + GroupKFold(n_splits=3), + TimeSeriesSplit(), + PredefinedSplit(test_fold=groups), + ] + for splitter in splitters: + list(_split(splitter, X, y, groups=groups)) + list(_split(splitter, X, y_2d, groups=groups)) + try: + list(_split(splitter, X, y_multilabel, groups=groups)) + except ValueError as e: + allowed_target_types = ("binary", "multiclass") + msg = "Supported target types are: {}. Got 'multilabel".format( + allowed_target_types + ) + assert msg in str(e) + + +def check_valid_split(train, test, n_samples=None): + # Use python sets to get more informative assertion failure messages + train, test = set(train), set(test) + + # Train and test split should not overlap + assert train.intersection(test) == set() + + if n_samples is not None: + # Check that the union of train an test split cover all the indices + assert train.union(test) == set(range(n_samples)) + + +def check_cv_coverage(cv, X, y, groups, expected_n_splits): + n_samples = _num_samples(X) + # Check that a all the samples appear at least once in a test fold + assert cv.get_n_splits(X, y, groups) == expected_n_splits + + collected_test_samples = set() + iterations = 0 + for train, test in cv.split(X, y, groups): + check_valid_split(train, test, n_samples=n_samples) + iterations += 1 + collected_test_samples.update(test) + + # Check that the accumulated test samples cover the whole dataset + assert iterations == expected_n_splits + if n_samples is not None: + assert collected_test_samples == set(range(n_samples)) + + +def test_kfold_valueerrors(): + X1 = np.array([[1, 2], [3, 4], [5, 6]]) + X2 = np.array([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]) + # Check that errors are raised if there is not enough samples + (ValueError, next, KFold(4).split(X1)) + + # Check that a warning is raised if the least populated class has too few + # members. + y = np.array([3, 3, -1, -1, 3]) + + skf_3 = StratifiedKFold(3) + 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 + with warnings.catch_warnings(): + 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): + KFold(0) + with pytest.raises(ValueError): + KFold(1) + error_string = "k-fold cross-validation requires at least one train/test split" + with pytest.raises(ValueError, match=error_string): + 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): + KFold(1.5) + with pytest.raises(ValueError): + KFold(2.0) + with pytest.raises(ValueError): + 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): + KFold(n_splits=4, shuffle=None) + + +def test_kfold_indices(): + # Check all indices are returned in the test folds + X1 = np.ones(18) + kf = KFold(3) + check_cv_coverage(kf, X1, y=None, groups=None, expected_n_splits=3) + + # Check all indices are returned in the test folds even when equal-sized + # folds are not possible + X2 = np.ones(17) + kf = KFold(3) + check_cv_coverage(kf, X2, y=None, groups=None, expected_n_splits=3) + + # Check if get_n_splits returns the number of folds + assert 5 == KFold(5).get_n_splits(X2) + + +def test_kfold_no_shuffle(): + # Manually check that KFold preserves the data ordering on toy datasets + X2 = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + + splits = KFold(2).split(X2[:-1]) + train, test = next(splits) + assert_array_equal(test, [0, 1]) + assert_array_equal(train, [2, 3]) + + train, test = next(splits) + assert_array_equal(test, [2, 3]) + assert_array_equal(train, [0, 1]) + + splits = KFold(2).split(X2) + train, test = next(splits) + assert_array_equal(test, [0, 1, 2]) + assert_array_equal(train, [3, 4]) + + train, test = next(splits) + assert_array_equal(test, [3, 4]) + assert_array_equal(train, [0, 1, 2]) + + +def test_stratified_kfold_no_shuffle(): + # Manually check that StratifiedKFold preserves the data ordering as much + # as possible on toy datasets in order to avoid hiding sample dependencies + # when possible + X, y = np.ones(4), [1, 1, 0, 0] + splits = StratifiedKFold(2).split(X, y) + train, test = next(splits) + assert_array_equal(test, [0, 2]) + assert_array_equal(train, [1, 3]) + + train, test = next(splits) + assert_array_equal(test, [1, 3]) + assert_array_equal(train, [0, 2]) + + X, y = np.ones(7), [1, 1, 1, 0, 0, 0, 0] + splits = StratifiedKFold(2).split(X, y) + train, test = next(splits) + assert_array_equal(test, [0, 1, 3, 4]) + assert_array_equal(train, [2, 5, 6]) + + train, test = next(splits) + assert_array_equal(test, [2, 5, 6]) + assert_array_equal(train, [0, 1, 3, 4]) + + # Check if get_n_splits returns the number of folds + assert 5 == StratifiedKFold(5).get_n_splits(X, y) + + # Make sure string labels are also supported + X = np.ones(7) + y1 = ["1", "1", "1", "0", "0", "0", "0"] + y2 = [1, 1, 1, 0, 0, 0, 0] + np.testing.assert_equal( + list(StratifiedKFold(2).split(X, y1)), list(StratifiedKFold(2).split(X, y2)) + ) + + # Check equivalence to KFold + y = [0, 1, 0, 1, 0, 1, 0, 1] + X = np.ones_like(y) + np.testing.assert_equal( + list(StratifiedKFold(3).split(X, y)), list(KFold(3).split(X, y)) + ) + + +@pytest.mark.parametrize("shuffle", [False, True]) +@pytest.mark.parametrize("k", [4, 5, 6, 7, 8, 9, 10]) +@pytest.mark.parametrize("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 + X = np.ones(n_samples) + 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 = kfold(k, random_state=random_state, shuffle=shuffle) + for train, test in _split(skf, 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)) + assert np.ptp(test_sizes) <= 1 + + +@pytest.mark.parametrize("shuffle", [False, True]) +@pytest.mark.parametrize("k", [4, 6, 7]) +@pytest.mark.parametrize("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 _split( + kfold(k, random_state=random_state, shuffle=shuffle), + X, + y, + groups=groups, + ) + ] + + splits_base = get_splits(y) + for perm in permutations([0, 1, 2]): + y_perm = np.take(perm, y) + splits_perm = get_splits(y_perm) + assert splits_perm == splits_base + + +def test_kfold_balance(): + # Check that KFold returns folds with balanced sizes + for i in range(11, 17): + kf = KFold(5).split(X=np.ones(i)) + sizes = [len(test) for _, test in kf] + + assert (np.max(sizes) - np.min(sizes)) <= 1 + assert np.sum(sizes) == i + + +@pytest.mark.parametrize("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 = kfold(3, shuffle=shuffle) + for i in range(11, 17): + skf = _split(cv, X[:i], y[:i], groups[:i]) + sizes = [len(test) for _, test in skf] + + assert (np.max(sizes) - np.min(sizes)) <= 1 + assert np.sum(sizes) == i + + +def test_shuffle_kfold(): + # Check the indices are shuffled properly + kf = KFold(3) + kf2 = KFold(3, shuffle=True, random_state=0) + kf3 = KFold(3, shuffle=True, random_state=1) + + X = np.ones(300) + + all_folds = np.zeros(300) + for (tr1, te1), (tr2, te2), (tr3, te3) in zip( + kf.split(X), kf2.split(X), kf3.split(X) + ): + for tr_a, tr_b in combinations((tr1, tr2, tr3), 2): + # Assert that there is no complete overlap + assert len(np.intersect1d(tr_a, tr_b)) != len(tr1) + + # Set all test indices in successive iterations of kf2 to 1 + all_folds[te2] = 1 + + # Check that all indices are returned in the different test folds + assert sum(all_folds) == 300 + + +@pytest.mark.parametrize("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) + + np.testing.assert_equal( + list(_split(kf, X, y, groups_1)), list(_split(kf, 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)) + 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(_split(kf, *data), _split(kf, *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(): + # Check that shuffling is happening when requested, and for proper + # sample coverage + X_40 = np.ones(40) + y = [0] * 20 + [1] * 20 + kf0 = StratifiedKFold(5, shuffle=True, random_state=0) + kf1 = StratifiedKFold(5, shuffle=True, random_state=1) + for (_, test0), (_, test1) in zip(kf0.split(X_40, y), kf1.split(X_40, y)): + assert set(test0) != set(test1) + check_cv_coverage(kf0, X_40, y, groups=None, expected_n_splits=5) + + # Ensure that we shuffle each class's samples with different + # random_state in StratifiedKFold + # See https://github.com/scikit-learn/scikit-learn/pull/13124 + X = np.arange(10) + y = [0] * 5 + [1] * 5 + kf1 = StratifiedKFold(5, shuffle=True, random_state=0) + kf2 = StratifiedKFold(5, shuffle=True, random_state=1) + test_set1 = sorted([tuple(s[1]) for s in kf1.split(X, y)]) + test_set2 = sorted([tuple(s[1]) for s in kf2.split(X, y)]) + assert test_set1 != test_set2 + + +def test_shuffle_groupkfold(): + # Check that shuffling is happening when requested, and for proper + # sample coverage + X = np.ones(40) + y = [0] * 20 + [1] * 20 + groups = np.arange(40) // 3 + gkf0 = GroupKFold(4, shuffle=True, random_state=0) + gkf1 = GroupKFold(4, shuffle=True, random_state=1) + + # Check that the groups are shuffled differently + test_groups0 = [ + set(groups[test_idx]) for _, test_idx in gkf0.split(X, None, groups) + ] + test_groups1 = [ + set(groups[test_idx]) for _, test_idx in gkf1.split(X, None, groups) + ] + for g0, g1 in zip(test_groups0, test_groups1): + assert g0 != g1, "Test groups should differ with different random states" + + # Check coverage and splits + check_cv_coverage(gkf0, X, y, groups, expected_n_splits=4) + check_cv_coverage(gkf1, X, y, groups, expected_n_splits=4) + + +def test_kfold_can_detect_dependent_samples_on_digits(): # see #2372 + # The digits samples are dependent: they are apparently grouped by authors + # although we don't have any information on the groups segment locations + # for this data. We can highlight this fact by computing k-fold cross- + # validation with and without shuffling: we observe that the shuffling case + # wrongly makes the IID assumption and is therefore too optimistic: it + # estimates a much higher accuracy (around 0.93) than that the non + # shuffling variant (around 0.81). + + X, y = digits.data[:600], digits.target[:600] + model = SVC(C=10, gamma=0.005) + + n_splits = 3 + + cv = KFold(n_splits=n_splits, shuffle=False) + mean_score = cross_val_score(model, X, y, cv=cv).mean() + assert 0.92 > mean_score + assert mean_score > 0.80 + + # Shuffling the data artificially breaks the dependency and hides the + # overfitting of the model with regards to the writing style of the authors + # by yielding a seriously overestimated score: + + cv = KFold(n_splits, shuffle=True, random_state=0) + mean_score = cross_val_score(model, X, y, cv=cv).mean() + assert mean_score > 0.92 + + cv = KFold(n_splits, shuffle=True, random_state=1) + mean_score = cross_val_score(model, X, y, cv=cv).mean() + assert mean_score > 0.92 + + # Similarly, StratifiedKFold should try to shuffle the data as little + # as possible (while respecting the balanced class constraints) + # and thus be able to detect the dependency by not overestimating + # the CV score either. As the digits dataset is approximately balanced + # the estimated mean score is close to the score measured with + # non-shuffled KFold + + cv = StratifiedKFold(n_splits) + mean_score = cross_val_score(model, X, y, cv=cv).mean() + assert 0.94 > mean_score + 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 + + +@pytest.mark.parametrize( + "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([[0.5, 0.5], [0.5, 0.5], [0.5, 0.5]]), + ), + ( + np.array([0] * 9 + [1] * 3), + np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 5, 6]), + np.asarray([[0.75, 0.25], [0.75, 0.25], [0.75, 0.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) + + +@pytest.mark.parametrize("cls_distr", [(0.4, 0.6), (0.3, 0.7), (0.2, 0.8), (0.8, 0.2)]) +@pytest.mark.parametrize("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) + ss3 = ShuffleSplit(test_size=np.int32(2), random_state=0).split(X) + ss4 = ShuffleSplit(test_size=2, random_state=0).split(X) + for t1, t2, t3, t4 in zip(ss1, ss2, ss3, ss4): + assert_array_equal(t1[0], t2[0]) + assert_array_equal(t2[0], t3[0]) + assert_array_equal(t3[0], t4[0]) + assert_array_equal(t1[1], t2[1]) + assert_array_equal(t2[1], t3[1]) + assert_array_equal(t3[1], t4[1]) + + +@pytest.mark.parametrize("split_class", [ShuffleSplit, StratifiedShuffleSplit]) +@pytest.mark.parametrize( + "train_size, exp_train, exp_test", [(None, 9, 1), (8, 8, 2), (0.8, 8, 2)] +) +def test_shuffle_split_default_test_size(split_class, train_size, exp_train, exp_test): + # Check that the default value has the expected behavior, i.e. 0.1 if both + # unspecified or complement train_size unless both are specified. + X = np.ones(10) + y = np.ones(10) + + X_train, X_test = next(split_class(train_size=train_size).split(X, y)) + + assert len(X_train) == exp_train + assert len(X_test) == exp_test + + +@pytest.mark.parametrize( + "train_size, exp_train, exp_test", [(None, 8, 2), (7, 7, 3), (0.7, 7, 3)] +) +def test_group_shuffle_split_default_test_size(train_size, exp_train, exp_test): + # Check that the default value has the expected behavior, i.e. 0.2 if both + # unspecified or complement train_size unless both are specified. + X = np.ones(10) + y = np.ones(10) + groups = range(10) + + X_train, X_test = next(GroupShuffleSplit(train_size=train_size).split(X, y, groups)) + + assert len(X_train) == exp_train + assert len(X_test) == exp_test + + +def test_stratified_shuffle_split_init(): + X = np.arange(7) + y = np.asarray([0, 1, 1, 1, 2, 2, 2]) + # Check that error is raised if there is a class with only one sample + with pytest.raises(ValueError): + next(StratifiedShuffleSplit(3, test_size=0.2).split(X, y)) + + # Check that error is raised if the test set size is smaller than n_classes + with pytest.raises(ValueError): + next(StratifiedShuffleSplit(3, test_size=2).split(X, y)) + # Check that error is raised if the train set size is smaller than + # n_classes + with pytest.raises(ValueError): + next(StratifiedShuffleSplit(3, test_size=3, train_size=2).split(X, y)) + + X = np.arange(9) + y = np.asarray([0, 0, 0, 1, 1, 1, 2, 2, 2]) + + # Train size or test size too small + with pytest.raises(ValueError): + next(StratifiedShuffleSplit(train_size=2).split(X, y)) + with pytest.raises(ValueError): + next(StratifiedShuffleSplit(test_size=2).split(X, y)) + + +def test_stratified_shuffle_split_respects_test_size(): + y = np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2]) + test_size = 5 + train_size = 10 + sss = StratifiedShuffleSplit( + 6, test_size=test_size, train_size=train_size, random_state=0 + ).split(np.ones(len(y)), y) + for train, test in sss: + assert len(train) == train_size + assert len(test) == test_size + + +def test_stratified_shuffle_split_iter(): + ys = [ + np.array([1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3]), + np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3]), + np.array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2] * 2), + np.array([1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4]), + np.array([-1] * 800 + [1] * 50), + np.concatenate([[i] * (100 + i) for i in range(11)]), + [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3], + ["1", "1", "1", "1", "2", "2", "2", "3", "3", "3", "3", "3"], + ] + + for y in ys: + sss = StratifiedShuffleSplit(6, test_size=0.33, random_state=0).split( + np.ones(len(y)), y + ) + y = np.asanyarray(y) # To make it indexable for y[train] + # this is how test-size is computed internally + # in _validate_shuffle_split + test_size = np.ceil(0.33 * len(y)) + train_size = len(y) - test_size + for train, test in sss: + assert_array_equal(np.unique(y[train]), np.unique(y[test])) + # Checks if folds keep classes proportions + p_train = np.bincount(np.unique(y[train], return_inverse=True)[1]) / float( + len(y[train]) + ) + p_test = np.bincount(np.unique(y[test], return_inverse=True)[1]) / float( + len(y[test]) + ) + assert_array_almost_equal(p_train, p_test, 1) + assert len(train) + len(test) == y.size + assert len(train) == train_size + assert len(test) == test_size + assert_array_equal(np.intersect1d(train, test), []) + + +def test_stratified_shuffle_split_even(): + # Test the StratifiedShuffleSplit, indices are drawn with a + # equal chance + n_folds = 5 + n_splits = 1000 + + def assert_counts_are_ok(idx_counts, p): + # Here we test that the distribution of the counts + # per index is close enough to a binomial + threshold = 0.05 / n_splits + bf = stats.binom(n_splits, p) + for count in idx_counts: + prob = bf.pmf(count) + assert prob > threshold, ( + "An index is not drawn with chance corresponding to even draws" + ) + + for n_samples in (6, 22): + groups = np.array((n_samples // 2) * [0, 1]) + splits = StratifiedShuffleSplit( + n_splits=n_splits, test_size=1.0 / n_folds, random_state=0 + ) + + train_counts = [0] * n_samples + test_counts = [0] * n_samples + n_splits_actual = 0 + for train, test in splits.split(X=np.ones(n_samples), y=groups): + n_splits_actual += 1 + for counter, ids in [(train_counts, train), (test_counts, test)]: + for id in ids: + counter[id] += 1 + assert n_splits_actual == n_splits + + n_train, n_test = _validate_shuffle_split( + n_samples, test_size=1.0 / n_folds, train_size=1.0 - (1.0 / n_folds) + ) + + assert len(train) == n_train + assert len(test) == n_test + assert len(set(train).intersection(test)) == 0 + + group_counts = np.unique(groups) + assert splits.test_size == 1.0 / n_folds + assert n_train + n_test == len(groups) + assert len(group_counts) == 2 + ex_test_p = float(n_test) / n_samples + ex_train_p = float(n_train) / n_samples + + assert_counts_are_ok(train_counts, ex_train_p) + assert_counts_are_ok(test_counts, ex_test_p) + + +def test_stratified_shuffle_split_overlap_train_test_bug(): + # See https://github.com/scikit-learn/scikit-learn/issues/6121 for + # the original bug report + y = [0, 1, 2, 3] * 3 + [4, 5] * 5 + X = np.ones_like(y) + + sss = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=0) + + train, test = next(sss.split(X=X, y=y)) + + # no overlap + assert_array_equal(np.intersect1d(train, test), []) + + # complete partition + assert_array_equal(np.union1d(train, test), np.arange(len(y))) + + +def test_stratified_shuffle_split_multilabel(): + # fix for issue 9037 + for y in [ + np.array([[0, 1], [1, 0], [1, 0], [0, 1]]), + np.array([[0, 1], [1, 1], [1, 1], [0, 1]]), + ]: + X = np.ones_like(y) + sss = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=0) + train, test = next(sss.split(X=X, y=y)) + y_train = y[train] + y_test = y[test] + + # no overlap + assert_array_equal(np.intersect1d(train, test), []) + + # complete partition + assert_array_equal(np.union1d(train, test), np.arange(len(y))) + + # correct stratification of entire rows + # (by design, here y[:, 0] uniquely determines the entire row of y) + expected_ratio = np.mean(y[:, 0]) + assert expected_ratio == np.mean(y_train[:, 0]) + assert expected_ratio == np.mean(y_test[:, 0]) + + +def test_stratified_shuffle_split_multilabel_many_labels(): + # fix in PR #9922: for multilabel data with > 1000 labels, str(row) + # truncates with an ellipsis for elements in positions 4 through + # len(row) - 4, so labels were not being correctly split using the powerset + # method for transforming a multilabel problem to a multiclass one; this + # test checks that this problem is fixed. + row_with_many_zeros = [1, 0, 1] + [0] * 1000 + [1, 0, 1] + row_with_many_ones = [1, 0, 1] + [1] * 1000 + [1, 0, 1] + y = np.array([row_with_many_zeros] * 10 + [row_with_many_ones] * 100) + X = np.ones_like(y) + + sss = StratifiedShuffleSplit(n_splits=1, test_size=0.5, random_state=0) + train, test = next(sss.split(X=X, y=y)) + y_train = y[train] + y_test = y[test] + + # correct stratification of entire rows + # (by design, here y[:, 4] uniquely determines the entire row of y) + expected_ratio = np.mean(y[:, 4]) + assert expected_ratio == np.mean(y_train[:, 4]) + assert expected_ratio == np.mean(y_test[:, 4]) + + +def test_predefinedsplit_with_kfold_split(): + # Check that PredefinedSplit can reproduce a split generated by Kfold. + folds = np.full(10, -1.0) + kf_train = [] + kf_test = [] + for i, (train_ind, test_ind) in enumerate(KFold(5, shuffle=True).split(X)): + kf_train.append(train_ind) + kf_test.append(test_ind) + folds[test_ind] = i + ps = PredefinedSplit(folds) + # n_splits is simply the no of unique folds + assert len(np.unique(folds)) == ps.get_n_splits() + ps_train, ps_test = zip(*ps.split()) + assert_array_equal(ps_train, kf_train) + assert_array_equal(ps_test, kf_test) + + +def test_group_shuffle_split(): + for groups_i in test_groups: + X = y = np.ones(len(groups_i)) + n_splits = 6 + test_size = 1.0 / 3 + slo = GroupShuffleSplit(n_splits, test_size=test_size, random_state=0) + + # Make sure the repr works + repr(slo) + + # Test that the length is correct + assert slo.get_n_splits(X, y, groups=groups_i) == n_splits + + l_unique = np.unique(groups_i) + l = np.asarray(groups_i) + + for train, test in slo.split(X, y, groups=groups_i): + # First test: no train group is in the test set and vice versa + l_train_unique = np.unique(l[train]) + l_test_unique = np.unique(l[test]) + assert not np.any(np.isin(l[train], l_test_unique)) + assert not np.any(np.isin(l[test], l_train_unique)) + + # Second test: train and test add up to all the data + assert l[train].size + l[test].size == l.size + + # Third test: train and test are disjoint + assert_array_equal(np.intersect1d(train, test), []) + + # Fourth test: + # unique train and test groups are correct, +- 1 for rounding error + assert abs(len(l_test_unique) - round(test_size * len(l_unique))) <= 1 + assert ( + abs(len(l_train_unique) - round((1.0 - test_size) * len(l_unique))) <= 1 + ) + + +def test_leave_one_p_group_out(): + logo = LeaveOneGroupOut() + lpgo_1 = LeavePGroupsOut(n_groups=1) + lpgo_2 = LeavePGroupsOut(n_groups=2) + + # Make sure the repr works + assert repr(logo) == "LeaveOneGroupOut()" + assert repr(lpgo_1) == "LeavePGroupsOut(n_groups=1)" + assert repr(lpgo_2) == "LeavePGroupsOut(n_groups=2)" + assert repr(LeavePGroupsOut(n_groups=3)) == "LeavePGroupsOut(n_groups=3)" + + for j, (cv, p_groups_out) in enumerate(((logo, 1), (lpgo_1, 1), (lpgo_2, 2))): + for i, groups_i in enumerate(test_groups): + n_groups = len(np.unique(groups_i)) + n_splits = n_groups if p_groups_out == 1 else n_groups * (n_groups - 1) / 2 + X = y = np.ones(len(groups_i)) + + # Test that the length is correct + assert cv.get_n_splits(X, y, groups=groups_i) == n_splits + + groups_arr = np.asarray(groups_i) + + # Split using the original list / array / list of string groups_i + for train, test in cv.split(X, y, groups=groups_i): + # First test: no train group is in the test set and vice versa + assert_array_equal( + np.intersect1d(groups_arr[train], groups_arr[test]).tolist(), [] + ) + + # Second test: train and test add up to all the data + assert len(train) + len(test) == len(groups_i) + + # Third test: + # The number of groups in test must be equal to p_groups_out + assert np.unique(groups_arr[test]).shape[0], p_groups_out + + # check get_n_splits() with dummy parameters + assert logo.get_n_splits(None, None, ["a", "b", "c", "b", "c"]) == 3 + assert logo.get_n_splits(groups=[1.0, 1.1, 1.0, 1.2]) == 3 + assert lpgo_2.get_n_splits(None, None, np.arange(4)) == 6 + assert lpgo_1.get_n_splits(groups=np.arange(4)) == 4 + + # raise ValueError if a `groups` parameter is illegal + with pytest.raises(ValueError): + logo.get_n_splits(None, None, [0.0, np.nan, 0.0]) + with pytest.raises(ValueError): + lpgo_2.get_n_splits(None, None, [0.0, np.inf, 0.0]) + + msg = "The 'groups' parameter should not be None." + with pytest.raises(ValueError, match=msg): + logo.get_n_splits(None, None, None) + with pytest.raises(ValueError, match=msg): + lpgo_1.get_n_splits(None, None, None) + + +def test_leave_group_out_changing_groups(): + # Check that LeaveOneGroupOut and LeavePGroupsOut work normally if + # the groups variable is changed before calling split + groups = np.array([0, 1, 2, 1, 1, 2, 0, 0]) + X = np.ones(len(groups)) + groups_changing = np.array(groups, copy=True) + lolo = LeaveOneGroupOut().split(X, groups=groups) + lolo_changing = LeaveOneGroupOut().split(X, groups=groups) + lplo = LeavePGroupsOut(n_groups=2).split(X, groups=groups) + lplo_changing = LeavePGroupsOut(n_groups=2).split(X, groups=groups) + groups_changing[:] = 0 + for llo, llo_changing in [(lolo, lolo_changing), (lplo, lplo_changing)]: + for (train, test), (train_chan, test_chan) in zip(llo, llo_changing): + assert_array_equal(train, train_chan) + assert_array_equal(test, test_chan) + + # n_splits = no of 2 (p) group combinations of the unique groups = 3C2 = 3 + assert 3 == LeavePGroupsOut(n_groups=2).get_n_splits(X, y=X, groups=groups) + # n_splits = no of unique groups (C(uniq_lbls, 1) = n_unique_groups) + assert 3 == LeaveOneGroupOut().get_n_splits(X, y=X, groups=groups) + + +def test_leave_group_out_order_dependence(): + # Check that LeaveOneGroupOut orders the splits according to the index + # of the group left out. + groups = np.array([2, 2, 0, 0, 1, 1]) + X = np.ones(len(groups)) + + splits = iter(LeaveOneGroupOut().split(X, groups=groups)) + + expected_indices = [ + ([0, 1, 4, 5], [2, 3]), + ([0, 1, 2, 3], [4, 5]), + ([2, 3, 4, 5], [0, 1]), + ] + + for expected_train, expected_test in expected_indices: + train, test = next(splits) + assert_array_equal(train, expected_train) + assert_array_equal(test, expected_test) + + +def test_leave_one_p_group_out_error_on_fewer_number_of_groups(): + X = y = groups = np.ones(0) + msg = re.escape("Found array with 0 sample(s)") + with pytest.raises(ValueError, match=msg): + next(LeaveOneGroupOut().split(X, y, groups)) + + X = y = groups = np.ones(1) + msg = re.escape( + f"The groups parameter contains fewer than 2 unique groups ({groups})." + " LeaveOneGroupOut expects at least 2." + ) + with pytest.raises(ValueError, match=msg): + next(LeaveOneGroupOut().split(X, y, groups)) + + X = y = groups = np.ones(1) + msg = re.escape( + "The groups parameter contains fewer than (or equal to) n_groups " + f"(3) numbers of unique groups ({groups}). LeavePGroupsOut expects " + "that at least n_groups + 1 (4) unique groups " + "be present" + ) + with pytest.raises(ValueError, match=msg): + next(LeavePGroupsOut(n_groups=3).split(X, y, groups)) + + X = y = groups = np.arange(3) + msg = re.escape( + "The groups parameter contains fewer than (or equal to) n_groups " + f"(3) numbers of unique groups ({groups}). LeavePGroupsOut expects " + "that at least n_groups + 1 (4) unique groups " + "be present" + ) + with pytest.raises(ValueError, match=msg): + next(LeavePGroupsOut(n_groups=3).split(X, y, groups)) + + +def test_repeated_cv_value_errors(): + # n_repeats is not integer or <= 0 + for cv in (RepeatedKFold, RepeatedStratifiedKFold): + with pytest.raises(ValueError): + cv(n_repeats=0) + with pytest.raises(ValueError): + cv(n_repeats=1.5) + + +@pytest.mark.parametrize("RepeatedCV", [RepeatedKFold, RepeatedStratifiedKFold]) +def test_repeated_cv_repr(RepeatedCV): + n_splits, n_repeats = 2, 6 + repeated_cv = RepeatedCV(n_splits=n_splits, n_repeats=n_repeats) + repeated_cv_repr = "{}(n_repeats=6, n_splits=2, random_state=None)".format( + repeated_cv.__class__.__name__ + ) + assert repeated_cv_repr == repr(repeated_cv) + + +def test_repeated_kfold_determinstic_split(): + X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + random_state = 258173307 + rkf = RepeatedKFold(n_splits=2, n_repeats=2, random_state=random_state) + + # split should produce same and deterministic splits on + # each call + for _ in range(3): + splits = rkf.split(X) + train, test = next(splits) + assert_array_equal(train, [2, 4]) + assert_array_equal(test, [0, 1, 3]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 3]) + assert_array_equal(test, [2, 4]) + + train, test = next(splits) + assert_array_equal(train, [0, 1]) + assert_array_equal(test, [2, 3, 4]) + + train, test = next(splits) + assert_array_equal(train, [2, 3, 4]) + assert_array_equal(test, [0, 1]) + + with pytest.raises(StopIteration): + next(splits) + + +def test_get_n_splits_for_repeated_kfold(): + n_splits = 3 + n_repeats = 4 + rkf = RepeatedKFold(n_splits=n_splits, n_repeats=n_repeats) + expected_n_splits = n_splits * n_repeats + assert expected_n_splits == rkf.get_n_splits() + + +def test_get_n_splits_for_repeated_stratified_kfold(): + n_splits = 3 + n_repeats = 4 + rskf = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=n_repeats) + expected_n_splits = n_splits * n_repeats + assert expected_n_splits == rskf.get_n_splits() + + +def test_repeated_stratified_kfold_determinstic_split(): + X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] + y = [1, 1, 1, 0, 0] + random_state = 1944695409 + rskf = RepeatedStratifiedKFold(n_splits=2, n_repeats=2, random_state=random_state) + + # split should produce same and deterministic splits on + # each call + for _ in range(3): + splits = rskf.split(X, y) + train, test = next(splits) + assert_array_equal(train, [1, 4]) + assert_array_equal(test, [0, 2, 3]) + + train, test = next(splits) + assert_array_equal(train, [0, 2, 3]) + assert_array_equal(test, [1, 4]) + + train, test = next(splits) + assert_array_equal(train, [2, 3]) + assert_array_equal(test, [0, 1, 4]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 4]) + assert_array_equal(test, [2, 3]) + + with pytest.raises(StopIteration): + next(splits) + + +def test_train_test_split_errors(): + pytest.raises(ValueError, train_test_split) + + pytest.raises(ValueError, train_test_split, range(3), train_size=1.1) + + pytest.raises(ValueError, train_test_split, range(3), test_size=0.6, train_size=0.6) + pytest.raises( + ValueError, + train_test_split, + range(3), + test_size=np.float32(0.6), + train_size=np.float32(0.6), + ) + pytest.raises(ValueError, train_test_split, range(3), test_size="wrong_type") + pytest.raises(ValueError, train_test_split, range(3), test_size=2, train_size=4) + pytest.raises(TypeError, train_test_split, range(3), some_argument=1.1) + pytest.raises(ValueError, train_test_split, range(3), range(42)) + pytest.raises(ValueError, train_test_split, range(10), shuffle=False, stratify=True) + + with pytest.raises( + ValueError, + match=r"train_size=11 should be either positive and " + r"smaller than the number of samples 10 or a " + r"float in the \(0, 1\) range", + ): + train_test_split(range(10), train_size=11, test_size=1) + + +@pytest.mark.parametrize( + "train_size, exp_train, exp_test", [(None, 7, 3), (8, 8, 2), (0.8, 8, 2)] +) +def test_train_test_split_default_test_size(train_size, exp_train, exp_test): + # Check that the default value has the expected behavior, i.e. complement + # train_size unless both are specified. + X_train, X_test = train_test_split(X, train_size=train_size) + + assert len(X_train) == exp_train + assert len(X_test) == exp_test + + +@pytest.mark.parametrize( + "array_namespace, device, dtype_name", + yield_namespace_device_dtype_combinations(), + ids=_get_namespace_device_dtype_ids, +) +@pytest.mark.parametrize( + "shuffle,stratify", + ( + (True, None), + (True, np.hstack((np.ones(6), np.zeros(4)))), + # stratification only works with shuffling + (False, None), + ), +) +def test_array_api_train_test_split( + shuffle, stratify, array_namespace, device, dtype_name +): + xp = _array_api_for_tests(array_namespace, device) + + X = np.arange(100).reshape((10, 10)) + y = np.arange(10) + + X_np = X.astype(dtype_name) + X_xp = xp.asarray(X_np, device=device) + + y_np = y.astype(dtype_name) + y_xp = xp.asarray(y_np, device=device) + + X_train_np, X_test_np, y_train_np, y_test_np = train_test_split( + X_np, y, random_state=0, shuffle=shuffle, stratify=stratify + ) + with config_context(array_api_dispatch=True): + if stratify is not None: + stratify_xp = xp.asarray(stratify) + else: + stratify_xp = stratify + X_train_xp, X_test_xp, y_train_xp, y_test_xp = train_test_split( + X_xp, y_xp, shuffle=shuffle, stratify=stratify_xp, random_state=0 + ) + + # Check that namespace is preserved, has to happen with + # array_api_dispatch enabled. + assert get_namespace(X_train_xp)[0] == get_namespace(X_xp)[0] + assert get_namespace(X_test_xp)[0] == get_namespace(X_xp)[0] + assert get_namespace(y_train_xp)[0] == get_namespace(y_xp)[0] + assert get_namespace(y_test_xp)[0] == get_namespace(y_xp)[0] + + # Check device and dtype is preserved on output + assert array_api_device(X_train_xp) == array_api_device(X_xp) + assert array_api_device(y_train_xp) == array_api_device(y_xp) + assert array_api_device(X_test_xp) == array_api_device(X_xp) + assert array_api_device(y_test_xp) == array_api_device(y_xp) + + assert X_train_xp.dtype == X_xp.dtype + assert y_train_xp.dtype == y_xp.dtype + assert X_test_xp.dtype == X_xp.dtype + assert y_test_xp.dtype == y_xp.dtype + + assert_allclose( + _convert_to_numpy(X_train_xp, xp=xp), + X_train_np, + ) + assert_allclose( + _convert_to_numpy(X_test_xp, xp=xp), + X_test_np, + ) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_train_test_split(coo_container): + X = np.arange(100).reshape((10, 10)) + X_s = coo_container(X) + y = np.arange(10) + + # simple test + split = train_test_split(X, y, test_size=None, train_size=0.5) + X_train, X_test, y_train, y_test = split + assert len(y_test) == len(y_train) + # test correspondence of X and y + assert_array_equal(X_train[:, 0], y_train * 10) + assert_array_equal(X_test[:, 0], y_test * 10) + + # don't convert lists to anything else by default + split = train_test_split(X, X_s, y.tolist()) + X_train, X_test, X_s_train, X_s_test, y_train, y_test = split + assert isinstance(y_train, list) + assert isinstance(y_test, list) + + # allow nd-arrays + X_4d = np.arange(10 * 5 * 3 * 2).reshape(10, 5, 3, 2) + y_3d = np.arange(10 * 7 * 11).reshape(10, 7, 11) + split = train_test_split(X_4d, y_3d) + assert split[0].shape == (7, 5, 3, 2) + assert split[1].shape == (3, 5, 3, 2) + assert split[2].shape == (7, 7, 11) + assert split[3].shape == (3, 7, 11) + + # test stratification option + y = np.array([1, 1, 1, 1, 2, 2, 2, 2]) + for test_size, exp_test_size in zip([2, 4, 0.25, 0.5, 0.75], [2, 4, 2, 4, 6]): + train, test = train_test_split( + y, test_size=test_size, stratify=y, random_state=0 + ) + assert len(test) == exp_test_size + assert len(test) + len(train) == len(y) + # check the 1:1 ratio of ones and twos in the data is preserved + assert np.sum(train == 1) == np.sum(train == 2) + + # test unshuffled split + y = np.arange(10) + for test_size in [2, 0.2]: + train, test = train_test_split(y, shuffle=False, test_size=test_size) + assert_array_equal(test, [8, 9]) + assert_array_equal(train, [0, 1, 2, 3, 4, 5, 6, 7]) + + +def test_train_test_split_32bit_overflow(): + """Check for integer overflow on 32-bit platforms. + + Non-regression test for: + https://github.com/scikit-learn/scikit-learn/issues/20774 + """ + + # A number 'n' big enough for expression 'n * n * train_size' to cause + # an overflow for signed 32-bit integer + big_number = 100000 + + # Definition of 'y' is a part of reproduction - population for at least + # one class should be in the same order of magnitude as size of X + X = np.arange(big_number) + y = X > (0.99 * big_number) + + split = train_test_split(X, y, stratify=y, train_size=0.25) + X_train, X_test, y_train, y_test = split + + assert X_train.size + X_test.size == big_number + assert y_train.size + y_test.size == big_number + + +def test_train_test_split_pandas(): + # check train_test_split doesn't destroy pandas dataframe + types = [MockDataFrame] + try: + from pandas import DataFrame + + types.append(DataFrame) + except ImportError: + pass + for InputFeatureType in types: + # X dataframe + X_df = InputFeatureType(X) + X_train, X_test = train_test_split(X_df) + assert isinstance(X_train, InputFeatureType) + assert isinstance(X_test, InputFeatureType) + + +@pytest.mark.parametrize( + "sparse_container", COO_CONTAINERS + CSC_CONTAINERS + CSR_CONTAINERS +) +def test_train_test_split_sparse(sparse_container): + # check that train_test_split converts scipy sparse matrices + # to csr, as stated in the documentation + X = np.arange(100).reshape((10, 10)) + X_s = sparse_container(X) + X_train, X_test = train_test_split(X_s) + assert issparse(X_train) and X_train.format == "csr" + assert issparse(X_test) and X_test.format == "csr" + + +def test_train_test_split_mock_pandas(): + # X mock dataframe + X_df = MockDataFrame(X) + X_train, X_test = train_test_split(X_df) + assert isinstance(X_train, MockDataFrame) + assert isinstance(X_test, MockDataFrame) + X_train_arr, X_test_arr = train_test_split(X_df) + + +def test_train_test_split_list_input(): + # Check that when y is a list / list of string labels, it works. + X = np.ones(7) + y1 = ["1"] * 4 + ["0"] * 3 + y2 = np.hstack((np.ones(4), np.zeros(3))) + y3 = y2.tolist() + + for stratify in (True, False): + X_train1, X_test1, y_train1, y_test1 = train_test_split( + X, y1, stratify=y1 if stratify else None, random_state=0 + ) + X_train2, X_test2, y_train2, y_test2 = train_test_split( + X, y2, stratify=y2 if stratify else None, random_state=0 + ) + X_train3, X_test3, y_train3, y_test3 = train_test_split( + X, y3, stratify=y3 if stratify else None, random_state=0 + ) + + np.testing.assert_equal(X_train1, X_train2) + np.testing.assert_equal(y_train2, y_train3) + np.testing.assert_equal(X_test1, X_test3) + np.testing.assert_equal(y_test3, y_test2) + + +@pytest.mark.parametrize( + "test_size, train_size", + [(2.0, None), (1.0, None), (0.1, 0.95), (None, 1j), (11, None), (10, None), (8, 3)], +) +def test_shufflesplit_errors(test_size, train_size): + with pytest.raises(ValueError): + next(ShuffleSplit(test_size=test_size, train_size=train_size).split(X)) + + +def test_shufflesplit_reproducible(): + # Check that iterating twice on the ShuffleSplit gives the same + # sequence of train-test when the random_state is given + ss = ShuffleSplit(random_state=21) + assert_array_equal([a for a, b in ss.split(X)], [a for a, b in ss.split(X)]) + + +def test_stratifiedshufflesplit_list_input(): + # Check that when y is a list / list of string labels, it works. + sss = StratifiedShuffleSplit(test_size=2, random_state=42) + X = np.ones(7) + y1 = ["1"] * 4 + ["0"] * 3 + y2 = np.hstack((np.ones(4), np.zeros(3))) + y3 = y2.tolist() + + np.testing.assert_equal(list(sss.split(X, y1)), list(sss.split(X, y2))) + np.testing.assert_equal(list(sss.split(X, y3)), list(sss.split(X, y2))) + + +def test_train_test_split_allow_nans(): + # Check that train_test_split allows input data with NaNs + X = np.arange(200, dtype=np.float64).reshape(10, -1) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + train_test_split(X, y, test_size=0.2, random_state=42) + + +def test_check_cv(): + X = np.ones(9) + cv = check_cv(3, classifier=False) + # Use numpy.testing.assert_equal which recursively compares + # lists of lists + np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X))) + + y_binary = np.array([0, 1, 0, 1, 0, 0, 1, 1, 1]) + cv = check_cv(3, y_binary, classifier=True) + np.testing.assert_equal( + list(StratifiedKFold(3).split(X, y_binary)), list(cv.split(X, y_binary)) + ) + + y_multiclass = np.array([0, 1, 0, 1, 2, 1, 2, 0, 2]) + cv = check_cv(3, y_multiclass, classifier=True) + np.testing.assert_equal( + list(StratifiedKFold(3).split(X, y_multiclass)), list(cv.split(X, y_multiclass)) + ) + # also works with 2d multiclass + y_multiclass_2d = y_multiclass.reshape(-1, 1) + cv = check_cv(3, y_multiclass_2d, classifier=True) + np.testing.assert_equal( + list(StratifiedKFold(3).split(X, y_multiclass_2d)), + list(cv.split(X, y_multiclass_2d)), + ) + + assert not np.all( + next(StratifiedKFold(3).split(X, y_multiclass_2d))[0] + == next(KFold(3).split(X, y_multiclass_2d))[0] + ) + + X = np.ones(5) + y_multilabel = np.array( + [[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 1], [0, 0, 1, 0]] + ) + cv = check_cv(3, y_multilabel, classifier=True) + np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X))) + + y_multioutput = np.array([[1, 2], [0, 3], [0, 0], [3, 1], [2, 0]]) + cv = check_cv(3, y_multioutput, classifier=True) + np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X))) + + with pytest.raises(ValueError): + check_cv(cv="lolo") + + +def test_cv_iterable_wrapper(): + kf_iter = KFold().split(X, y) + kf_iter_wrapped = check_cv(kf_iter) + # Since the wrapped iterable is enlisted and stored, + # split can be called any number of times to produce + # consistent results. + np.testing.assert_equal( + list(kf_iter_wrapped.split(X, y)), list(kf_iter_wrapped.split(X, y)) + ) + # If the splits are randomized, successive calls to split yields different + # results + kf_randomized_iter = KFold(shuffle=True, random_state=0).split(X, y) + kf_randomized_iter_wrapped = check_cv(kf_randomized_iter) + # numpy's assert_array_equal properly compares nested lists + np.testing.assert_equal( + list(kf_randomized_iter_wrapped.split(X, y)), + list(kf_randomized_iter_wrapped.split(X, y)), + ) + + try: + splits_are_equal = True + np.testing.assert_equal( + list(kf_iter_wrapped.split(X, y)), + list(kf_randomized_iter_wrapped.split(X, y)), + ) + except AssertionError: + splits_are_equal = False + assert not splits_are_equal, ( + "If the splits are randomized, " + "successive calls to split should yield different results" + ) + + +@pytest.mark.parametrize("kfold", [GroupKFold, StratifiedGroupKFold]) +@pytest.mark.parametrize("shuffle", [True, False]) +def test_group_kfold(kfold, shuffle, global_random_seed): + rng = np.random.RandomState(global_random_seed) + + # Parameters of the test + n_groups = 15 + n_samples = 1000 + n_splits = 5 + + X = y = np.ones(n_samples) + + # Construct the test data + tolerance = 0.05 * n_samples # 5 percent error allowed + groups = rng.randint(0, n_groups, n_samples) + + ideal_n_groups_per_fold = n_samples // n_splits + + len(np.unique(groups)) + # Get the test fold indices from the test set indices of each fold + folds = np.zeros(n_samples) + random_state = None if not shuffle else global_random_seed + lkf = kfold(n_splits=n_splits, shuffle=shuffle, random_state=random_state) + for i, (_, test) in enumerate(lkf.split(X, y, groups)): + folds[test] = i + + # Check that folds have approximately the same size + assert len(folds) == len(groups) + for i in np.unique(folds): + assert tolerance >= abs(sum(folds == i) - ideal_n_groups_per_fold) + + # Check that each group appears only in 1 fold + for group in np.unique(groups): + assert len(np.unique(folds[groups == group])) == 1 + + # Check that no group is on both sides of the split + groups = np.asarray(groups, dtype=object) + for train, test in lkf.split(X, y, groups): + assert len(np.intersect1d(groups[train], groups[test])) == 0 + + # Construct the test data + groups = np.array( + [ + "Albert", + "Jean", + "Bertrand", + "Michel", + "Jean", + "Francis", + "Robert", + "Michel", + "Rachel", + "Lois", + "Michelle", + "Bernard", + "Marion", + "Laura", + "Jean", + "Rachel", + "Franck", + "John", + "Gael", + "Anna", + "Alix", + "Robert", + "Marion", + "David", + "Tony", + "Abel", + "Becky", + "Madmood", + "Cary", + "Mary", + "Alexandre", + "David", + "Francis", + "Barack", + "Abdoul", + "Rasha", + "Xi", + "Silvia", + ] + ) + + n_groups = len(np.unique(groups)) + n_samples = len(groups) + n_splits = 5 + tolerance = 0.05 * n_samples # 5 percent error allowed + ideal_n_groups_per_fold = n_samples // n_splits + + X = y = np.ones(n_samples) + + # Get the test fold indices from the test set indices of each fold + folds = np.zeros(n_samples) + for i, (_, test) in enumerate(lkf.split(X, y, groups)): + folds[test] = i + + # Check that folds have approximately the same size + assert len(folds) == len(groups) + if not shuffle: + for i in np.unique(folds): + assert tolerance >= abs(sum(folds == i) - ideal_n_groups_per_fold) + + # Check that each group appears only in 1 fold + with warnings.catch_warnings(): + warnings.simplefilter("ignore", FutureWarning) + for group in np.unique(groups): + assert len(np.unique(folds[groups == group])) == 1 + + # Check that no group is on both sides of the split + groups = np.asarray(groups, dtype=object) + for train, test in lkf.split(X, y, groups): + assert len(np.intersect1d(groups[train], groups[test])) == 0 + + # groups can also be a list + # use a new instance for reproducibility when shuffle=True + lkf_copy = kfold(n_splits=n_splits, shuffle=shuffle, random_state=random_state) + cv_iter = list(lkf.split(X, y, groups.tolist())) + for (train1, test1), (train2, test2) in zip(lkf_copy.split(X, y, groups), cv_iter): + assert_array_equal(train1, train2) + assert_array_equal(test1, test2) + + # Should fail if there are more folds than groups + groups = np.array([1, 1, 1, 2, 2]) + X = y = np.ones(len(groups)) + with pytest.raises(ValueError, match="Cannot have number of splits.*greater"): + next(GroupKFold(n_splits=3).split(X, y, groups)) + + +def test_time_series_cv(): + X = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [13, 14]] + + # Should fail if there are more folds than samples + with pytest.raises(ValueError, match="Cannot have number of folds.*greater"): + next(TimeSeriesSplit(n_splits=7).split(X)) + + tscv = TimeSeriesSplit(2) + + # Manually check that Time Series CV preserves the data + # ordering on toy datasets + splits = tscv.split(X[:-1]) + train, test = next(splits) + assert_array_equal(train, [0, 1]) + assert_array_equal(test, [2, 3]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3]) + assert_array_equal(test, [4, 5]) + + splits = TimeSeriesSplit(2).split(X) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2]) + assert_array_equal(test, [3, 4]) + + train, test = next(splits) + assert_array_equal(train, [0, 1, 2, 3, 4]) + assert_array_equal(test, [5, 6]) + + # Check get_n_splits returns the correct number of splits + splits = TimeSeriesSplit(2).split(X) + n_splits_actual = len(list(splits)) + assert n_splits_actual == tscv.get_n_splits() + assert n_splits_actual == 2 + + +def _check_time_series_max_train_size(splits, check_splits, max_train_size): + for (train, test), (check_train, check_test) in zip(splits, check_splits): + assert_array_equal(test, check_test) + assert len(check_train) <= max_train_size + suffix_start = max(len(train) - max_train_size, 0) + assert_array_equal(check_train, train[suffix_start:]) + + +def test_time_series_max_train_size(): + X = np.zeros((6, 1)) + splits = TimeSeriesSplit(n_splits=3).split(X) + check_splits = TimeSeriesSplit(n_splits=3, max_train_size=3).split(X) + _check_time_series_max_train_size(splits, check_splits, max_train_size=3) + + # Test for the case where the size of a fold is greater than max_train_size + check_splits = TimeSeriesSplit(n_splits=3, max_train_size=2).split(X) + _check_time_series_max_train_size(splits, check_splits, max_train_size=2) + + # Test for the case where the size of each fold is less than max_train_size + check_splits = TimeSeriesSplit(n_splits=3, max_train_size=5).split(X) + _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) + + +@ignore_warnings +def test_nested_cv(): + # Test if nested cross validation works with different combinations of cv + rng = np.random.RandomState(0) + + X, y = make_classification(n_samples=15, n_classes=2, random_state=0) + groups = rng.randint(0, 5, 15) + + cvs = [ + LeaveOneGroupOut(), + StratifiedKFold(n_splits=2), + LeaveOneOut(), + GroupKFold(n_splits=3), + StratifiedKFold(), + StratifiedGroupKFold(), + StratifiedShuffleSplit(n_splits=3, random_state=0), + ] + + for inner_cv, outer_cv in combinations_with_replacement(cvs, 2): + gs = GridSearchCV( + DummyClassifier(), + param_grid={"strategy": ["stratified", "most_frequent"]}, + cv=inner_cv, + error_score="raise", + ) + cross_val_score( + gs, X=X, y=y, groups=groups, cv=outer_cv, params={"groups": groups} + ) + + +def test_build_repr(): + class MockSplitter: + def __init__(self, a, b=0, c=None): + self.a = a + self.b = b + self.c = c + + def __repr__(self): + return _build_repr(self) + + assert repr(MockSplitter(5, 6)) == "MockSplitter(a=5, b=6, c=None)" + + +@pytest.mark.parametrize( + "CVSplitter", (ShuffleSplit, GroupShuffleSplit, StratifiedShuffleSplit) +) +def test_shuffle_split_empty_trainset(CVSplitter): + cv = CVSplitter(test_size=0.99) + X, y = [[1]], [0] # 1 sample + with pytest.raises( + ValueError, + match=( + "With n_samples=1, test_size=0.99 and train_size=None, " + "the resulting train set will be empty" + ), + ): + next(_split(cv, X, y, groups=[1])) + + +def test_train_test_split_empty_trainset(): + (X,) = [[1]] # 1 sample + with pytest.raises( + ValueError, + match=( + "With n_samples=1, test_size=0.99 and train_size=None, " + "the resulting train set will be empty" + ), + ): + train_test_split(X, test_size=0.99) + + X = [[1], [1], [1]] # 3 samples, ask for more than 2 thirds + with pytest.raises( + ValueError, + match=( + "With n_samples=3, test_size=0.67 and train_size=None, " + "the resulting train set will be empty" + ), + ): + train_test_split(X, test_size=0.67) + + +def test_leave_one_out_empty_trainset(): + # LeaveOneGroup out expect at least 2 groups so no need to check + cv = LeaveOneOut() + X, y = [[1]], [0] # 1 sample + with pytest.raises(ValueError, match="Cannot perform LeaveOneOut with n_samples=1"): + next(cv.split(X, y)) + + +def test_leave_p_out_empty_trainset(): + # No need to check LeavePGroupsOut + cv = LeavePOut(p=2) + X, y = [[1], [2]], [0, 3] # 2 samples + with pytest.raises( + ValueError, match="p=2 must be strictly less than the number of samples=2" + ): + next(cv.split(X, y)) + + +@pytest.mark.parametrize( + "Klass", (KFold, StratifiedKFold, StratifiedGroupKFold, GroupKFold) +) +def test_random_state_shuffle_false(Klass): + # passing a non-default random_state when shuffle=False makes no sense + with pytest.raises(ValueError, match="has no effect since shuffle is False"): + Klass(3, shuffle=False, random_state=0) + + +@pytest.mark.parametrize( + "cv, expected", + [ + (KFold(), True), + (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), + (GroupShuffleSplit(random_state=123), True), + (StratifiedShuffleSplit(random_state=123), True), + (GroupKFold(), True), + (GroupKFold(shuffle=True, random_state=123), 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 + + +@pytest.mark.parametrize("cv", ALL_SPLITTERS, ids=[str(cv) for cv in ALL_SPLITTERS]) +def test_splitter_get_metadata_routing(cv): + """Check get_metadata_routing returns the correct MetadataRouter.""" + assert hasattr(cv, "get_metadata_routing") + metadata = cv.get_metadata_routing() + if cv in GROUP_SPLITTERS: + assert metadata.split.requests["groups"] is True + elif cv in NO_GROUP_SPLITTERS: + assert not metadata.split.requests + + assert_request_is_empty(metadata, exclude=["split"]) + + +@pytest.mark.parametrize("cv", ALL_SPLITTERS, ids=[str(cv) for cv in ALL_SPLITTERS]) +def test_splitter_set_split_request(cv): + """Check set_split_request is defined for group splitters and not for others.""" + if cv in GROUP_SPLITTERS: + assert hasattr(cv, "set_split_request") + elif cv in NO_GROUP_SPLITTERS: + assert not hasattr(cv, "set_split_request") + + +@pytest.mark.parametrize("cv", NO_GROUP_SPLITTERS, ids=str) +def test_no_group_splitters_warns_with_groups(cv): + msg = f"The groups parameter is ignored by {cv.__class__.__name__}" + + n_samples = 30 + rng = np.random.RandomState(1) + X = rng.randint(0, 3, size=(n_samples, 2)) + y = rng.randint(0, 3, size=(n_samples,)) + groups = rng.randint(0, 3, size=(n_samples,)) + + with pytest.warns(UserWarning, match=msg): + cv.split(X, y, groups=groups) + + +@pytest.mark.parametrize( + "cv", SPLITTERS_REQUIRING_TARGET, ids=[str(cv) for cv in SPLITTERS_REQUIRING_TARGET] +) +def test_stratified_splitter_without_y(cv): + msg = "missing 1 required positional argument: 'y'" + with pytest.raises(TypeError, match=msg): + cv.split(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py new file mode 100644 index 0000000000000000000000000000000000000000..bdfab45b4f7ca337ce7e3ce92df517a00bc42a8e --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_successive_halving.py @@ -0,0 +1,853 @@ +from math import ceil + +import numpy as np +import pytest +from scipy.stats import expon, norm, randint + +from sklearn.datasets import make_classification +from sklearn.dummy import DummyClassifier +from sklearn.experimental import enable_halving_search_cv # noqa: F401 +from sklearn.model_selection import ( + GroupKFold, + GroupShuffleSplit, + HalvingGridSearchCV, + HalvingRandomSearchCV, + KFold, + LeaveOneGroupOut, + LeavePGroupsOut, + ShuffleSplit, + StratifiedKFold, + StratifiedShuffleSplit, +) +from sklearn.model_selection._search_successive_halving import ( + _SubsampleMetaSplitter, + _top_k, +) +from sklearn.model_selection.tests.test_search import ( + check_cv_results_array_types, + check_cv_results_keys, +) +from sklearn.svm import SVC, LinearSVC + + +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.""" + + # update the constraints such that we accept all parameters from a to z + _parameter_constraints: dict = { + **DummyClassifier._parameter_constraints, + **{chr(key): "no_validation" for key in range(ord("a"), ord("z") + 1)}, + } + + 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 + + +class SometimesFailClassifier(DummyClassifier): + def __init__( + self, + strategy="stratified", + random_state=None, + constant=None, + n_estimators=10, + fail_fit=False, + fail_predict=False, + a=0, + ): + self.fail_fit = fail_fit + self.fail_predict = fail_predict + self.n_estimators = n_estimators + self.a = a + + super().__init__( + strategy=strategy, random_state=random_state, constant=constant + ) + + def fit(self, X, y): + if self.fail_fit: + raise Exception("fitting failed") + return super().fit(X, y) + + def predict(self, X): + if self.fail_predict: + raise Exception("predict failed") + return super().predict(X) + + +@pytest.mark.filterwarnings("ignore::sklearn.exceptions.FitFailedWarning") +@pytest.mark.filterwarnings("ignore:Scoring failed:UserWarning") +@pytest.mark.filterwarnings("ignore:One or more of the:UserWarning") +@pytest.mark.parametrize("HalvingSearch", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize("fail_at", ("fit", "predict")) +def test_nan_handling(HalvingSearch, fail_at): + """Check the selection of the best scores in presence of failure represented by + NaN values.""" + n_samples = 1_000 + X, y = make_classification(n_samples=n_samples, random_state=0) + + search = HalvingSearch( + SometimesFailClassifier(), + {f"fail_{fail_at}": [False, True], "a": range(3)}, + resource="n_estimators", + max_resources=6, + min_resources=1, + factor=2, + ) + + search.fit(X, y) + + # estimators that failed during fit/predict should always rank lower + # than ones where the fit/predict succeeded + assert not search.best_params_[f"fail_{fail_at}"] + scores = search.cv_results_["mean_test_score"] + ranks = search.cv_results_["rank_test_score"] + + # some scores should be NaN + assert np.isnan(scores).any() + + unique_nan_ranks = np.unique(ranks[np.isnan(scores)]) + # all NaN scores should have the same rank + assert unique_nan_ranks.shape[0] == 1 + # NaNs should have the lowest rank + assert (unique_nan_ranks[0] >= ranks).all() + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + ( + "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_ + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + ( + "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_) + + +@pytest.mark.parametrize("Est", (HalvingRandomSearchCV, HalvingGridSearchCV)) +@pytest.mark.parametrize( + "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 + + +@pytest.mark.parametrize("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) + + +@pytest.mark.parametrize( + "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 + + +@pytest.mark.parametrize( + "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 + # development 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 + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +@pytest.mark.parametrize( + "params, expected_error_message", + [ + ( + {"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": "auto", "resource": "b"}, + "resource can only be 'n_samples' when max_resources='auto'", + ), + ( + {"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) + + +@pytest.mark.parametrize( + "params, expected_error_message", + [ + ( + {"n_candidates": "exhaust", "min_resources": "exhaust"}, + "cannot be both set to 'exhaust'", + ), + ], +) +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) + + +@pytest.mark.parametrize( + "fraction, subsample_test, expected_train_size, expected_test_size", + [ + (0.5, True, 40, 10), + (0.5, False, 40, 20), + (0.2, True, 16, 4), + (0.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() + + +@pytest.mark.parametrize("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=0.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]) + + +@pytest.mark.parametrize( + "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) + + +@pytest.mark.parametrize("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) + + # non-regression check for + # https://github.com/scikit-learn/scikit-learn/issues/19203 + assert isinstance(sh.cv_results_["iter"], np.ndarray) + assert isinstance(sh.cv_results_["n_resources"], np.ndarray) + + 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"] + ) + + +@pytest.mark.parametrize("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() + + +@pytest.mark.parametrize("Est", (HalvingGridSearchCV, HalvingRandomSearchCV)) +def test_groups_support(Est): + # Check if ValueError (when groups is None) propagates to + # HalvingGridSearchCV and HalvingRandomSearchCV + # And also check if groups is correctly passed to the cv object + rng = np.random.RandomState(0) + + X, y = make_classification(n_samples=50, n_classes=2, random_state=0) + groups = rng.randint(0, 3, 50) + + clf = LinearSVC(random_state=0) + grid = {"C": [1]} + + group_cvs = [ + LeaveOneGroupOut(), + LeavePGroupsOut(2), + GroupKFold(n_splits=3), + GroupShuffleSplit(random_state=0), + ] + error_msg = "The 'groups' parameter should not be None." + for cv in group_cvs: + gs = Est(clf, grid, cv=cv, random_state=0) + with pytest.raises(ValueError, match=error_msg): + gs.fit(X, y) + gs.fit(X, y, groups=groups) + + non_group_cvs = [StratifiedKFold(), StratifiedShuffleSplit(random_state=0)] + for cv in non_group_cvs: + gs = Est(clf, grid, cv=cv) + # Should not raise an error + gs.fit(X, y) + + +@pytest.mark.parametrize("SearchCV", [HalvingRandomSearchCV, HalvingGridSearchCV]) +def test_min_resources_null(SearchCV): + """Check that we raise an error if the minimum resources is set to 0.""" + base_estimator = FastClassifier() + param_grid = {"a": [1]} + X = np.empty(0).reshape(0, 3) + + search = SearchCV(base_estimator, param_grid, min_resources="smallest") + + err_msg = "min_resources_=0: you might have passed an empty dataset X." + with pytest.raises(ValueError, match=err_msg): + search.fit(X, []) + + +@pytest.mark.parametrize("SearchCV", [HalvingGridSearchCV, HalvingRandomSearchCV]) +def test_select_best_index(SearchCV): + """Check the selection strategy of the halving search.""" + 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"]), + } + + # we expect the index of 'i' + best_index = SearchCV._select_best_index(None, None, results) + assert best_index == 8 + + +def test_halving_random_search_list_of_dicts(): + """Check the behaviour of the `HalvingRandomSearchCV` with `param_distribution` + being a list of dictionary. + """ + X, y = make_classification(n_samples=150, n_features=4, random_state=42) + + params = [ + {"kernel": ["rbf"], "C": expon(scale=10), "gamma": expon(scale=0.1)}, + {"kernel": ["poly"], "degree": [2, 3]}, + ] + param_keys = ( + "param_C", + "param_degree", + "param_gamma", + "param_kernel", + ) + score_keys = ( + "mean_test_score", + "mean_train_score", + "rank_test_score", + "split0_test_score", + "split1_test_score", + "split2_test_score", + "split0_train_score", + "split1_train_score", + "split2_train_score", + "std_test_score", + "std_train_score", + "mean_fit_time", + "std_fit_time", + "mean_score_time", + "std_score_time", + ) + extra_keys = ("n_resources", "iter") + + search = HalvingRandomSearchCV( + SVC(), cv=3, param_distributions=params, return_train_score=True, random_state=0 + ) + search.fit(X, y) + n_candidates = sum(search.n_candidates_) + cv_results = search.cv_results_ + # Check results structure + check_cv_results_keys(cv_results, param_keys, score_keys, n_candidates, extra_keys) + expected_cv_results_kinds = { + "param_C": "f", + "param_degree": "i", + "param_gamma": "f", + "param_kernel": "O", + } + check_cv_results_array_types( + search, param_keys, score_keys, expected_cv_results_kinds + ) + + assert all( + ( + cv_results["param_C"].mask[i] + and cv_results["param_gamma"].mask[i] + and not cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "poly" + ) + assert all( + ( + not cv_results["param_C"].mask[i] + and not cv_results["param_gamma"].mask[i] + and cv_results["param_degree"].mask[i] + ) + for i in range(n_candidates) + if cv_results["param_kernel"][i] == "rbf" + ) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_validation.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..c20131b8d3f387d32a9abe5cbf80a6387e0017f3 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/model_selection/tests/test_validation.py @@ -0,0 +1,2739 @@ +"""Test the validation module""" + +import os +import re +import sys +import tempfile +import warnings +from functools import partial +from io import StringIO +from time import sleep + +import numpy as np +import pytest +from scipy.sparse import issparse + +from sklearn import config_context +from sklearn.base import BaseEstimator, ClassifierMixin, clone +from sklearn.cluster import KMeans +from sklearn.datasets import ( + load_diabetes, + load_digits, + load_iris, + make_classification, + make_multilabel_classification, + make_regression, +) +from sklearn.ensemble import RandomForestClassifier +from sklearn.exceptions import FitFailedWarning, UnsetMetadataPassedError +from sklearn.impute import SimpleImputer +from sklearn.linear_model import ( + LogisticRegression, + PassiveAggressiveClassifier, + Ridge, + RidgeClassifier, + SGDClassifier, +) +from sklearn.metrics import ( + accuracy_score, + check_scoring, + confusion_matrix, + explained_variance_score, + make_scorer, + mean_squared_error, + precision_recall_fscore_support, + precision_score, + r2_score, +) +from sklearn.metrics._scorer import _MultimetricScorer +from sklearn.model_selection import ( + GridSearchCV, + GroupKFold, + GroupShuffleSplit, + KFold, + LeaveOneGroupOut, + LeaveOneOut, + LeavePGroupsOut, + ShuffleSplit, + StratifiedKFold, + cross_val_predict, + cross_val_score, + cross_validate, + learning_curve, + permutation_test_score, + validation_curve, +) +from sklearn.model_selection._validation import ( + _check_is_permutation, + _fit_and_score, + _score, +) +from sklearn.model_selection.tests.common import OneTimeSplitter +from sklearn.model_selection.tests.test_search import FailingClassifier +from sklearn.multiclass import OneVsRestClassifier +from sklearn.neighbors import KNeighborsClassifier +from sklearn.neural_network import MLPRegressor +from sklearn.pipeline import Pipeline +from sklearn.preprocessing import LabelEncoder, scale +from sklearn.svm import SVC, LinearSVC +from sklearn.tests.metadata_routing_common import ( + ConsumingClassifier, + ConsumingScorer, + ConsumingSplitter, + _Registry, + check_recorded_metadata, +) +from sklearn.utils import shuffle +from sklearn.utils._mocking import CheckingClassifier, MockDataFrame +from sklearn.utils._testing import ( + assert_allclose, + assert_almost_equal, + assert_array_almost_equal, + assert_array_equal, +) +from sklearn.utils.fixes import COO_CONTAINERS, CSR_CONTAINERS +from sklearn.utils.validation import _num_samples + + +class MockImprovingEstimator(BaseEstimator): + """Dummy classifier to test the learning curve""" + + def __init__(self, n_max_train_sizes): + self.n_max_train_sizes = n_max_train_sizes + self.train_sizes = 0 + self.X_subset = None + + def fit(self, X_subset, y_subset=None): + self.X_subset = X_subset + self.train_sizes = X_subset.shape[0] + return self + + def predict(self, X): + raise NotImplementedError + + def score(self, X=None, Y=None): + # training score becomes worse (2 -> 1), test error better (0 -> 1) + if self._is_training_data(X): + return 2.0 - float(self.train_sizes) / self.n_max_train_sizes + else: + return float(self.train_sizes) / self.n_max_train_sizes + + def _is_training_data(self, X): + return X is self.X_subset + + +class MockIncrementalImprovingEstimator(MockImprovingEstimator): + """Dummy classifier that provides partial_fit""" + + def __init__(self, n_max_train_sizes, expected_fit_params=None): + super().__init__(n_max_train_sizes) + self.x = None + self.expected_fit_params = expected_fit_params + + def _is_training_data(self, X): + return self.x in X + + def partial_fit(self, X, y=None, **params): + self.train_sizes += X.shape[0] + self.x = X[0] + if self.expected_fit_params: + missing = set(self.expected_fit_params) - set(params) + if missing: + raise AssertionError( + f"Expected fit parameter(s) {list(missing)} not seen." + ) + for key, value in params.items(): + if key in self.expected_fit_params and _num_samples( + value + ) != _num_samples(X): + raise AssertionError( + f"Fit parameter {key} has length {_num_samples(value)}" + f"; expected {_num_samples(X)}." + ) + + +class MockEstimatorWithParameter(BaseEstimator): + """Dummy classifier to test the validation curve""" + + def __init__(self, param=0.5): + self.X_subset = None + self.param = param + + def fit(self, X_subset, y_subset): + self.X_subset = X_subset + self.train_sizes = X_subset.shape[0] + return self + + def predict(self, X): + raise NotImplementedError + + def score(self, X=None, y=None): + return self.param if self._is_training_data(X) else 1 - self.param + + def _is_training_data(self, X): + return X is self.X_subset + + +class MockEstimatorWithSingleFitCallAllowed(MockEstimatorWithParameter): + """Dummy classifier that disallows repeated calls of fit method""" + + def fit(self, X_subset, y_subset): + assert not hasattr(self, "fit_called_"), "fit is called the second time" + self.fit_called_ = True + return super().fit(X_subset, y_subset) + + def predict(self, X): + raise NotImplementedError + + +class MockClassifier(ClassifierMixin, BaseEstimator): + """Dummy classifier to test the cross-validation""" + + def __init__(self, a=0, allow_nd=False): + self.a = a + self.allow_nd = allow_nd + + def fit( + self, + X, + Y=None, + sample_weight=None, + class_prior=None, + sparse_sample_weight=None, + sparse_param=None, + dummy_int=None, + dummy_str=None, + dummy_obj=None, + callback=None, + ): + """The dummy arguments are to test that this fit function can + accept non-array arguments through cross-validation, such as: + - int + - str (this is actually array-like) + - object + - function + """ + self.dummy_int = dummy_int + self.dummy_str = dummy_str + self.dummy_obj = dummy_obj + if callback is not None: + callback(self) + + if self.allow_nd: + X = X.reshape(len(X), -1) + if X.ndim >= 3 and not self.allow_nd: + raise ValueError("X cannot be d") + if sample_weight is not None: + assert sample_weight.shape[0] == X.shape[0], ( + "MockClassifier extra fit_param " + "sample_weight.shape[0] is {0}, should be {1}".format( + sample_weight.shape[0], X.shape[0] + ) + ) + if class_prior is not None: + assert class_prior.shape[0] == len(np.unique(y)), ( + "MockClassifier extra fit_param class_prior.shape[0]" + " is {0}, should be {1}".format(class_prior.shape[0], len(np.unique(y))) + ) + if sparse_sample_weight is not None: + fmt = ( + "MockClassifier extra fit_param sparse_sample_weight" + ".shape[0] is {0}, should be {1}" + ) + assert sparse_sample_weight.shape[0] == X.shape[0], fmt.format( + sparse_sample_weight.shape[0], X.shape[0] + ) + if sparse_param is not None: + fmt = ( + "MockClassifier extra fit_param sparse_param.shape " + "is ({0}, {1}), should be ({2}, {3})" + ) + assert sparse_param.shape == P.shape, fmt.format( + sparse_param.shape[0], + sparse_param.shape[1], + P.shape[0], + P.shape[1], + ) + self.classes_ = np.unique(y) + return self + + def predict(self, T): + if self.allow_nd: + T = T.reshape(len(T), -1) + return T[:, 0] + + def predict_proba(self, T): + return T + + def score(self, X=None, Y=None): + return 1.0 / (1 + np.abs(self.a)) + + def get_params(self, deep=False): + return {"a": self.a, "allow_nd": self.allow_nd} + + +# XXX: use 2D array, since 1D X is being detected as a single sample in +# check_consistent_length +X = np.ones((15, 2)) +y = np.array([0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6]) +# The number of samples per class needs to be > n_splits, +# for StratifiedKFold(n_splits=3) +y2 = np.array([1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]) +P = np.eye(5) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_cross_val_score(coo_container): + clf = MockClassifier() + X_sparse = coo_container(X) + + for a in range(-10, 10): + clf.a = a + # Smoke test + scores = cross_val_score(clf, X, y2) + assert_array_equal(scores, clf.score(X, y2)) + + # test with multioutput y + multioutput_y = np.column_stack([y2, y2[::-1]]) + scores = cross_val_score(clf, X_sparse, multioutput_y) + assert_array_equal(scores, clf.score(X_sparse, multioutput_y)) + + scores = cross_val_score(clf, X_sparse, y2) + assert_array_equal(scores, clf.score(X_sparse, y2)) + + # test with multioutput y + scores = cross_val_score(clf, X_sparse, multioutput_y) + assert_array_equal(scores, clf.score(X_sparse, multioutput_y)) + + # test with X and y as list + list_check = lambda x: isinstance(x, list) + clf = CheckingClassifier(check_X=list_check) + scores = cross_val_score(clf, X.tolist(), y2.tolist(), cv=3) + + clf = CheckingClassifier(check_y=list_check) + scores = cross_val_score(clf, X, y2.tolist(), cv=3) + + # test with 3d X and + X_3d = X[:, :, np.newaxis] + clf = MockClassifier(allow_nd=True) + scores = cross_val_score(clf, X_3d, y2) + + clf = MockClassifier(allow_nd=False) + with pytest.raises(ValueError): + cross_val_score(clf, X_3d, y2, error_score="raise") + + +def test_cross_validate_many_jobs(): + # regression test for #12154: cv='warn' with n_jobs>1 trigger a copy of + # the parameters leading to a failure in check_cv due to cv is 'warn' + # instead of cv == 'warn'. + X, y = load_iris(return_X_y=True) + clf = SVC(gamma="auto") + grid = GridSearchCV(clf, param_grid={"C": [1, 10]}) + cross_validate(grid, X, y, n_jobs=2) + + +def test_cross_validate_invalid_scoring_param(): + X, y = make_classification(random_state=0) + estimator = MockClassifier() + + # Test the errors + error_message_regexp = ".*must be unique strings.*" + + # List/tuple of callables should raise a message advising users to use + # dict of names to callables mapping + with pytest.raises(ValueError, match=error_message_regexp): + cross_validate( + estimator, + X, + y, + scoring=(make_scorer(precision_score), make_scorer(accuracy_score)), + ) + with pytest.raises(ValueError, match=error_message_regexp): + cross_validate(estimator, X, y, scoring=(make_scorer(precision_score),)) + + # So should empty lists/tuples + with pytest.raises(ValueError, match=error_message_regexp + "Empty list.*"): + cross_validate(estimator, X, y, scoring=()) + + # So should duplicated entries + with pytest.raises(ValueError, match=error_message_regexp + "Duplicate.*"): + cross_validate(estimator, X, y, scoring=("f1_micro", "f1_micro")) + + # Nested Lists should raise a generic error message + with pytest.raises(ValueError, match=error_message_regexp): + cross_validate(estimator, X, y, scoring=[[make_scorer(precision_score)]]) + + # Empty dict should raise invalid scoring error + with pytest.raises(ValueError, match="An empty dict"): + cross_validate(estimator, X, y, scoring=(dict())) + + multiclass_scorer = make_scorer(precision_recall_fscore_support) + + # Multiclass Scorers that return multiple values are not supported yet + # the warning message we're expecting to see + warning_message = ( + "Scoring failed. The score on this train-test " + f"partition for these parameters will be set to {np.nan}. " + "Details: \n" + ) + + 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}) + + +def test_cross_validate_nested_estimator(): + # Non-regression test to ensure that nested + # estimators are properly returned in a list + # https://github.com/scikit-learn/scikit-learn/pull/17745 + (X, y) = load_iris(return_X_y=True) + pipeline = Pipeline( + [ + ("imputer", SimpleImputer()), + ("classifier", MockClassifier()), + ] + ) + + results = cross_validate(pipeline, X, y, return_estimator=True) + estimators = results["estimator"] + + assert isinstance(estimators, list) + assert all(isinstance(estimator, Pipeline) for estimator in estimators) + + +@pytest.mark.parametrize("use_sparse", [False, True]) +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_cross_validate(use_sparse: bool, csr_container): + # Compute train and test mse/r2 scores + cv = KFold() + + # Regression + X_reg, y_reg = make_regression(n_samples=30, random_state=0) + reg = Ridge(random_state=0) + + # Classification + X_clf, y_clf = make_classification(n_samples=30, random_state=0) + clf = SVC(kernel="linear", random_state=0) + + if use_sparse: + X_reg = csr_container(X_reg) + X_clf = csr_container(X_clf) + + for X, y, est in ((X_reg, y_reg, reg), (X_clf, y_clf, clf)): + # It's okay to evaluate regression metrics on classification too + mse_scorer = check_scoring(est, scoring="neg_mean_squared_error") + r2_scorer = check_scoring(est, scoring="r2") + train_mse_scores = [] + test_mse_scores = [] + train_r2_scores = [] + test_r2_scores = [] + fitted_estimators = [] + + for train, test in cv.split(X, y): + est = clone(est).fit(X[train], y[train]) + train_mse_scores.append(mse_scorer(est, X[train], y[train])) + train_r2_scores.append(r2_scorer(est, X[train], y[train])) + test_mse_scores.append(mse_scorer(est, X[test], y[test])) + test_r2_scores.append(r2_scorer(est, X[test], y[test])) + fitted_estimators.append(est) + + train_mse_scores = np.array(train_mse_scores) + test_mse_scores = np.array(test_mse_scores) + train_r2_scores = np.array(train_r2_scores) + test_r2_scores = np.array(test_r2_scores) + fitted_estimators = np.array(fitted_estimators) + + scores = ( + train_mse_scores, + test_mse_scores, + train_r2_scores, + test_r2_scores, + fitted_estimators, + ) + + # To ensure that the test does not suffer from + # large statistical fluctuations due to slicing small datasets, + # we pass the cross-validation instance + check_cross_validate_single_metric(est, X, y, scores, cv) + check_cross_validate_multi_metric(est, X, y, scores, cv) + + +def check_cross_validate_single_metric(clf, X, y, scores, cv): + ( + train_mse_scores, + test_mse_scores, + train_r2_scores, + test_r2_scores, + fitted_estimators, + ) = scores + # Test single metric evaluation when scoring is string or singleton list + for return_train_score, dict_len in ((True, 4), (False, 3)): + # Single metric passed as a string + if return_train_score: + mse_scores_dict = cross_validate( + clf, + X, + y, + scoring="neg_mean_squared_error", + return_train_score=True, + cv=cv, + ) + assert_array_almost_equal(mse_scores_dict["train_score"], train_mse_scores) + else: + mse_scores_dict = cross_validate( + clf, + X, + y, + scoring="neg_mean_squared_error", + return_train_score=False, + cv=cv, + ) + assert isinstance(mse_scores_dict, dict) + assert len(mse_scores_dict) == dict_len + assert_array_almost_equal(mse_scores_dict["test_score"], test_mse_scores) + + # Single metric passed as a list + if return_train_score: + # It must be True by default - deprecated + r2_scores_dict = cross_validate( + clf, X, y, scoring=["r2"], return_train_score=True, cv=cv + ) + assert_array_almost_equal(r2_scores_dict["train_r2"], train_r2_scores, True) + else: + r2_scores_dict = cross_validate( + clf, X, y, scoring=["r2"], return_train_score=False, cv=cv + ) + assert isinstance(r2_scores_dict, dict) + assert len(r2_scores_dict) == dict_len + assert_array_almost_equal(r2_scores_dict["test_r2"], test_r2_scores) + + # Test return_estimator option + mse_scores_dict = cross_validate( + clf, X, y, scoring="neg_mean_squared_error", return_estimator=True, cv=cv + ) + for k, est in enumerate(mse_scores_dict["estimator"]): + est_coef = est.coef_.copy() + if issparse(est_coef): + est_coef = est_coef.toarray() + + fitted_est_coef = fitted_estimators[k].coef_.copy() + if issparse(fitted_est_coef): + fitted_est_coef = fitted_est_coef.toarray() + + assert_almost_equal(est_coef, fitted_est_coef) + assert_almost_equal(est.intercept_, fitted_estimators[k].intercept_) + + +def check_cross_validate_multi_metric(clf, X, y, scores, cv): + # Test multimetric evaluation when scoring is a list / dict + ( + train_mse_scores, + test_mse_scores, + train_r2_scores, + test_r2_scores, + fitted_estimators, + ) = scores + + def custom_scorer(clf, X, y): + y_pred = clf.predict(X) + return { + "r2": r2_score(y, y_pred), + "neg_mean_squared_error": -mean_squared_error(y, y_pred), + } + + all_scoring = ( + ("r2", "neg_mean_squared_error"), + { + "r2": make_scorer(r2_score), + "neg_mean_squared_error": "neg_mean_squared_error", + }, + custom_scorer, + ) + + keys_sans_train = { + "test_r2", + "test_neg_mean_squared_error", + "fit_time", + "score_time", + } + keys_with_train = keys_sans_train.union( + {"train_r2", "train_neg_mean_squared_error"} + ) + + for return_train_score in (True, False): + for scoring in all_scoring: + if return_train_score: + # return_train_score must be True by default - deprecated + cv_results = cross_validate( + clf, X, y, scoring=scoring, return_train_score=True, cv=cv + ) + assert_array_almost_equal(cv_results["train_r2"], train_r2_scores) + assert_array_almost_equal( + cv_results["train_neg_mean_squared_error"], train_mse_scores + ) + else: + cv_results = cross_validate( + clf, X, y, scoring=scoring, return_train_score=False, cv=cv + ) + assert isinstance(cv_results, dict) + assert set(cv_results.keys()) == ( + keys_with_train if return_train_score else keys_sans_train + ) + assert_array_almost_equal(cv_results["test_r2"], test_r2_scores) + assert_array_almost_equal( + cv_results["test_neg_mean_squared_error"], test_mse_scores + ) + + # Make sure all the arrays are of np.ndarray type + assert isinstance(cv_results["test_r2"], np.ndarray) + assert isinstance(cv_results["test_neg_mean_squared_error"], np.ndarray) + assert isinstance(cv_results["fit_time"], np.ndarray) + assert isinstance(cv_results["score_time"], np.ndarray) + + # Ensure all the times are within sane limits + assert np.all(cv_results["fit_time"] >= 0) + assert np.all(cv_results["fit_time"] < 10) + assert np.all(cv_results["score_time"] >= 0) + assert np.all(cv_results["score_time"] < 10) + + +def test_cross_val_score_predict_groups(): + # Check if ValueError (when groups is None) propagates to cross_val_score + # and cross_val_predict + # And also check if groups is correctly passed to the cv object + X, y = make_classification(n_samples=20, n_classes=2, random_state=0) + + clf = SVC(kernel="linear") + + group_cvs = [ + LeaveOneGroupOut(), + LeavePGroupsOut(2), + GroupKFold(), + GroupShuffleSplit(), + ] + error_message = "The 'groups' parameter should not be None." + for cv in group_cvs: + with pytest.raises(ValueError, match=error_message): + cross_val_score(estimator=clf, X=X, y=y, cv=cv) + with pytest.raises(ValueError, match=error_message): + cross_val_predict(estimator=clf, X=X, y=y, cv=cv) + + +def test_cross_val_score_pandas(): + # check cross_val_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import DataFrame, Series + + types.append((Series, DataFrame)) + except ImportError: + pass + for TargetType, InputFeatureType in types: + # X dataframe, y series + # 3 fold cross val is used so we need at least 3 samples per class + X_df, y_ser = InputFeatureType(X), TargetType(y2) + check_df = lambda x: isinstance(x, InputFeatureType) + check_series = lambda x: isinstance(x, TargetType) + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + cross_val_score(clf, X_df, y_ser, cv=3) + + +def test_cross_val_score_mask(): + # test that cross_val_score works with boolean masks + svm = SVC(kernel="linear") + iris = load_iris() + X, y = iris.data, iris.target + kfold = KFold(5) + scores_indices = cross_val_score(svm, X, y, cv=kfold) + kfold = KFold(5) + cv_masks = [] + for train, test in kfold.split(X, y): + mask_train = np.zeros(len(y), dtype=bool) + mask_test = np.zeros(len(y), dtype=bool) + mask_train[train] = 1 + mask_test[test] = 1 + cv_masks.append((train, test)) + scores_masks = cross_val_score(svm, X, y, cv=cv_masks) + assert_array_equal(scores_indices, scores_masks) + + +def test_cross_val_score_precomputed(): + # test for svm with precomputed kernel + svm = SVC(kernel="precomputed") + iris = load_iris() + X, y = iris.data, iris.target + linear_kernel = np.dot(X, X.T) + score_precomputed = cross_val_score(svm, linear_kernel, y) + svm = SVC(kernel="linear") + score_linear = cross_val_score(svm, X, y) + assert_array_almost_equal(score_precomputed, score_linear) + + # test with callable + svm = SVC(kernel=lambda x, y: np.dot(x, y.T)) + score_callable = cross_val_score(svm, X, y) + assert_array_almost_equal(score_precomputed, score_callable) + + # Error raised for non-square X + svm = SVC(kernel="precomputed") + with pytest.raises(ValueError): + cross_val_score(svm, X, y) + + # test error is raised when the precomputed kernel is not array-like + # or sparse + with pytest.raises(ValueError): + cross_val_score(svm, linear_kernel.tolist(), y) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_cross_val_score_fit_params(coo_container): + clf = MockClassifier() + n_samples = X.shape[0] + n_classes = len(np.unique(y)) + + W_sparse = coo_container( + (np.array([1]), (np.array([1]), np.array([0]))), shape=(15, 1) + ) + P_sparse = coo_container(np.eye(5)) + + DUMMY_INT = 42 + DUMMY_STR = "42" + DUMMY_OBJ = object() + + def assert_fit_params(clf): + # Function to test that the values are passed correctly to the + # classifier arguments for non-array type + + assert clf.dummy_int == DUMMY_INT + assert clf.dummy_str == DUMMY_STR + assert clf.dummy_obj == DUMMY_OBJ + + fit_params = { + "sample_weight": np.ones(n_samples), + "class_prior": np.full(n_classes, 1.0 / n_classes), + "sparse_sample_weight": W_sparse, + "sparse_param": P_sparse, + "dummy_int": DUMMY_INT, + "dummy_str": DUMMY_STR, + "dummy_obj": DUMMY_OBJ, + "callback": assert_fit_params, + } + cross_val_score(clf, X, y2, params=fit_params) + + +def test_cross_val_score_score_func(): + clf = MockClassifier() + _score_func_args = [] + + def score_func(y_test, y_predict): + _score_func_args.append((y_test, y_predict)) + return 1.0 + + with warnings.catch_warnings(record=True): + scoring = make_scorer(score_func) + score = cross_val_score(clf, X, y, scoring=scoring, cv=3) + assert_array_equal(score, [1.0, 1.0, 1.0]) + # Test that score function is called only 3 times (for cv=3) + assert len(_score_func_args) == 3 + + +def test_cross_val_score_with_score_func_classification(): + iris = load_iris() + clf = SVC(kernel="linear") + + # Default score (should be the accuracy score) + scores = cross_val_score(clf, iris.data, iris.target) + assert_array_almost_equal(scores, [0.97, 1.0, 0.97, 0.97, 1.0], 2) + + # Correct classification score (aka. zero / one score) - should be the + # same as the default estimator score + zo_scores = cross_val_score(clf, iris.data, iris.target, scoring="accuracy") + assert_array_almost_equal(zo_scores, [0.97, 1.0, 0.97, 0.97, 1.0], 2) + + # F1 score (class are balanced so f1_score should be equal to zero/one + # score + f1_scores = cross_val_score(clf, iris.data, iris.target, scoring="f1_weighted") + assert_array_almost_equal(f1_scores, [0.97, 1.0, 0.97, 0.97, 1.0], 2) + + +def test_cross_val_score_with_score_func_regression(): + X, y = make_regression(n_samples=30, n_features=20, n_informative=5, random_state=0) + reg = Ridge() + + # Default score of the Ridge regression estimator + scores = cross_val_score(reg, X, y) + assert_array_almost_equal(scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) + + # R2 score (aka. determination coefficient) - should be the + # same as the default estimator score + r2_scores = cross_val_score(reg, X, y, scoring="r2") + assert_array_almost_equal(r2_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) + + # Mean squared error; this is a loss function, so "scores" are negative + neg_mse_scores = cross_val_score(reg, X, y, scoring="neg_mean_squared_error") + expected_neg_mse = np.array([-763.07, -553.16, -274.38, -273.26, -1681.99]) + assert_array_almost_equal(neg_mse_scores, expected_neg_mse, 2) + + # Explained variance + scoring = make_scorer(explained_variance_score) + ev_scores = cross_val_score(reg, X, y, scoring=scoring) + assert_array_almost_equal(ev_scores, [0.94, 0.97, 0.97, 0.99, 0.92], 2) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_permutation_score(coo_container): + iris = load_iris() + X = iris.data + X_sparse = coo_container(X) + y = iris.target + svm = SVC(kernel="linear") + cv = StratifiedKFold(2) + + score, scores, pvalue = permutation_test_score( + svm, X, y, n_permutations=30, cv=cv, scoring="accuracy" + ) + assert score > 0.9 + assert_almost_equal(pvalue, 0.0, 1) + + score_group, _, pvalue_group = permutation_test_score( + svm, + X, + y, + n_permutations=30, + cv=cv, + scoring="accuracy", + groups=np.ones(y.size), + random_state=0, + ) + assert score_group == score + assert pvalue_group == pvalue + + # check that we obtain the same results with a sparse representation + svm_sparse = SVC(kernel="linear") + cv_sparse = StratifiedKFold(2) + score_group, _, pvalue_group = permutation_test_score( + svm_sparse, + X_sparse, + y, + n_permutations=30, + cv=cv_sparse, + scoring="accuracy", + groups=np.ones(y.size), + random_state=0, + ) + + assert score_group == score + assert pvalue_group == pvalue + + # test with custom scoring object + def custom_score(y_true, y_pred): + return ((y_true == y_pred).sum() - (y_true != y_pred).sum()) / y_true.shape[0] + + scorer = make_scorer(custom_score) + score, _, pvalue = permutation_test_score( + svm, X, y, n_permutations=100, scoring=scorer, cv=cv, random_state=0 + ) + assert_almost_equal(score, 0.93, 2) + assert_almost_equal(pvalue, 0.01, 3) + + # set random y + y = np.mod(np.arange(len(y)), 3) + + score, scores, pvalue = permutation_test_score( + svm, X, y, n_permutations=30, cv=cv, scoring="accuracy" + ) + + assert score < 0.5 + assert pvalue > 0.2 + + +def test_permutation_test_score_allow_nans(): + # Check that permutation_test_score allows input data with NaNs + X = np.arange(200, dtype=np.float64).reshape(10, -1) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + p = Pipeline( + [ + ("imputer", SimpleImputer(strategy="mean", missing_values=np.nan)), + ("classifier", MockClassifier()), + ] + ) + permutation_test_score(p, X, y) + + +def test_permutation_test_score_params(): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_sample_weight=True) + + err_msg = r"Expected sample_weight to be passed" + with pytest.raises(AssertionError, match=err_msg): + permutation_test_score(clf, X, y) + + err_msg = r"sample_weight.shape == \(1,\), expected \(8,\)!" + with pytest.raises(ValueError, match=err_msg): + permutation_test_score(clf, X, y, params={"sample_weight": np.ones(1)}) + permutation_test_score(clf, X, y, 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) + X[2, :] = np.nan + y = np.repeat([0, 1], X.shape[0] / 2) + p = Pipeline( + [ + ("imputer", SimpleImputer(strategy="mean", missing_values=np.nan)), + ("classifier", MockClassifier()), + ] + ) + cross_val_score(p, X, y) + + +def test_cross_val_score_multilabel(): + X = np.array( + [ + [-3, 4], + [2, 4], + [3, 3], + [0, 2], + [-3, 1], + [-2, 1], + [0, 0], + [-2, -1], + [-1, -2], + [1, -2], + ] + ) + y = np.array( + [[1, 1], [0, 1], [0, 1], [0, 1], [1, 1], [0, 1], [1, 0], [1, 1], [1, 0], [0, 0]] + ) + clf = KNeighborsClassifier(n_neighbors=1) + scoring_micro = make_scorer(precision_score, average="micro") + scoring_macro = make_scorer(precision_score, average="macro") + scoring_samples = make_scorer(precision_score, average="samples") + score_micro = cross_val_score(clf, X, y, scoring=scoring_micro) + score_macro = cross_val_score(clf, X, y, scoring=scoring_macro) + score_samples = cross_val_score(clf, X, y, scoring=scoring_samples) + assert_almost_equal(score_micro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 3]) + assert_almost_equal(score_macro, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) + assert_almost_equal(score_samples, [1, 1 / 2, 3 / 4, 1 / 2, 1 / 4]) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_cross_val_predict(coo_container): + X, y = load_diabetes(return_X_y=True) + cv = KFold() + + est = Ridge() + + # Naive loop (should be same as cross_val_predict): + preds2 = np.zeros_like(y) + for train, test in cv.split(X, y): + est.fit(X[train], y[train]) + preds2[test] = est.predict(X[test]) + + preds = cross_val_predict(est, X, y, cv=cv) + assert_array_almost_equal(preds, preds2) + + preds = cross_val_predict(est, X, y) + assert len(preds) == len(y) + + cv = LeaveOneOut() + preds = cross_val_predict(est, X, y, cv=cv) + assert len(preds) == len(y) + + Xsp = X.copy() + Xsp *= Xsp > np.median(Xsp) + Xsp = coo_container(Xsp) + preds = cross_val_predict(est, Xsp, y) + assert_array_almost_equal(len(preds), len(y)) + + preds = cross_val_predict(KMeans(n_init="auto"), X) + assert len(preds) == len(y) + + class BadCV: + def split(self, X, y=None, groups=None): + for i in range(4): + yield np.array([0, 1, 2, 3]), np.array([4, 5, 6, 7, 8]) + + with pytest.raises(ValueError): + cross_val_predict(est, X, y, cv=BadCV()) + + X, y = load_iris(return_X_y=True) + + warning_message = ( + r"Number of classes in training fold \(2\) does " + r"not match total number of classes \(3\). " + "Results may not be appropriate for your use case." + ) + with pytest.warns(RuntimeWarning, match=warning_message): + cross_val_predict( + LogisticRegression(solver="liblinear"), + X, + y, + method="predict_proba", + cv=KFold(2), + ) + + +def test_cross_val_predict_decision_function_shape(): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + preds = cross_val_predict(LogisticRegression(), X, y, method="decision_function") + assert preds.shape == (50,) + + X, y = load_iris(return_X_y=True) + + preds = cross_val_predict(LogisticRegression(), X, y, method="decision_function") + assert preds.shape == (150, 3) + + # This specifically tests imbalanced splits for binary + # classification with decision_function. This is only + # applicable to classifiers that can be fit on a single + # class. + X = X[:100] + y = y[:100] + error_message = ( + "Only 1 class/es in training fold," + " but 2 in overall dataset. This" + " is not supported for decision_function" + " with imbalanced folds. To fix " + "this, use a cross-validation technique " + "resulting in properly stratified folds" + ) + with pytest.raises(ValueError, match=error_message): + cross_val_predict( + RidgeClassifier(), X, y, method="decision_function", cv=KFold(2) + ) + + X, y = load_digits(return_X_y=True) + est = SVC(kernel="linear", decision_function_shape="ovo") + + preds = cross_val_predict(est, X, y, method="decision_function") + assert preds.shape == (1797, 45) + + ind = np.argsort(y) + X, y = X[ind], y[ind] + error_message_regexp = ( + r"Output shape \(599L?, 21L?\) of " + "decision_function does not match number of " + r"classes \(7\) in fold. Irregular " + "decision_function .*" + ) + with pytest.raises(ValueError, match=error_message_regexp): + cross_val_predict(est, X, y, cv=KFold(n_splits=3), method="decision_function") + + +def test_cross_val_predict_predict_proba_shape(): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + preds = cross_val_predict(LogisticRegression(), X, y, method="predict_proba") + assert preds.shape == (50, 2) + + X, y = load_iris(return_X_y=True) + + preds = cross_val_predict(LogisticRegression(), X, y, method="predict_proba") + assert preds.shape == (150, 3) + + +def test_cross_val_predict_predict_log_proba_shape(): + X, y = make_classification(n_classes=2, n_samples=50, random_state=0) + + preds = cross_val_predict(LogisticRegression(), X, y, method="predict_log_proba") + assert preds.shape == (50, 2) + + X, y = load_iris(return_X_y=True) + + preds = cross_val_predict(LogisticRegression(), X, y, method="predict_log_proba") + assert preds.shape == (150, 3) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_cross_val_predict_input_types(coo_container): + iris = load_iris() + X, y = iris.data, iris.target + X_sparse = coo_container(X) + multioutput_y = np.column_stack([y, y[::-1]]) + + clf = Ridge(fit_intercept=False, random_state=0) + # 3 fold cv is used --> at least 3 samples per class + # Smoke test + predictions = cross_val_predict(clf, X, y) + assert predictions.shape == (150,) + + # test with multioutput y + predictions = cross_val_predict(clf, X_sparse, multioutput_y) + assert predictions.shape == (150, 2) + + predictions = cross_val_predict(clf, X_sparse, y) + assert_array_equal(predictions.shape, (150,)) + + # test with multioutput y + predictions = cross_val_predict(clf, X_sparse, multioutput_y) + assert_array_equal(predictions.shape, (150, 2)) + + # test with X and y as list + list_check = lambda x: isinstance(x, list) + clf = CheckingClassifier(check_X=list_check) + predictions = cross_val_predict(clf, X.tolist(), y.tolist()) + + clf = CheckingClassifier(check_y=list_check) + predictions = cross_val_predict(clf, X, y.tolist()) + + # test with X and y as list and non empty method + predictions = cross_val_predict( + LogisticRegression(), + X.tolist(), + y.tolist(), + method="decision_function", + ) + predictions = cross_val_predict( + LogisticRegression(), + X, + y.tolist(), + method="decision_function", + ) + + # test with 3d X and + X_3d = X[:, :, np.newaxis] + check_3d = lambda x: x.ndim == 3 + clf = CheckingClassifier(check_X=check_3d) + predictions = cross_val_predict(clf, X_3d, y) + assert_array_equal(predictions.shape, (150,)) + + +def test_cross_val_predict_pandas(): + # check cross_val_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import DataFrame, Series + + types.append((Series, DataFrame)) + except ImportError: + pass + for TargetType, InputFeatureType in types: + # X dataframe, y series + X_df, y_ser = InputFeatureType(X), TargetType(y2) + check_df = lambda x: isinstance(x, InputFeatureType) + check_series = lambda x: isinstance(x, TargetType) + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + cross_val_predict(clf, X_df, y_ser, cv=3) + + +def test_cross_val_predict_unbalanced(): + X, y = make_classification( + n_samples=100, + n_features=2, + n_redundant=0, + n_informative=2, + n_clusters_per_class=1, + random_state=1, + ) + # Change the first sample to a new class + y[0] = 2 + clf = LogisticRegression(random_state=1) + cv = StratifiedKFold(n_splits=2) + train, test = list(cv.split(X, y)) + yhat_proba = cross_val_predict(clf, X, y, cv=cv, method="predict_proba") + assert y[test[0]][0] == 2 # sanity check for further assertions + assert np.all(yhat_proba[test[0]][:, 2] == 0) + assert np.all(yhat_proba[test[0]][:, 0:1] > 0) + assert np.all(yhat_proba[test[1]] > 0) + assert_array_almost_equal(yhat_proba.sum(axis=1), np.ones(y.shape), decimal=12) + + +def test_cross_val_predict_y_none(): + # ensure that cross_val_predict works when y is None + mock_classifier = MockClassifier() + rng = np.random.RandomState(42) + X = rng.rand(100, 10) + y_hat = cross_val_predict(mock_classifier, X, y=None, cv=5, method="predict") + assert_allclose(X[:, 0], y_hat) + y_hat_proba = cross_val_predict( + mock_classifier, X, y=None, cv=5, method="predict_proba" + ) + assert_allclose(X, y_hat_proba) + + +@pytest.mark.parametrize("coo_container", COO_CONTAINERS) +def test_cross_val_score_sparse_fit_params(coo_container): + iris = load_iris() + X, y = iris.data, iris.target + clf = MockClassifier() + fit_params = {"sparse_sample_weight": coo_container(np.eye(X.shape[0]))} + a = cross_val_score(clf, X, y, params=fit_params, cv=3) + assert_array_equal(a, np.ones(3)) + + +def test_learning_curve(): + n_samples = 30 + n_splits = 3 + X, y = make_classification( + n_samples=n_samples, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(n_samples * ((n_splits - 1) / n_splits)) + for shuffle_train in [False, True]: + with warnings.catch_warnings(record=True) as w: + ( + train_sizes, + train_scores, + test_scores, + fit_times, + score_times, + ) = learning_curve( + estimator, + X, + y, + cv=KFold(n_splits=n_splits), + train_sizes=np.linspace(0.1, 1.0, 10), + shuffle=shuffle_train, + return_times=True, + ) + if len(w) > 0: + raise RuntimeError("Unexpected warning: %r" % w[0].message) + assert train_scores.shape == (10, 3) + assert test_scores.shape == (10, 3) + assert fit_times.shape == (10, 3) + assert score_times.shape == (10, 3) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) + + # Cannot use assert_array_almost_equal for fit and score times because + # the values are hardware-dependant + assert fit_times.dtype == "float64" + assert score_times.dtype == "float64" + + # Test a custom cv splitter that can iterate only once + with warnings.catch_warnings(record=True) as w: + train_sizes2, train_scores2, test_scores2 = learning_curve( + estimator, + X, + y, + cv=OneTimeSplitter(n_splits=n_splits, n_samples=n_samples), + train_sizes=np.linspace(0.1, 1.0, 10), + shuffle=shuffle_train, + ) + if len(w) > 0: + raise RuntimeError("Unexpected warning: %r" % w[0].message) + assert_array_almost_equal(train_scores2, train_scores) + assert_array_almost_equal(test_scores2, test_scores) + + +def test_learning_curve_unsupervised(): + X, _ = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(20) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y=None, cv=3, train_sizes=np.linspace(0.1, 1.0, 10) + ) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_verbose(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(20) + + old_stdout = sys.stdout + sys.stdout = StringIO() + try: + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=3, verbose=1 + ) + finally: + out = sys.stdout.getvalue() + sys.stdout.close() + sys.stdout = old_stdout + + assert "[learning_curve]" in out + + +def test_learning_curve_incremental_learning_not_possible(): + X, y = make_classification( + n_samples=2, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + # The mockup does not have partial_fit() + estimator = MockImprovingEstimator(1) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, exploit_incremental_learning=True) + + +def test_learning_curve_incremental_learning(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockIncrementalImprovingEstimator(20) + for shuffle_train in [False, True]: + train_sizes, train_scores, test_scores = learning_curve( + estimator, + X, + y, + cv=3, + exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10), + shuffle=shuffle_train, + ) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_incremental_learning_unsupervised(): + X, _ = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockIncrementalImprovingEstimator(20) + train_sizes, train_scores, test_scores = learning_curve( + estimator, + X, + y=None, + cv=3, + exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10), + ) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_batch_and_incremental_learning_are_equal(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + train_sizes = np.linspace(0.2, 1.0, 5) + estimator = PassiveAggressiveClassifier(max_iter=1, tol=None, shuffle=False) + + train_sizes_inc, train_scores_inc, test_scores_inc = learning_curve( + estimator, + X, + y, + train_sizes=train_sizes, + cv=3, + exploit_incremental_learning=True, + ) + train_sizes_batch, train_scores_batch, test_scores_batch = learning_curve( + estimator, + X, + y, + cv=3, + train_sizes=train_sizes, + exploit_incremental_learning=False, + ) + + assert_array_equal(train_sizes_inc, train_sizes_batch) + assert_array_almost_equal( + train_scores_inc.mean(axis=1), train_scores_batch.mean(axis=1) + ) + assert_array_almost_equal( + test_scores_inc.mean(axis=1), test_scores_batch.mean(axis=1) + ) + + +def test_learning_curve_n_sample_range_out_of_bounds(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(20) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, cv=3, train_sizes=[0, 1]) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, cv=3, train_sizes=[0.0, 1.0]) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, cv=3, train_sizes=[0.1, 1.1]) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, cv=3, train_sizes=[0, 20]) + with pytest.raises(ValueError): + learning_curve(estimator, X, y, cv=3, train_sizes=[1, 21]) + + +def test_learning_curve_remove_duplicate_sample_sizes(): + X, y = make_classification( + n_samples=3, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(2) + warning_message = ( + "Removed duplicate entries from 'train_sizes'. Number of ticks " + "will be less than the size of 'train_sizes': 2 instead of 3." + ) + with pytest.warns(RuntimeWarning, match=warning_message): + train_sizes, _, _ = learning_curve( + estimator, X, y, cv=3, train_sizes=np.linspace(0.33, 1.0, 3) + ) + assert_array_equal(train_sizes, [1, 2]) + + +def test_learning_curve_with_boolean_indices(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockImprovingEstimator(20) + cv = KFold(n_splits=3) + train_sizes, train_scores, test_scores = learning_curve( + estimator, X, y, cv=cv, train_sizes=np.linspace(0.1, 1.0, 10) + ) + assert_array_equal(train_sizes, np.linspace(2, 20, 10)) + assert_array_almost_equal(train_scores.mean(axis=1), np.linspace(1.9, 1.0, 10)) + assert_array_almost_equal(test_scores.mean(axis=1), np.linspace(0.1, 1.0, 10)) + + +def test_learning_curve_with_shuffle(): + # Following test case was designed this way to verify the code + # changes made in pull request: #7506. + X = np.array( + [ + [1, 2], + [3, 4], + [5, 6], + [7, 8], + [11, 12], + [13, 14], + [15, 16], + [17, 18], + [19, 20], + [7, 8], + [9, 10], + [11, 12], + [13, 14], + [15, 16], + [17, 18], + ] + ) + y = np.array([1, 1, 1, 2, 3, 4, 1, 1, 2, 3, 4, 1, 2, 3, 4]) + groups = np.array([1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 4, 4, 4, 4]) + # Splits on these groups fail without shuffle as the first iteration + # of the learning curve doesn't contain label 4 in the training set. + estimator = PassiveAggressiveClassifier(max_iter=5, tol=None, shuffle=False) + + cv = GroupKFold(n_splits=2) + train_sizes_batch, train_scores_batch, test_scores_batch = learning_curve( + estimator, + X, + y, + cv=cv, + n_jobs=1, + train_sizes=np.linspace(0.3, 1.0, 3), + groups=groups, + shuffle=True, + random_state=2, + ) + assert_array_almost_equal( + train_scores_batch.mean(axis=1), np.array([0.75, 0.3, 0.36111111]) + ) + assert_array_almost_equal( + test_scores_batch.mean(axis=1), np.array([0.36111111, 0.25, 0.25]) + ) + with pytest.raises(ValueError): + learning_curve( + estimator, + X, + y, + cv=cv, + n_jobs=1, + train_sizes=np.linspace(0.3, 1.0, 3), + groups=groups, + error_score="raise", + ) + + train_sizes_inc, train_scores_inc, test_scores_inc = learning_curve( + estimator, + X, + y, + cv=cv, + n_jobs=1, + train_sizes=np.linspace(0.3, 1.0, 3), + groups=groups, + shuffle=True, + random_state=2, + exploit_incremental_learning=True, + ) + assert_array_almost_equal( + train_scores_inc.mean(axis=1), train_scores_batch.mean(axis=1) + ) + assert_array_almost_equal( + test_scores_inc.mean(axis=1), test_scores_batch.mean(axis=1) + ) + + +def test_learning_curve_params(): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_sample_weight=True) + + err_msg = r"Expected sample_weight to be passed" + with pytest.raises(AssertionError, match=err_msg): + learning_curve(clf, X, y, error_score="raise") + + err_msg = r"sample_weight.shape == \(1,\), expected \(2,\)!" + with pytest.raises(ValueError, match=err_msg): + learning_curve( + clf, X, y, error_score="raise", params={"sample_weight": np.ones(1)} + ) + learning_curve( + clf, X, y, error_score="raise", params={"sample_weight": np.ones(10)} + ) + + +def test_learning_curve_incremental_learning_params(): + X, y = make_classification( + n_samples=30, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + estimator = MockIncrementalImprovingEstimator(20, ["sample_weight"]) + err_msg = r"Expected fit parameter\(s\) \['sample_weight'\] not seen." + with pytest.raises(AssertionError, match=err_msg): + learning_curve( + estimator, + X, + y, + cv=3, + exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10), + error_score="raise", + ) + + err_msg = "Fit parameter sample_weight has length 3; expected" + with pytest.raises(AssertionError, match=err_msg): + learning_curve( + estimator, + X, + y, + cv=3, + exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10), + error_score="raise", + params={"sample_weight": np.ones(3)}, + ) + + learning_curve( + estimator, + X, + y, + cv=3, + exploit_incremental_learning=True, + train_sizes=np.linspace(0.1, 1.0, 10), + error_score="raise", + params={"sample_weight": np.ones(2)}, + ) + + +def test_validation_curve(): + X, y = make_classification( + n_samples=2, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + param_range = np.linspace(0, 1, 10) + with warnings.catch_warnings(record=True) as w: + train_scores, test_scores = validation_curve( + MockEstimatorWithParameter(), + X, + y, + param_name="param", + param_range=param_range, + cv=2, + ) + if len(w) > 0: + raise RuntimeError("Unexpected warning: %r" % w[0].message) + + assert_array_almost_equal(train_scores.mean(axis=1), param_range) + assert_array_almost_equal(test_scores.mean(axis=1), 1 - param_range) + + +def test_validation_curve_clone_estimator(): + X, y = make_classification( + n_samples=2, + n_features=1, + n_informative=1, + n_redundant=0, + n_classes=2, + n_clusters_per_class=1, + random_state=0, + ) + + param_range = np.linspace(1, 0, 10) + _, _ = validation_curve( + MockEstimatorWithSingleFitCallAllowed(), + X, + y, + param_name="param", + param_range=param_range, + cv=2, + ) + + +def test_validation_curve_cv_splits_consistency(): + n_samples = 100 + n_splits = 5 + X, y = make_classification(n_samples=100, random_state=0) + + scores1 = validation_curve( + SVC(kernel="linear", random_state=0), + X, + y, + param_name="C", + param_range=[0.1, 0.1, 0.2, 0.2], + cv=OneTimeSplitter(n_splits=n_splits, n_samples=n_samples), + ) + # The OneTimeSplitter is a non-re-entrant cv splitter. Unless, the + # `split` is called for each parameter, the following should produce + # identical results for param setting 1 and param setting 2 as both have + # the same C value. + assert_array_almost_equal(*np.vsplit(np.hstack(scores1)[(0, 2, 1, 3), :], 2)) + + scores2 = validation_curve( + SVC(kernel="linear", random_state=0), + X, + y, + param_name="C", + param_range=[0.1, 0.1, 0.2, 0.2], + cv=KFold(n_splits=n_splits, shuffle=True), + ) + + # For scores2, compare the 1st and 2nd parameter's scores + # (Since the C value for 1st two param setting is 0.1, they must be + # consistent unless the train test folds differ between the param settings) + assert_array_almost_equal(*np.vsplit(np.hstack(scores2)[(0, 2, 1, 3), :], 2)) + + scores3 = validation_curve( + SVC(kernel="linear", random_state=0), + X, + y, + param_name="C", + param_range=[0.1, 0.1, 0.2, 0.2], + cv=KFold(n_splits=n_splits), + ) + + # OneTimeSplitter is basically unshuffled KFold(n_splits=5). Sanity check. + assert_array_almost_equal(np.array(scores3), np.array(scores1)) + + +def test_validation_curve_params(): + X = np.arange(100).reshape(10, 10) + y = np.array([0] * 5 + [1] * 5) + clf = CheckingClassifier(expected_sample_weight=True) + + err_msg = r"Expected sample_weight to be passed" + 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 = r"sample_weight.shape == \(1,\), expected \(8,\)!" + with pytest.raises(ValueError, match=err_msg): + validation_curve( + clf, + X, + y, + param_name="foo_param", + param_range=[1, 2, 3], + error_score="raise", + params={"sample_weight": np.ones(1)}, + ) + validation_curve( + clf, + X, + y, + param_name="foo_param", + param_range=[1, 2, 3], + error_score="raise", + params={"sample_weight": np.ones(10)}, + ) + + +def test_check_is_permutation(): + rng = np.random.RandomState(0) + p = np.arange(100) + rng.shuffle(p) + assert _check_is_permutation(p, 100) + assert not _check_is_permutation(np.delete(p, 23), 100) + + p[0] = 23 + assert not _check_is_permutation(p, 100) + + # Check if the additional duplicate indices are caught + assert not _check_is_permutation(np.hstack((p, 0)), 100) + + +@pytest.mark.parametrize("csr_container", CSR_CONTAINERS) +def test_cross_val_predict_sparse_prediction(csr_container): + # check that cross_val_predict gives same result for sparse and dense input + X, y = make_multilabel_classification( + n_classes=2, + n_labels=1, + allow_unlabeled=False, + return_indicator=True, + random_state=1, + ) + X_sparse = csr_container(X) + y_sparse = csr_container(y) + classif = OneVsRestClassifier(SVC(kernel="linear")) + preds = cross_val_predict(classif, X, y, cv=10) + preds_sparse = cross_val_predict(classif, X_sparse, y_sparse, cv=10) + preds_sparse = preds_sparse.toarray() + assert_array_almost_equal(preds_sparse, preds) + + +def check_cross_val_predict_binary(est, X, y, method): + """Helper for tests of cross_val_predict with binary classification""" + cv = KFold(n_splits=3, shuffle=False) + + # Generate expected outputs + if y.ndim == 1: + exp_shape = (len(X),) if method == "decision_function" else (len(X), 2) + else: + exp_shape = y.shape + expected_predictions = np.zeros(exp_shape) + for train, test in cv.split(X, y): + est = clone(est).fit(X[train], y[train]) + expected_predictions[test] = getattr(est, method)(X[test]) + + # Check actual outputs for several representations of y + for tg in [y, y + 1, y - 2, y.astype("str")]: + assert_allclose( + cross_val_predict(est, X, tg, method=method, cv=cv), expected_predictions + ) + + +def check_cross_val_predict_multiclass(est, X, y, method): + """Helper for tests of cross_val_predict with multiclass classification""" + cv = KFold(n_splits=3, shuffle=False) + + # Generate expected outputs + float_min = np.finfo(np.float64).min + default_values = { + "decision_function": float_min, + "predict_log_proba": float_min, + "predict_proba": 0, + } + expected_predictions = np.full( + (len(X), len(set(y))), default_values[method], dtype=np.float64 + ) + _, y_enc = np.unique(y, return_inverse=True) + for train, test in cv.split(X, y_enc): + est = clone(est).fit(X[train], y_enc[train]) + fold_preds = getattr(est, method)(X[test]) + i_cols_fit = np.unique(y_enc[train]) + expected_predictions[np.ix_(test, i_cols_fit)] = fold_preds + + # Check actual outputs for several representations of y + for tg in [y, y + 1, y - 2, y.astype("str")]: + assert_allclose( + cross_val_predict(est, X, tg, method=method, cv=cv), expected_predictions + ) + + +def check_cross_val_predict_multilabel(est, X, y, method): + """Check the output of cross_val_predict for 2D targets using + Estimators which provide a predictions as a list with one + element per class. + """ + cv = KFold(n_splits=3, shuffle=False) + + # Create empty arrays of the correct size to hold outputs + float_min = np.finfo(np.float64).min + default_values = { + "decision_function": float_min, + "predict_log_proba": float_min, + "predict_proba": 0, + } + n_targets = y.shape[1] + expected_preds = [] + for i_col in range(n_targets): + n_classes_in_label = len(set(y[:, i_col])) + if n_classes_in_label == 2 and method == "decision_function": + exp_shape = (len(X),) + else: + exp_shape = (len(X), n_classes_in_label) + expected_preds.append( + np.full(exp_shape, default_values[method], dtype=np.float64) + ) + + # Generate expected outputs + y_enc_cols = [ + np.unique(y[:, i], return_inverse=True)[1][:, np.newaxis] + for i in range(y.shape[1]) + ] + y_enc = np.concatenate(y_enc_cols, axis=1) + for train, test in cv.split(X, y_enc): + est = clone(est).fit(X[train], y_enc[train]) + fold_preds = getattr(est, method)(X[test]) + for i_col in range(n_targets): + fold_cols = np.unique(y_enc[train][:, i_col]) + if expected_preds[i_col].ndim == 1: + # Decision function with <=2 classes + expected_preds[i_col][test] = fold_preds[i_col] + else: + idx = np.ix_(test, fold_cols) + expected_preds[i_col][idx] = fold_preds[i_col] + + # Check actual outputs for several representations of y + for tg in [y, y + 1, y - 2, y.astype("str")]: + cv_predict_output = cross_val_predict(est, X, tg, method=method, cv=cv) + assert len(cv_predict_output) == len(expected_preds) + for i in range(len(cv_predict_output)): + assert_allclose(cv_predict_output[i], expected_preds[i]) + + +def check_cross_val_predict_with_method_binary(est): + # This test includes the decision_function with two classes. + # This is a special case: it has only one column of output. + X, y = make_classification(n_classes=2, random_state=0) + for method in ["decision_function", "predict_proba", "predict_log_proba"]: + check_cross_val_predict_binary(est, X, y, method) + + +def check_cross_val_predict_with_method_multiclass(est): + iris = load_iris() + X, y = iris.data, iris.target + X, y = shuffle(X, y, random_state=0) + for method in ["decision_function", "predict_proba", "predict_log_proba"]: + check_cross_val_predict_multiclass(est, X, y, method) + + +def test_cross_val_predict_with_method(): + check_cross_val_predict_with_method_binary(LogisticRegression()) + check_cross_val_predict_with_method_multiclass(LogisticRegression()) + + +def test_cross_val_predict_method_checking(): + # Regression test for issue #9639. Tests that cross_val_predict does not + # check estimator methods (e.g. predict_proba) before fitting + iris = load_iris() + X, y = iris.data, iris.target + X, y = shuffle(X, y, random_state=0) + for method in ["decision_function", "predict_proba", "predict_log_proba"]: + est = SGDClassifier(loss="log_loss", random_state=2) + check_cross_val_predict_multiclass(est, X, y, method) + + +def test_gridsearchcv_cross_val_predict_with_method(): + iris = load_iris() + X, y = iris.data, iris.target + X, y = shuffle(X, y, random_state=0) + est = GridSearchCV(LogisticRegression(random_state=42), {"C": [0.1, 1]}, cv=2) + for method in ["decision_function", "predict_proba", "predict_log_proba"]: + check_cross_val_predict_multiclass(est, X, y, method) + + +def test_cross_val_predict_with_method_multilabel_ovr(): + # OVR does multilabel predictions, but only arrays of + # binary indicator columns. The output of predict_proba + # is a 2D array with shape (n_samples, n_classes). + n_samp = 100 + n_classes = 4 + X, y = make_multilabel_classification( + n_samples=n_samp, n_labels=3, n_classes=n_classes, n_features=5, random_state=42 + ) + est = OneVsRestClassifier(LogisticRegression(solver="liblinear", random_state=0)) + for method in ["predict_proba", "decision_function"]: + check_cross_val_predict_binary(est, X, y, method=method) + + +class RFWithDecisionFunction(RandomForestClassifier): + # None of the current multioutput-multiclass estimators have + # decision function methods. Create a mock decision function + # to test the cross_val_predict function's handling of this case. + def decision_function(self, X): + probs = self.predict_proba(X) + msg = "This helper should only be used on multioutput-multiclass tasks" + assert isinstance(probs, list), msg + probs = [p[:, -1] if p.shape[1] == 2 else p for p in probs] + return probs + + +def test_cross_val_predict_with_method_multilabel_rf(): + # The RandomForest allows multiple classes in each label. + # Output of predict_proba is a list of outputs of predict_proba + # for each individual label. + n_classes = 4 + X, y = make_multilabel_classification( + n_samples=100, n_labels=3, n_classes=n_classes, n_features=5, random_state=42 + ) + y[:, 0] += y[:, 1] # Put three classes in the first column + for method in ["predict_proba", "predict_log_proba", "decision_function"]: + est = RFWithDecisionFunction(n_estimators=5, random_state=0) + with warnings.catch_warnings(): + # Suppress "RuntimeWarning: divide by zero encountered in log" + warnings.simplefilter("ignore") + check_cross_val_predict_multilabel(est, X, y, method=method) + + +def test_cross_val_predict_with_method_rare_class(): + # Test a multiclass problem where one class will be missing from + # one of the CV training sets. + rng = np.random.RandomState(0) + X = rng.normal(0, 1, size=(14, 10)) + y = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 3]) + est = LogisticRegression() + for method in ["predict_proba", "predict_log_proba", "decision_function"]: + with warnings.catch_warnings(): + # Suppress warning about too few examples of a class + warnings.simplefilter("ignore") + check_cross_val_predict_multiclass(est, X, y, method) + + +def test_cross_val_predict_with_method_multilabel_rf_rare_class(): + # The RandomForest allows anything for the contents of the labels. + # Output of predict_proba is a list of outputs of predict_proba + # for each individual label. + # In this test, the first label has a class with a single example. + # We'll have one CV fold where the training data don't include it. + rng = np.random.RandomState(0) + X = rng.normal(0, 1, size=(5, 10)) + y = np.array([[0, 0], [1, 1], [2, 1], [0, 1], [1, 0]]) + for method in ["predict_proba", "predict_log_proba"]: + est = RFWithDecisionFunction(n_estimators=5, random_state=0) + with warnings.catch_warnings(): + # Suppress "RuntimeWarning: divide by zero encountered in log" + warnings.simplefilter("ignore") + check_cross_val_predict_multilabel(est, X, y, method=method) + + +def get_expected_predictions(X, y, cv, classes, est, method): + expected_predictions = np.zeros([len(y), classes]) + func = getattr(est, method) + + for train, test in cv.split(X, y): + est.fit(X[train], y[train]) + expected_predictions_ = func(X[test]) + # To avoid 2 dimensional indexing + if method == "predict_proba": + exp_pred_test = np.zeros((len(test), classes)) + else: + exp_pred_test = np.full( + (len(test), classes), np.finfo(expected_predictions.dtype).min + ) + exp_pred_test[:, est.classes_] = expected_predictions_ + expected_predictions[test] = exp_pred_test + + return expected_predictions + + +def test_cross_val_predict_class_subset(): + X = np.arange(200).reshape(100, 2) + y = np.array([x // 10 for x in range(100)]) + classes = 10 + + kfold3 = KFold(n_splits=3) + kfold4 = KFold(n_splits=4) + + le = LabelEncoder() + + methods = ["decision_function", "predict_proba", "predict_log_proba"] + for method in methods: + est = LogisticRegression() + + # Test with n_splits=3 + predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) + + # Runs a naive loop (should be same as cross_val_predict): + expected_predictions = get_expected_predictions( + X, y, kfold3, classes, est, method + ) + assert_array_almost_equal(expected_predictions, predictions) + + # Test with n_splits=4 + predictions = cross_val_predict(est, X, y, method=method, cv=kfold4) + expected_predictions = get_expected_predictions( + X, y, kfold4, classes, est, method + ) + assert_array_almost_equal(expected_predictions, predictions) + + # Testing unordered labels + y = shuffle(np.repeat(range(10), 10), random_state=0) + predictions = cross_val_predict(est, X, y, method=method, cv=kfold3) + y = le.fit_transform(y) + expected_predictions = get_expected_predictions( + X, y, kfold3, classes, est, method + ) + assert_array_almost_equal(expected_predictions, predictions) + + +def test_score_memmap(): + # Ensure a scalar score of memmap type is accepted + iris = load_iris() + X, y = iris.data, iris.target + clf = MockClassifier() + tf = tempfile.NamedTemporaryFile(mode="wb", delete=False) + tf.write(b"Hello world!!!!!") + tf.close() + scores = np.memmap(tf.name, dtype=np.float64) + score = np.memmap(tf.name, shape=(), mode="r", dtype=np.float64) + try: + cross_val_score(clf, X, y, scoring=lambda est, X, y: score) + with pytest.raises(ValueError): + cross_val_score(clf, X, y, scoring=lambda est, X, y: scores) + finally: + # Best effort to release the mmap file handles before deleting the + # backing file under Windows + scores, score = None, None + for _ in range(3): + try: + os.unlink(tf.name) + break + except OSError: + sleep(1.0) + + +def test_permutation_test_score_pandas(): + # check permutation_test_score doesn't destroy pandas dataframe + types = [(MockDataFrame, MockDataFrame)] + try: + from pandas import DataFrame, Series + + types.append((Series, DataFrame)) + except ImportError: + pass + for TargetType, InputFeatureType in types: + # X dataframe, y series + iris = load_iris() + X, y = iris.data, iris.target + X_df, y_ser = InputFeatureType(X), TargetType(y) + check_df = lambda x: isinstance(x, InputFeatureType) + check_series = lambda x: isinstance(x, TargetType) + clf = CheckingClassifier(check_X=check_df, check_y=check_series) + permutation_test_score(clf, X_df, y_ser) + + +def test_fit_and_score_failing(): + # Create a failing classifier to deliberately fail + failing_clf = FailingClassifier(FailingClassifier.FAILING_PARAMETER) + # dummy X data + X = np.arange(1, 10) + train, test = np.arange(0, 5), np.arange(5, 9) + fit_and_score_args = dict( + estimator=failing_clf, + X=X, + y=None, + scorer=dict(), + train=train, + test=test, + verbose=0, + parameters=None, + fit_params=None, + score_params=None, + ) + # passing error score to trigger the warning message + fit_and_score_args["error_score"] = "raise" + # check if exception was raised, with default error_score='raise' + with pytest.raises(ValueError, match="Failing classifier failed as required"): + _fit_and_score(**fit_and_score_args) + + assert failing_clf.score() == 0.0 # FailingClassifier coverage + + +def test_fit_and_score_working(): + X, y = make_classification(n_samples=30, random_state=0) + clf = SVC(kernel="linear", random_state=0) + train, test = next(ShuffleSplit().split(X)) + # Test return_parameters option + fit_and_score_args = dict( + estimator=clf, + X=X, + y=y, + scorer=dict(), + train=train, + test=test, + verbose=0, + parameters={"max_iter": 100, "tol": 0.1}, + fit_params=None, + score_params=None, + return_parameters=True, + ) + result = _fit_and_score(**fit_and_score_args) + assert result["parameters"] == fit_and_score_args["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_some_failing_fits_warning(error_score): + # Create a failing classifier to deliberately fail + failing_clf = DataDependentFailingClassifier(max_x_value=8) + # dummy X data + X = np.arange(1, 10) + y = np.ones(9) + # passing error score to trigger the warning message + cross_validate_args = [failing_clf, X, y] + 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( + ( + "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']}.+{individual_fit_error_message}" + ), + flags=re.DOTALL, + ) + + with pytest.warns(FitFailedWarning, match=warning_message): + cross_validate(*cross_validate_args, **cross_validate_kwargs) + + +@pytest.mark.parametrize("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.raises(ValueError, match=error_message): + cross_validate(*cross_validate_args, **cross_validate_kwargs) + + +def _failing_scorer(estimator, X, y, error_msg): + raise ValueError(error_msg) + + +@pytest.mark.filterwarnings("ignore:lbfgs failed to converge") +@pytest.mark.parametrize("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 = ( + "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) + + +@pytest.mark.filterwarnings("ignore:lbfgs failed to converge") +@pytest.mark.parametrize("error_score", [np.nan, 0, "raise"]) +@pytest.mark.parametrize("return_train_score", [True, False]) +@pytest.mark.parametrize("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 replace it with `error_score`. In the multimetric + # case also check the result of a non-failing scorer where the other scorers + # are failing. + 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: + non_failing_scorer = make_scorer(mean_squared_error) + scoring = { + "score_1": failing_scorer, + "score_2": non_failing_scorer, + "score_3": 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 = ( + "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: + if "_score_2" in key: + # check the test (and optionally train) score for the + # scorer that should be non-failing + for i in results[key]: + assert isinstance(i, float) + else: + # 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 + + +@pytest.mark.parametrize( + "train_score, scorer, verbose, split_prg, cdt_prg, expected", + [ + ( + False, + three_params_scorer, + 2, + (1, 3), + (0, 1), + r"\[CV\] END ...................................................." + r" total time= 0.\ds", + ), + ( + True, + _MultimetricScorer( + scorers={"sc1": three_params_scorer, "sc2": three_params_scorer} + ), + 3, + (1, 3), + (0, 1), + r"\[CV 2/3\] END sc1: \(train=3.421, test=3.421\) sc2: " + r"\(train=3.421, test=3.421\) total time= 0.\ds", + ), + ( + False, + _MultimetricScorer( + scorers={"sc1": three_params_scorer, "sc2": three_params_scorer} + ), + 10, + (1, 3), + (0, 1), + r"\[CV 2/3; 1/1\] END ....... sc1: \(test=3.421\) sc2: \(test=3.421\)" + r" total time= 0.\ds", + ), + ], +) +def test_fit_and_score_verbosity( + capsys, train_score, scorer, verbose, split_prg, cdt_prg, expected +): + X, y = make_classification(n_samples=30, random_state=0) + clf = SVC(kernel="linear", random_state=0) + train, test = next(ShuffleSplit().split(X)) + + # test print without train score + fit_and_score_args = dict( + estimator=clf, + X=X, + y=y, + scorer=scorer, + train=train, + test=test, + verbose=verbose, + parameters=None, + fit_params=None, + score_params=None, + return_train_score=train_score, + split_progress=split_prg, + candidate_progress=cdt_prg, + ) + _fit_and_score(**fit_and_score_args) + out, _ = capsys.readouterr() + outlines = out.split("\n") + if len(outlines) > 2: + assert re.match(expected, outlines[1]) + else: + assert re.match(expected, outlines[0]) + + +def test_score(): + error_message = "scoring must return a number, got None" + + def two_params_scorer(estimator, X_test): + return None + + with pytest.raises(ValueError, match=error_message): + _score( + estimator=None, + X_test=None, + y_test=None, + scorer=two_params_scorer, + score_params=None, + error_score=np.nan, + ) + + +def test_callable_multimetric_confusion_matrix_cross_validate(): + def custom_scorer(clf, X, y): + y_pred = clf.predict(X) + cm = confusion_matrix(y, y_pred) + return {"tn": cm[0, 0], "fp": cm[0, 1], "fn": cm[1, 0], "tp": cm[1, 1]} + + X, y = make_classification(n_samples=40, n_features=4, random_state=42) + est = LinearSVC(random_state=42) + est.fit(X, y) + cv_results = cross_validate(est, X, y, cv=5, scoring=custom_scorer) + + score_names = ["tn", "fp", "fn", "tp"] + for name in score_names: + assert "test_{}".format(name) in cv_results + + +def test_learning_curve_partial_fit_regressors(): + """Check that regressors with partial_fit is supported. + + Non-regression test for #22981. + """ + X, y = make_regression(random_state=42) + + # Does not error + learning_curve(MLPRegressor(), X, y, exploit_incremental_learning=True, cv=2) + + +def test_learning_curve_some_failing_fits_warning(global_random_seed): + """Checks for fit failures in `learning_curve` and raises the required warning""" + + X, y = make_classification( + n_samples=30, + n_classes=3, + n_informative=6, + shuffle=False, + random_state=global_random_seed, + ) + # sorting the target to trigger SVC error on the 2 first splits because a single + # class is present + sorted_idx = np.argsort(y) + X, y = X[sorted_idx], y[sorted_idx] + + svc = SVC() + warning_message = "10 fits failed out of a total of 25" + + with pytest.warns(FitFailedWarning, match=warning_message): + _, train_score, test_score, *_ = learning_curve( + svc, X, y, cv=5, error_score=np.nan + ) + + # the first 2 splits should lead to warnings and thus np.nan scores + for idx in range(2): + assert np.isnan(train_score[idx]).all() + assert np.isnan(test_score[idx]).all() + + for idx in range(2, train_score.shape[0]): + assert not np.isnan(train_score[idx]).any() + assert not np.isnan(test_score[idx]).any() + + +def test_cross_validate_return_indices(global_random_seed): + """Check the behaviour of `return_indices` in `cross_validate`.""" + X, y = load_iris(return_X_y=True) + X = scale(X) # scale features for better convergence + estimator = LogisticRegression() + + cv = KFold(n_splits=3, shuffle=True, random_state=global_random_seed) + cv_results = cross_validate(estimator, X, y, cv=cv, n_jobs=2, return_indices=False) + assert "indices" not in cv_results + + cv_results = cross_validate(estimator, X, y, cv=cv, n_jobs=2, return_indices=True) + assert "indices" in cv_results + train_indices = cv_results["indices"]["train"] + test_indices = cv_results["indices"]["test"] + assert len(train_indices) == cv.n_splits + assert len(test_indices) == cv.n_splits + + assert_array_equal([indices.size for indices in train_indices], 100) + assert_array_equal([indices.size for indices in test_indices], 50) + + for split_idx, (expected_train_idx, expected_test_idx) in enumerate(cv.split(X, y)): + assert_array_equal(train_indices[split_idx], expected_train_idx) + assert_array_equal(test_indices[split_idx], expected_test_idx) + + +# Tests for metadata routing in cross_val* and in *curve +# ====================================================== + + +# TODO(1.8): remove `learning_curve`, `validation_curve` and `permutation_test_score`. +@pytest.mark.parametrize( + "func, extra_args", + [ + (learning_curve, {}), + (permutation_test_score, {}), + (validation_curve, {"param_name": "alpha", "param_range": np.array([1])}), + ], +) +def test_fit_param_deprecation(func, extra_args): + """Check that we warn about deprecating `fit_params`.""" + with pytest.warns(FutureWarning, match="`fit_params` is deprecated"): + func( + estimator=ConsumingClassifier(), X=X, y=y, cv=2, fit_params={}, **extra_args + ) + + with pytest.raises( + ValueError, match="`params` and `fit_params` cannot both be provided" + ): + func( + estimator=ConsumingClassifier(), + X=X, + y=y, + fit_params={}, + params={}, + **extra_args, + ) + + +@pytest.mark.parametrize( + "func, extra_args", + [ + (cross_validate, {}), + (cross_val_score, {}), + (cross_val_predict, {}), + (learning_curve, {}), + (permutation_test_score, {}), + (validation_curve, {"param_name": "alpha", "param_range": np.array([1])}), + ], +) +@config_context(enable_metadata_routing=True) +def test_groups_with_routing_validation(func, extra_args): + """Check that we raise an error if `groups` are passed to the cv method instead + of `params` when metadata routing is enabled. + """ + with pytest.raises(ValueError, match="`groups` can only be passed if"): + func( + estimator=ConsumingClassifier(), + X=X, + y=y, + groups=[], + **extra_args, + ) + + +@pytest.mark.parametrize( + "func, extra_args", + [ + (cross_validate, {}), + (cross_val_score, {}), + (cross_val_predict, {}), + (learning_curve, {}), + (permutation_test_score, {}), + (validation_curve, {"param_name": "alpha", "param_range": np.array([1])}), + ], +) +@config_context(enable_metadata_routing=True) +def test_cross_validate_params_none(func, extra_args): + """Test that no errors are raised when passing `params=None`, which is the + default value. + Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/30447 + """ + X, y = make_classification(n_samples=100, n_classes=2, random_state=0) + func(estimator=ConsumingClassifier(), X=X, y=y, **extra_args) + + +@pytest.mark.parametrize( + "func, extra_args", + [ + (cross_validate, {}), + (cross_val_score, {}), + (cross_val_predict, {}), + (learning_curve, {}), + (permutation_test_score, {}), + (validation_curve, {"param_name": "alpha", "param_range": np.array([1])}), + ], +) +@config_context(enable_metadata_routing=True) +def test_passed_unrequested_metadata(func, extra_args): + """Check that we raise an error when passing metadata that is not + requested.""" + + err_msg = re.escape( + "[metadata] are passed but are not explicitly set as requested or not " + "requested for ConsumingClassifier.fit, which is used within" + ) + with pytest.raises(UnsetMetadataPassedError, match=err_msg): + func( + estimator=ConsumingClassifier(), + X=X, + y=y2, + params=dict(metadata=[]), + **extra_args, + ) + + # cross_val_predict doesn't use scoring + if func == cross_val_predict: + return + + err_msg = re.escape( + "[metadata] are passed but are not explicitly set as requested or not " + "requested for ConsumingClassifier.score, which is used within" + ) + with pytest.raises(UnsetMetadataPassedError, match=err_msg): + func( + estimator=ConsumingClassifier() + .set_fit_request(metadata=True) + .set_partial_fit_request(metadata=True), + X=X, + y=y2, + params=dict(metadata=[]), + **extra_args, + ) + + +@pytest.mark.parametrize( + "func, extra_args", + [ + (cross_validate, {}), + (cross_val_score, {}), + (cross_val_predict, {}), + (learning_curve, {}), + (permutation_test_score, {}), + (validation_curve, {"param_name": "alpha", "param_range": np.array([1])}), + ], +) +@config_context(enable_metadata_routing=True) +def test_validation_functions_routing(func, extra_args): + """Check that the respective cv method is properly dispatching the metadata + to the consumer.""" + scorer_registry = _Registry() + scorer = ConsumingScorer(registry=scorer_registry).set_score_request( + sample_weight="score_weights", metadata="score_metadata" + ) + splitter_registry = _Registry() + splitter = ConsumingSplitter(registry=splitter_registry).set_split_request( + groups="split_groups", metadata="split_metadata" + ) + estimator_registry = _Registry() + estimator = ConsumingClassifier(registry=estimator_registry).set_fit_request( + sample_weight="fit_sample_weight", metadata="fit_metadata" + ) + + n_samples = _num_samples(X) + rng = np.random.RandomState(0) + score_weights = rng.rand(n_samples) + score_metadata = rng.rand(n_samples) + split_groups = rng.randint(0, 3, n_samples) + split_metadata = rng.rand(n_samples) + fit_sample_weight = rng.rand(n_samples) + fit_metadata = rng.rand(n_samples) + + scoring_args = { + cross_validate: dict(scoring=dict(my_scorer=scorer, accuracy="accuracy")), + cross_val_score: dict(scoring=scorer), + learning_curve: dict(scoring=scorer), + validation_curve: dict(scoring=scorer), + permutation_test_score: dict(scoring=scorer), + cross_val_predict: dict(), + } + + params = dict( + split_groups=split_groups, + split_metadata=split_metadata, + fit_sample_weight=fit_sample_weight, + fit_metadata=fit_metadata, + ) + + if func is not cross_val_predict: + params.update( + score_weights=score_weights, + score_metadata=score_metadata, + ) + + func( + estimator, + X=X, + y=y, + cv=splitter, + **scoring_args[func], + **extra_args, + params=params, + ) + + if func is not cross_val_predict: + # cross_val_predict doesn't need a scorer + assert len(scorer_registry) + for _scorer in scorer_registry: + check_recorded_metadata( + obj=_scorer, + method="score", + parent=func.__name__, + split_params=("sample_weight", "metadata"), + sample_weight=score_weights, + metadata=score_metadata, + ) + + assert len(splitter_registry) + for _splitter in splitter_registry: + check_recorded_metadata( + obj=_splitter, + method="split", + parent=func.__name__, + groups=split_groups, + metadata=split_metadata, + ) + + assert len(estimator_registry) + for _estimator in estimator_registry: + check_recorded_metadata( + obj=_estimator, + method="fit", + parent=func.__name__, + split_params=("sample_weight", "metadata"), + sample_weight=fit_sample_weight, + metadata=fit_metadata, + ) + + +@config_context(enable_metadata_routing=True) +def test_learning_curve_exploit_incremental_learning_routing(): + """Test that learning_curve routes metadata to the estimator correctly while + partial_fitting it with `exploit_incremental_learning=True`.""" + + n_samples = _num_samples(X) + rng = np.random.RandomState(0) + fit_sample_weight = rng.rand(n_samples) + fit_metadata = rng.rand(n_samples) + + estimator_registry = _Registry() + estimator = ConsumingClassifier( + registry=estimator_registry + ).set_partial_fit_request( + sample_weight="fit_sample_weight", metadata="fit_metadata" + ) + + learning_curve( + estimator, + X=X, + y=y, + cv=ConsumingSplitter(), + exploit_incremental_learning=True, + params=dict(fit_sample_weight=fit_sample_weight, fit_metadata=fit_metadata), + ) + + assert len(estimator_registry) + for _estimator in estimator_registry: + check_recorded_metadata( + obj=_estimator, + method="partial_fit", + parent="learning_curve", + split_params=("sample_weight", "metadata"), + sample_weight=fit_sample_weight, + metadata=fit_metadata, + ) + + +# End of metadata routing tests +# ============================= diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/__init__.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e0de99f5e7e37bb92643ad29f3c859c689d4918 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/__init__.py @@ -0,0 +1,42 @@ +"""The k-nearest neighbors algorithms.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +from ._ball_tree import BallTree +from ._base import VALID_METRICS, VALID_METRICS_SPARSE, sort_graph_by_row_values +from ._classification import KNeighborsClassifier, RadiusNeighborsClassifier +from ._graph import ( + KNeighborsTransformer, + RadiusNeighborsTransformer, + kneighbors_graph, + radius_neighbors_graph, +) +from ._kd_tree import KDTree +from ._kde import KernelDensity +from ._lof import LocalOutlierFactor +from ._nca import NeighborhoodComponentsAnalysis +from ._nearest_centroid import NearestCentroid +from ._regression import KNeighborsRegressor, RadiusNeighborsRegressor +from ._unsupervised import NearestNeighbors + +__all__ = [ + "VALID_METRICS", + "VALID_METRICS_SPARSE", + "BallTree", + "KDTree", + "KNeighborsClassifier", + "KNeighborsRegressor", + "KNeighborsTransformer", + "KernelDensity", + "LocalOutlierFactor", + "NearestCentroid", + "NearestNeighbors", + "NeighborhoodComponentsAnalysis", + "RadiusNeighborsClassifier", + "RadiusNeighborsRegressor", + "RadiusNeighborsTransformer", + "kneighbors_graph", + "radius_neighbors_graph", + "sort_graph_by_row_values", +] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..44d876187c54f370a6acaa72645c39371526fac8 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_ball_tree.pyx.tp @@ -0,0 +1,284 @@ +{{py: + +# Generated file: _ball_tree.pyx + +implementation_specific_values = [ + # The values are arranged as follows: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + # + ('64', 'float64_t', 'np.float64'), + ('32', 'float32_t', 'np.float32') +] + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +}} + + +__all__ = ['BallTree', 'BallTree64', 'BallTree32'] + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +DOC_DICT{{name_suffix}} = { + 'BinaryTree': 'BallTree{{name_suffix}}', + 'binary_tree': 'ball_tree{{name_suffix}}', +} + +VALID_METRICS{{name_suffix}} = [ + 'BrayCurtisDistance{{name_suffix}}', + 'CanberraDistance{{name_suffix}}', + 'ChebyshevDistance{{name_suffix}}', + 'DiceDistance{{name_suffix}}', + 'EuclideanDistance{{name_suffix}}', + 'HammingDistance{{name_suffix}}', + 'HaversineDistance{{name_suffix}}', + 'JaccardDistance{{name_suffix}}', + 'MahalanobisDistance{{name_suffix}}', + 'ManhattanDistance{{name_suffix}}', + 'MinkowskiDistance{{name_suffix}}', + 'PyFuncDistance{{name_suffix}}', + 'RogersTanimotoDistance{{name_suffix}}', + 'RussellRaoDistance{{name_suffix}}', + 'SEuclideanDistance{{name_suffix}}', + 'SokalMichenerDistance{{name_suffix}}', + 'SokalSneathDistance{{name_suffix}}', + 'WMinkowskiDistance{{name_suffix}}', +] + +{{endfor}} + +include "_binary_tree.pxi" + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +# Inherit BallTree{{name_suffix}} from BinaryTree{{name_suffix}} +cdef class BallTree{{name_suffix}}(BinaryTree{{name_suffix}}): + __doc__ = CLASS_DOC.format(**DOC_DICT{{name_suffix}}) + pass + +{{endfor}} + + +#---------------------------------------------------------------------- +# The functions below specialized the Binary Tree as a Ball Tree +# +# Note that these functions use the concept of "reduced distance". +# The reduced distance, defined for some metrics, is a quantity which +# is more efficient to compute than the distance, but preserves the +# relative rankings of the true distance. For example, the reduced +# distance for the Euclidean metric is the squared-euclidean distance. +# For some metrics, the reduced distance is simply the distance. + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +cdef int allocate_data{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t n_nodes, + intp_t n_features, +) except -1: + """Allocate arrays needed for the KD Tree""" + tree.node_bounds = np.zeros((1, n_nodes, n_features), dtype={{INPUT_DTYPE}}) + return 0 + + +cdef int init_node{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + NodeData_t[::1] node_data, + intp_t i_node, + intp_t idx_start, + intp_t idx_end, +) except -1: + """Initialize the node for the dataset stored in tree.data""" + cdef intp_t n_features = tree.data.shape[1] + cdef intp_t n_points = idx_end - idx_start + + cdef intp_t i, j + cdef float64_t radius + cdef const {{INPUT_DTYPE_t}} *this_pt + + cdef intp_t* idx_array = &tree.idx_array[0] + cdef const {{INPUT_DTYPE_t}}* data = &tree.data[0, 0] + cdef {{INPUT_DTYPE_t}}* centroid = &tree.node_bounds[0, i_node, 0] + + cdef bint with_sample_weight = tree.sample_weight is not None + cdef const {{INPUT_DTYPE_t}}* sample_weight + cdef float64_t sum_weight_node + if with_sample_weight: + sample_weight = &tree.sample_weight[0] + + # determine Node centroid + for j in range(n_features): + centroid[j] = 0 + + if with_sample_weight: + sum_weight_node = 0 + for i in range(idx_start, idx_end): + sum_weight_node += sample_weight[idx_array[i]] + this_pt = data + n_features * idx_array[i] + for j from 0 <= j < n_features: + centroid[j] += this_pt[j] * sample_weight[idx_array[i]] + + for j in range(n_features): + centroid[j] /= sum_weight_node + else: + for i in range(idx_start, idx_end): + this_pt = data + n_features * idx_array[i] + for j from 0 <= j < n_features: + centroid[j] += this_pt[j] + + for j in range(n_features): + centroid[j] /= n_points + + # determine Node radius + radius = 0 + for i in range(idx_start, idx_end): + radius = fmax(radius, + tree.rdist(centroid, + data + n_features * idx_array[i], + n_features)) + + node_data[i_node].radius = tree.dist_metric._rdist_to_dist(radius) + node_data[i_node].idx_start = idx_start + node_data[i_node].idx_end = idx_end + return 0 + + +cdef inline float64_t min_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1 nogil: + """Compute the minimum distance between a point and a node""" + cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + tree.data.shape[1]) + return fmax(0, dist_pt - tree.node_data[i_node].radius) + + +cdef inline float64_t max_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1: + """Compute the maximum distance between a point and a node""" + cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + tree.data.shape[1]) + return dist_pt + tree.node_data[i_node].radius + + +cdef inline int min_max_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + float64_t* min_dist, + float64_t* max_dist, +) except -1 nogil: + """Compute the minimum and maximum distance between a point and a node""" + cdef float64_t dist_pt = tree.dist(pt, &tree.node_bounds[0, i_node, 0], + tree.data.shape[1]) + cdef float64_t rad = tree.node_data[i_node].radius + min_dist[0] = fmax(0, dist_pt - rad) + max_dist[0] = dist_pt + rad + return 0 + + +cdef inline float64_t min_rdist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1 nogil: + """Compute the minimum reduced-distance between a point and a node""" + if tree.euclidean: + return euclidean_dist_to_rdist{{name_suffix}}( + min_dist{{name_suffix}}(tree, i_node, pt) + ) + else: + return tree.dist_metric._dist_to_rdist( + min_dist{{name_suffix}}(tree, i_node, pt) + ) + + +cdef inline float64_t max_rdist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1: + """Compute the maximum reduced-distance between a point and a node""" + if tree.euclidean: + return euclidean_dist_to_rdist{{name_suffix}}( + max_dist{{name_suffix}}(tree, i_node, pt) + ) + else: + return tree.dist_metric._dist_to_rdist( + max_dist{{name_suffix}}(tree, i_node, pt) + ) + + +cdef inline float64_t min_dist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """compute the minimum distance between two nodes""" + cdef float64_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + &tree1.node_bounds[0, i_node1, 0], + tree1.data.shape[1]) + return fmax(0, (dist_pt - tree1.node_data[i_node1].radius + - tree2.node_data[i_node2].radius)) + + +cdef inline float64_t max_dist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """compute the maximum distance between two nodes""" + cdef float64_t dist_pt = tree1.dist(&tree2.node_bounds[0, i_node2, 0], + &tree1.node_bounds[0, i_node1, 0], + tree1.data.shape[1]) + return (dist_pt + tree1.node_data[i_node1].radius + + tree2.node_data[i_node2].radius) + + +cdef inline float64_t min_rdist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """compute the minimum reduced distance between two nodes""" + if tree1.euclidean: + return euclidean_dist_to_rdist{{name_suffix}}( + min_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + else: + return tree1.dist_metric._dist_to_rdist( + min_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + + +cdef inline float64_t max_rdist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """compute the maximum reduced distance between two nodes""" + if tree1.euclidean: + return euclidean_dist_to_rdist{{name_suffix}}( + max_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + else: + return tree1.dist_metric._dist_to_rdist( + max_dist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + +{{endfor}} + + +class BallTree(BallTree64): + __doc__ = CLASS_DOC.format(BinaryTree="BallTree") + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_base.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..767eee1358aa873808ab7796d080cea06bae97bc --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_base.py @@ -0,0 +1,1404 @@ +"""Base and mixin classes for nearest neighbors.""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +import numbers +import warnings +from abc import ABCMeta, abstractmethod +from functools import partial +from numbers import Integral, Real + +import numpy as np +from joblib import effective_n_jobs +from scipy.sparse import csr_matrix, issparse + +from ..base import BaseEstimator, MultiOutputMixin, is_classifier +from ..exceptions import DataConversionWarning, EfficiencyWarning +from ..metrics import DistanceMetric, pairwise_distances_chunked +from ..metrics._pairwise_distances_reduction import ( + ArgKmin, + RadiusNeighbors, +) +from ..metrics.pairwise import PAIRWISE_DISTANCE_FUNCTIONS +from ..utils import ( + check_array, + gen_even_slices, + get_tags, +) +from ..utils._param_validation import Interval, StrOptions, validate_params +from ..utils.fixes import parse_version, sp_base_version +from ..utils.multiclass import check_classification_targets +from ..utils.parallel import Parallel, delayed +from ..utils.validation import _to_object_array, check_is_fitted, validate_data +from ._ball_tree import BallTree +from ._kd_tree import KDTree + +SCIPY_METRICS = [ + "braycurtis", + "canberra", + "chebyshev", + "correlation", + "cosine", + "dice", + "hamming", + "jaccard", + "mahalanobis", + "minkowski", + "rogerstanimoto", + "russellrao", + "seuclidean", + "sokalsneath", + "sqeuclidean", + "yule", +] +if sp_base_version < parse_version("1.17"): + # Deprecated in SciPy 1.15 and removed in SciPy 1.17 + SCIPY_METRICS += ["sokalmichener"] +if sp_base_version < parse_version("1.11"): + # Deprecated in SciPy 1.9 and removed in SciPy 1.11 + SCIPY_METRICS += ["kulsinski"] +if sp_base_version < parse_version("1.9"): + # Deprecated in SciPy 1.0 and removed in SciPy 1.9 + SCIPY_METRICS += ["matching"] + +VALID_METRICS = dict( + ball_tree=BallTree.valid_metrics, + kd_tree=KDTree.valid_metrics, + # The following list comes from the + # sklearn.metrics.pairwise doc string + brute=sorted(set(PAIRWISE_DISTANCE_FUNCTIONS).union(SCIPY_METRICS)), +) + +VALID_METRICS_SPARSE = dict( + ball_tree=[], + kd_tree=[], + brute=(PAIRWISE_DISTANCE_FUNCTIONS.keys() - {"haversine", "nan_euclidean"}), +) + + +def _get_weights(dist, weights): + """Get the weights from an array of distances and a parameter ``weights``. + + Assume weights have already been validated. + + Parameters + ---------- + dist : ndarray + The input distances. + + weights : {'uniform', 'distance'}, callable or None + The kind of weighting used. + + Returns + ------- + weights_arr : array of the same shape as ``dist`` + If ``weights == 'uniform'``, then returns None. + """ + if weights in (None, "uniform"): + return None + + if weights == "distance": + # if user attempts to classify a point that was zero distance from one + # or more training points, those training points are weighted as 1.0 + # and the other points as 0.0 + if dist.dtype is np.dtype(object): + for point_dist_i, point_dist in enumerate(dist): + # check if point_dist is iterable + # (ex: RadiusNeighborClassifier.predict may set an element of + # dist to 1e-6 to represent an 'outlier') + if hasattr(point_dist, "__contains__") and 0.0 in point_dist: + dist[point_dist_i] = point_dist == 0.0 + else: + dist[point_dist_i] = 1.0 / point_dist + else: + with np.errstate(divide="ignore"): + dist = 1.0 / dist + inf_mask = np.isinf(dist) + inf_row = np.any(inf_mask, axis=1) + dist[inf_row] = inf_mask[inf_row] + return dist + + if callable(weights): + return weights(dist) + + +def _is_sorted_by_data(graph): + """Return whether the graph's non-zero entries are sorted by data. + + The non-zero entries are stored in graph.data and graph.indices. + For each row (or sample), the non-zero entries can be either: + - sorted by indices, as after graph.sort_indices(); + - sorted by data, as after _check_precomputed(graph); + - not sorted. + + Parameters + ---------- + graph : sparse matrix of shape (n_samples, n_samples) + Neighbors graph as given by `kneighbors_graph` or + `radius_neighbors_graph`. Matrix should be of format CSR format. + + Returns + ------- + res : bool + Whether input graph is sorted by data. + """ + assert graph.format == "csr" + out_of_order = graph.data[:-1] > graph.data[1:] + line_change = np.unique(graph.indptr[1:-1] - 1) + line_change = line_change[line_change < out_of_order.shape[0]] + return out_of_order.sum() == out_of_order[line_change].sum() + + +def _check_precomputed(X): + """Check precomputed distance matrix. + + If the precomputed distance matrix is sparse, it checks that the non-zero + entries are sorted by distances. If not, the matrix is copied and sorted. + + Parameters + ---------- + X : {sparse matrix, array-like}, (n_samples, n_samples) + Distance matrix to other samples. X may be a sparse matrix, in which + case only non-zero elements may be considered neighbors. + + Returns + ------- + X : {sparse matrix, array-like}, (n_samples, n_samples) + Distance matrix to other samples. X may be a sparse matrix, in which + case only non-zero elements may be considered neighbors. + """ + if not issparse(X): + X = check_array(X, ensure_non_negative=True, input_name="X") + return X + else: + graph = X + + if graph.format not in ("csr", "csc", "coo", "lil"): + raise TypeError( + "Sparse matrix in {!r} format is not supported due to " + "its handling of explicit zeros".format(graph.format) + ) + copied = graph.format != "csr" + graph = check_array( + graph, + accept_sparse="csr", + ensure_non_negative=True, + input_name="precomputed distance matrix", + ) + graph = sort_graph_by_row_values(graph, copy=not copied, warn_when_not_sorted=True) + + return graph + + +@validate_params( + { + "graph": ["sparse matrix"], + "copy": ["boolean"], + "warn_when_not_sorted": ["boolean"], + }, + prefer_skip_nested_validation=True, +) +def sort_graph_by_row_values(graph, copy=False, warn_when_not_sorted=True): + """Sort a sparse graph such that each row is stored with increasing values. + + .. versionadded:: 1.2 + + Parameters + ---------- + graph : sparse matrix of shape (n_samples, n_samples) + Distance matrix to other samples, where only non-zero elements are + considered neighbors. Matrix is converted to CSR format if not already. + + copy : bool, default=False + If True, the graph is copied before sorting. If False, the sorting is + performed inplace. If the graph is not of CSR format, `copy` must be + True to allow the conversion to CSR format, otherwise an error is + raised. + + warn_when_not_sorted : bool, default=True + If True, a :class:`~sklearn.exceptions.EfficiencyWarning` is raised + when the input graph is not sorted by row values. + + Returns + ------- + graph : sparse matrix of shape (n_samples, n_samples) + Distance matrix to other samples, where only non-zero elements are + considered neighbors. Matrix is in CSR format. + + Examples + -------- + >>> from scipy.sparse import csr_matrix + >>> from sklearn.neighbors import sort_graph_by_row_values + >>> X = csr_matrix( + ... [[0., 3., 1.], + ... [3., 0., 2.], + ... [1., 2., 0.]]) + >>> X.data + array([3., 1., 3., 2., 1., 2.]) + >>> X_ = sort_graph_by_row_values(X) + >>> X_.data + array([1., 3., 2., 3., 1., 2.]) + """ + if graph.format == "csr" and _is_sorted_by_data(graph): + return graph + + if warn_when_not_sorted: + warnings.warn( + ( + "Precomputed sparse input was not sorted by row values. Use the" + " function sklearn.neighbors.sort_graph_by_row_values to sort the input" + " by row values, with warn_when_not_sorted=False to remove this" + " warning." + ), + EfficiencyWarning, + ) + + if graph.format not in ("csr", "csc", "coo", "lil"): + raise TypeError( + f"Sparse matrix in {graph.format!r} format is not supported due to " + "its handling of explicit zeros" + ) + elif graph.format != "csr": + if not copy: + raise ValueError( + "The input graph is not in CSR format. Use copy=True to allow " + "the conversion to CSR format." + ) + graph = graph.asformat("csr") + elif copy: # csr format with copy=True + graph = graph.copy() + + row_nnz = np.diff(graph.indptr) + if row_nnz.max() == row_nnz.min(): + # if each sample has the same number of provided neighbors + n_samples = graph.shape[0] + distances = graph.data.reshape(n_samples, -1) + + order = np.argsort(distances, kind="mergesort") + order += np.arange(n_samples)[:, None] * row_nnz[0] + order = order.ravel() + graph.data = graph.data[order] + graph.indices = graph.indices[order] + + else: + for start, stop in zip(graph.indptr, graph.indptr[1:]): + order = np.argsort(graph.data[start:stop], kind="mergesort") + graph.data[start:stop] = graph.data[start:stop][order] + graph.indices[start:stop] = graph.indices[start:stop][order] + + return graph + + +def _kneighbors_from_graph(graph, n_neighbors, return_distance): + """Decompose a nearest neighbors sparse graph into distances and indices. + + Parameters + ---------- + graph : sparse matrix of shape (n_samples, n_samples) + Neighbors graph as given by `kneighbors_graph` or + `radius_neighbors_graph`. Matrix should be of format CSR format. + + n_neighbors : int + Number of neighbors required for each sample. + + return_distance : bool + Whether or not to return the distances. + + Returns + ------- + neigh_dist : ndarray of shape (n_samples, n_neighbors) + Distances to nearest neighbors. Only present if `return_distance=True`. + + neigh_ind : ndarray of shape (n_samples, n_neighbors) + Indices of nearest neighbors. + """ + n_samples = graph.shape[0] + assert graph.format == "csr" + + # number of neighbors by samples + row_nnz = np.diff(graph.indptr) + row_nnz_min = row_nnz.min() + if n_neighbors is not None and row_nnz_min < n_neighbors: + raise ValueError( + "%d neighbors per samples are required, but some samples have only" + " %d neighbors in precomputed graph matrix. Decrease number of " + "neighbors used or recompute the graph with more neighbors." + % (n_neighbors, row_nnz_min) + ) + + def extract(a): + # if each sample has the same number of provided neighbors + if row_nnz.max() == row_nnz_min: + return a.reshape(n_samples, -1)[:, :n_neighbors] + else: + idx = np.tile(np.arange(n_neighbors), (n_samples, 1)) + idx += graph.indptr[:-1, None] + return a.take(idx, mode="clip").reshape(n_samples, n_neighbors) + + if return_distance: + return extract(graph.data), extract(graph.indices) + else: + return extract(graph.indices) + + +def _radius_neighbors_from_graph(graph, radius, return_distance): + """Decompose a nearest neighbors sparse graph into distances and indices. + + Parameters + ---------- + graph : sparse matrix of shape (n_samples, n_samples) + Neighbors graph as given by `kneighbors_graph` or + `radius_neighbors_graph`. Matrix should be of format CSR format. + + radius : float + Radius of neighborhoods which should be strictly positive. + + return_distance : bool + Whether or not to return the distances. + + Returns + ------- + neigh_dist : ndarray of shape (n_samples,) of arrays + Distances to nearest neighbors. Only present if `return_distance=True`. + + neigh_ind : ndarray of shape (n_samples,) of arrays + Indices of nearest neighbors. + """ + assert graph.format == "csr" + + no_filter_needed = bool(graph.data.max() <= radius) + + if no_filter_needed: + data, indices, indptr = graph.data, graph.indices, graph.indptr + else: + mask = graph.data <= radius + if return_distance: + data = np.compress(mask, graph.data) + indices = np.compress(mask, graph.indices) + indptr = np.concatenate(([0], np.cumsum(mask)))[graph.indptr] + + indices = indices.astype(np.intp, copy=no_filter_needed) + + if return_distance: + neigh_dist = _to_object_array(np.split(data, indptr[1:-1])) + neigh_ind = _to_object_array(np.split(indices, indptr[1:-1])) + + if return_distance: + return neigh_dist, neigh_ind + else: + return neigh_ind + + +class NeighborsBase(MultiOutputMixin, BaseEstimator, metaclass=ABCMeta): + """Base class for nearest neighbors estimators.""" + + _parameter_constraints: dict = { + "n_neighbors": [Interval(Integral, 1, None, closed="left"), None], + "radius": [Interval(Real, 0, None, closed="both"), None], + "algorithm": [StrOptions({"auto", "ball_tree", "kd_tree", "brute"})], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "p": [Interval(Real, 0, None, closed="right"), None], + "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable], + "metric_params": [dict, None], + "n_jobs": [Integral, None], + } + + @abstractmethod + def __init__( + self, + n_neighbors=None, + radius=None, + algorithm="auto", + leaf_size=30, + metric="minkowski", + p=2, + metric_params=None, + n_jobs=None, + ): + self.n_neighbors = n_neighbors + self.radius = radius + self.algorithm = algorithm + self.leaf_size = leaf_size + self.metric = metric + self.metric_params = metric_params + self.p = p + self.n_jobs = n_jobs + + def _check_algorithm_metric(self): + if self.algorithm == "auto": + if self.metric == "precomputed": + alg_check = "brute" + elif ( + callable(self.metric) + or self.metric in VALID_METRICS["ball_tree"] + or isinstance(self.metric, DistanceMetric) + ): + alg_check = "ball_tree" + else: + alg_check = "brute" + else: + alg_check = self.algorithm + + if callable(self.metric): + if self.algorithm == "kd_tree": + # callable metric is only valid for brute force and ball_tree + raise ValueError( + "kd_tree does not support callable metric '%s'" + "Function call overhead will result" + "in very poor performance." % self.metric + ) + elif self.metric not in VALID_METRICS[alg_check] and not isinstance( + self.metric, DistanceMetric + ): + raise ValueError( + "Metric '%s' not valid. Use " + "sorted(sklearn.neighbors.VALID_METRICS['%s']) " + "to get valid options. " + "Metric can also be a callable function." % (self.metric, alg_check) + ) + + if self.metric_params is not None and "p" in self.metric_params: + if self.p is not None: + warnings.warn( + ( + "Parameter p is found in metric_params. " + "The corresponding parameter from __init__ " + "is ignored." + ), + SyntaxWarning, + stacklevel=3, + ) + + def _fit(self, X, y=None): + ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True + if self.__sklearn_tags__().target_tags.required: + if not isinstance(X, (KDTree, BallTree, NeighborsBase)): + X, y = validate_data( + self, + X, + y, + accept_sparse="csr", + multi_output=True, + order="C", + ensure_all_finite=ensure_all_finite, + ) + + if is_classifier(self): + # Classification targets require a specific format + if y.ndim == 1 or (y.ndim == 2 and y.shape[1] == 1): + if y.ndim != 1: + warnings.warn( + ( + "A column-vector y was passed when a " + "1d array was expected. Please change " + "the shape of y to (n_samples,), for " + "example using ravel()." + ), + DataConversionWarning, + stacklevel=2, + ) + + self.outputs_2d_ = False + y = y.reshape((-1, 1)) + else: + self.outputs_2d_ = True + + check_classification_targets(y) + self.classes_ = [] + # Using `dtype=np.intp` is necessary since `np.bincount` + # (called in _classification.py) fails when dealing + # with a float64 array on 32bit systems. + self._y = np.empty(y.shape, dtype=np.intp) + for k in range(self._y.shape[1]): + classes, self._y[:, k] = np.unique(y[:, k], return_inverse=True) + self.classes_.append(classes) + + if not self.outputs_2d_: + self.classes_ = self.classes_[0] + self._y = self._y.ravel() + else: + self._y = y + + else: + if not isinstance(X, (KDTree, BallTree, NeighborsBase)): + X = validate_data( + self, + X, + ensure_all_finite=ensure_all_finite, + accept_sparse="csr", + order="C", + ) + + self._check_algorithm_metric() + if self.metric_params is None: + self.effective_metric_params_ = {} + else: + self.effective_metric_params_ = self.metric_params.copy() + + effective_p = self.effective_metric_params_.get("p", self.p) + if self.metric == "minkowski": + self.effective_metric_params_["p"] = effective_p + + self.effective_metric_ = self.metric + # For minkowski distance, use more efficient methods where available + if self.metric == "minkowski": + p = self.effective_metric_params_.pop("p", 2) + w = self.effective_metric_params_.pop("w", None) + + if p == 1 and w is None: + self.effective_metric_ = "manhattan" + elif p == 2 and w is None: + self.effective_metric_ = "euclidean" + elif p == np.inf and w is None: + self.effective_metric_ = "chebyshev" + else: + # Use the generic minkowski metric, possibly weighted. + self.effective_metric_params_["p"] = p + self.effective_metric_params_["w"] = w + + if isinstance(X, NeighborsBase): + self._fit_X = X._fit_X + self._tree = X._tree + self._fit_method = X._fit_method + self.n_samples_fit_ = X.n_samples_fit_ + return self + + elif isinstance(X, BallTree): + self._fit_X = X.data + self._tree = X + self._fit_method = "ball_tree" + self.n_samples_fit_ = X.data.shape[0] + return self + + elif isinstance(X, KDTree): + self._fit_X = X.data + self._tree = X + self._fit_method = "kd_tree" + self.n_samples_fit_ = X.data.shape[0] + return self + + if self.metric == "precomputed": + X = _check_precomputed(X) + # Precomputed matrix X must be squared + if X.shape[0] != X.shape[1]: + raise ValueError( + "Precomputed matrix must be square." + " Input is a {}x{} matrix.".format(X.shape[0], X.shape[1]) + ) + self.n_features_in_ = X.shape[1] + + n_samples = X.shape[0] + if n_samples == 0: + raise ValueError("n_samples must be greater than 0") + + if issparse(X): + if self.algorithm not in ("auto", "brute"): + warnings.warn("cannot use tree with sparse input: using brute force") + + if ( + self.effective_metric_ not in VALID_METRICS_SPARSE["brute"] + and not callable(self.effective_metric_) + and not isinstance(self.effective_metric_, DistanceMetric) + ): + raise ValueError( + "Metric '%s' not valid for sparse input. " + "Use sorted(sklearn.neighbors." + "VALID_METRICS_SPARSE['brute']) " + "to get valid options. " + "Metric can also be a callable function." % (self.effective_metric_) + ) + self._fit_X = X.copy() + self._tree = None + self._fit_method = "brute" + self.n_samples_fit_ = X.shape[0] + return self + + self._fit_method = self.algorithm + self._fit_X = X + self.n_samples_fit_ = X.shape[0] + + if self._fit_method == "auto": + # A tree approach is better for small number of neighbors or small + # number of features, with KDTree generally faster when available + if ( + self.metric == "precomputed" + or self._fit_X.shape[1] > 15 + or ( + self.n_neighbors is not None + and self.n_neighbors >= self._fit_X.shape[0] // 2 + ) + ): + self._fit_method = "brute" + else: + if ( + self.effective_metric_ == "minkowski" + and self.effective_metric_params_["p"] < 1 + ): + self._fit_method = "brute" + elif ( + self.effective_metric_ == "minkowski" + and self.effective_metric_params_.get("w") is not None + ): + # 'minkowski' with weights is not supported by KDTree but is + # supported byBallTree. + self._fit_method = "ball_tree" + elif self.effective_metric_ in VALID_METRICS["kd_tree"]: + self._fit_method = "kd_tree" + elif ( + callable(self.effective_metric_) + or self.effective_metric_ in VALID_METRICS["ball_tree"] + ): + self._fit_method = "ball_tree" + else: + self._fit_method = "brute" + + if ( + self.effective_metric_ == "minkowski" + and self.effective_metric_params_["p"] < 1 + ): + # For 0 < p < 1 Minkowski distances aren't valid distance + # metric as they do not satisfy triangular inequality: + # they are semi-metrics. + # algorithm="kd_tree" and algorithm="ball_tree" can't be used because + # KDTree and BallTree require a proper distance metric to work properly. + # However, the brute-force algorithm supports semi-metrics. + if self._fit_method == "brute": + warnings.warn( + "Mind that for 0 < p < 1, Minkowski metrics are not distance" + " metrics. Continuing the execution with `algorithm='brute'`." + ) + else: # self._fit_method in ("kd_tree", "ball_tree") + raise ValueError( + f'algorithm="{self._fit_method}" does not support 0 < p < 1 for ' + "the Minkowski metric. To resolve this problem either " + 'set p >= 1 or algorithm="brute".' + ) + + if self._fit_method == "ball_tree": + self._tree = BallTree( + X, + self.leaf_size, + metric=self.effective_metric_, + **self.effective_metric_params_, + ) + elif self._fit_method == "kd_tree": + if ( + self.effective_metric_ == "minkowski" + and self.effective_metric_params_.get("w") is not None + ): + raise ValueError( + "algorithm='kd_tree' is not valid for " + "metric='minkowski' with a weight parameter 'w': " + "try algorithm='ball_tree' " + "or algorithm='brute' instead." + ) + self._tree = KDTree( + X, + self.leaf_size, + metric=self.effective_metric_, + **self.effective_metric_params_, + ) + elif self._fit_method == "brute": + self._tree = None + + return self + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + # For cross-validation routines to split data correctly + tags.input_tags.pairwise = self.metric == "precomputed" + # when input is precomputed metric values, all those values need to be positive + tags.input_tags.positive_only = tags.input_tags.pairwise + tags.input_tags.allow_nan = self.metric == "nan_euclidean" + return tags + + +class KNeighborsMixin: + """Mixin for k-neighbors searches.""" + + def _kneighbors_reduce_func(self, dist, start, n_neighbors, return_distance): + """Reduce a chunk of distances to the nearest neighbors. + + Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked` + + Parameters + ---------- + dist : ndarray of shape (n_samples_chunk, n_samples) + The distance matrix. + + start : int + The index in X which the first row of dist corresponds to. + + n_neighbors : int + Number of neighbors required for each sample. + + return_distance : bool + Whether or not to return the distances. + + Returns + ------- + dist : array of shape (n_samples_chunk, n_neighbors) + Returned only if `return_distance=True`. + + neigh : array of shape (n_samples_chunk, n_neighbors) + The neighbors indices. + """ + sample_range = np.arange(dist.shape[0])[:, None] + neigh_ind = np.argpartition(dist, n_neighbors - 1, axis=1) + neigh_ind = neigh_ind[:, :n_neighbors] + # argpartition doesn't guarantee sorted order, so we sort again + neigh_ind = neigh_ind[sample_range, np.argsort(dist[sample_range, neigh_ind])] + if return_distance: + if self.effective_metric_ == "euclidean": + result = np.sqrt(dist[sample_range, neigh_ind]), neigh_ind + else: + result = dist[sample_range, neigh_ind], neigh_ind + else: + result = neigh_ind + return result + + def kneighbors(self, X=None, n_neighbors=None, return_distance=True): + """Find the K-neighbors of a point. + + Returns indices of and distances to the neighbors of each point. + + Parameters + ---------- + X : {array-like, sparse matrix}, shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', default=None + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. + + n_neighbors : int, default=None + Number of neighbors required for each sample. The default is the + value passed to the constructor. + + return_distance : bool, default=True + Whether or not to return the distances. + + Returns + ------- + neigh_dist : ndarray of shape (n_queries, n_neighbors) + Array representing the lengths to points, only present if + return_distance=True. + + neigh_ind : ndarray of shape (n_queries, n_neighbors) + Indices of the nearest points in the population matrix. + + Examples + -------- + In the following example, we construct a NearestNeighbors + class from an array representing our data set and ask who's + the closest point to [1,1,1] + + >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] + >>> from sklearn.neighbors import NearestNeighbors + >>> neigh = NearestNeighbors(n_neighbors=1) + >>> neigh.fit(samples) + NearestNeighbors(n_neighbors=1) + >>> print(neigh.kneighbors([[1., 1., 1.]])) + (array([[0.5]]), array([[2]])) + + As you can see, it returns [[0.5]], and [[2]], which means that the + element is at distance 0.5 and is the third element of samples + (indexes start at 0). You can also query for multiple points: + + >>> X = [[0., 1., 0.], [1., 0., 1.]] + >>> neigh.kneighbors(X, return_distance=False) + array([[1], + [2]]...) + """ + check_is_fitted(self) + + if n_neighbors is None: + n_neighbors = self.n_neighbors + elif n_neighbors <= 0: + raise ValueError("Expected n_neighbors > 0. Got %d" % n_neighbors) + elif not isinstance(n_neighbors, numbers.Integral): + raise TypeError( + "n_neighbors does not take %s value, enter integer value" + % type(n_neighbors) + ) + + ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True + query_is_train = X is None + if query_is_train: + X = self._fit_X + # Include an extra neighbor to account for the sample itself being + # returned, which is removed later + n_neighbors += 1 + else: + if self.metric == "precomputed": + X = _check_precomputed(X) + else: + X = validate_data( + self, + X, + ensure_all_finite=ensure_all_finite, + accept_sparse="csr", + reset=False, + order="C", + ) + + n_samples_fit = self.n_samples_fit_ + if n_neighbors > n_samples_fit: + if query_is_train: + n_neighbors -= 1 # ok to modify inplace because an error is raised + inequality_str = "n_neighbors < n_samples_fit" + else: + inequality_str = "n_neighbors <= n_samples_fit" + raise ValueError( + f"Expected {inequality_str}, but " + f"n_neighbors = {n_neighbors}, n_samples_fit = {n_samples_fit}, " + f"n_samples = {X.shape[0]}" # include n_samples for common tests + ) + + n_jobs = effective_n_jobs(self.n_jobs) + chunked_results = None + use_pairwise_distances_reductions = ( + self._fit_method == "brute" + and ArgKmin.is_usable_for( + X if X is not None else self._fit_X, self._fit_X, self.effective_metric_ + ) + ) + if use_pairwise_distances_reductions: + results = ArgKmin.compute( + X=X, + Y=self._fit_X, + k=n_neighbors, + metric=self.effective_metric_, + metric_kwargs=self.effective_metric_params_, + strategy="auto", + return_distance=return_distance, + ) + + elif ( + self._fit_method == "brute" and self.metric == "precomputed" and issparse(X) + ): + results = _kneighbors_from_graph( + X, n_neighbors=n_neighbors, return_distance=return_distance + ) + + elif self._fit_method == "brute": + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions + # support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + reduce_func = partial( + self._kneighbors_reduce_func, + n_neighbors=n_neighbors, + return_distance=return_distance, + ) + + # for efficiency, use squared euclidean distances + if self.effective_metric_ == "euclidean": + kwds = {"squared": True} + else: + kwds = self.effective_metric_params_ + + chunked_results = list( + pairwise_distances_chunked( + X, + self._fit_X, + reduce_func=reduce_func, + metric=self.effective_metric_, + n_jobs=n_jobs, + **kwds, + ) + ) + + elif self._fit_method in ["ball_tree", "kd_tree"]: + if issparse(X): + raise ValueError( + "%s does not work with sparse matrices. Densify the data, " + "or set algorithm='brute'" % self._fit_method + ) + chunked_results = Parallel(n_jobs, prefer="threads")( + delayed(self._tree.query)(X[s], n_neighbors, return_distance) + for s in gen_even_slices(X.shape[0], n_jobs) + ) + else: + raise ValueError("internal: _fit_method not recognized") + + if chunked_results is not None: + if return_distance: + neigh_dist, neigh_ind = zip(*chunked_results) + results = np.vstack(neigh_dist), np.vstack(neigh_ind) + else: + results = np.vstack(chunked_results) + + if not query_is_train: + return results + else: + # If the query data is the same as the indexed data, we would like + # to ignore the first nearest neighbor of every sample, i.e + # the sample itself. + if return_distance: + neigh_dist, neigh_ind = results + else: + neigh_ind = results + + n_queries, _ = X.shape + sample_range = np.arange(n_queries)[:, None] + sample_mask = neigh_ind != sample_range + + # Corner case: When the number of duplicates are more + # than the number of neighbors, the first NN will not + # be the sample, but a duplicate. + # In that case mask the first duplicate. + dup_gr_nbrs = np.all(sample_mask, axis=1) + sample_mask[:, 0][dup_gr_nbrs] = False + neigh_ind = np.reshape(neigh_ind[sample_mask], (n_queries, n_neighbors - 1)) + + if return_distance: + neigh_dist = np.reshape( + neigh_dist[sample_mask], (n_queries, n_neighbors - 1) + ) + return neigh_dist, neigh_ind + return neigh_ind + + def kneighbors_graph(self, X=None, n_neighbors=None, mode="connectivity"): + """Compute the (weighted) graph of k-Neighbors for points in X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', default=None + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. + For ``metric='precomputed'`` the shape should be + (n_queries, n_indexed). Otherwise the shape should be + (n_queries, n_features). + + n_neighbors : int, default=None + Number of neighbors for each sample. The default is the value + passed to the constructor. + + mode : {'connectivity', 'distance'}, default='connectivity' + Type of returned matrix: 'connectivity' will return the + connectivity matrix with ones and zeros, in 'distance' the + edges are distances between points, type of distance + depends on the selected metric parameter in + NearestNeighbors class. + + Returns + ------- + A : sparse-matrix of shape (n_queries, n_samples_fit) + `n_samples_fit` is the number of samples in the fitted data. + `A[i, j]` gives the weight of the edge connecting `i` to `j`. + The matrix is of CSR format. + + See Also + -------- + NearestNeighbors.radius_neighbors_graph : Compute the (weighted) graph + of Neighbors for points in X. + + Examples + -------- + >>> X = [[0], [3], [1]] + >>> from sklearn.neighbors import NearestNeighbors + >>> neigh = NearestNeighbors(n_neighbors=2) + >>> neigh.fit(X) + NearestNeighbors(n_neighbors=2) + >>> A = neigh.kneighbors_graph(X) + >>> A.toarray() + array([[1., 0., 1.], + [0., 1., 1.], + [1., 0., 1.]]) + """ + check_is_fitted(self) + if n_neighbors is None: + n_neighbors = self.n_neighbors + + # check the input only in self.kneighbors + + # construct CSR matrix representation of the k-NN graph + if mode == "connectivity": + A_ind = self.kneighbors(X, n_neighbors, return_distance=False) + n_queries = A_ind.shape[0] + A_data = np.ones(n_queries * n_neighbors) + + elif mode == "distance": + A_data, A_ind = self.kneighbors(X, n_neighbors, return_distance=True) + A_data = np.ravel(A_data) + + else: + raise ValueError( + 'Unsupported mode, must be one of "connectivity", ' + f'or "distance" but got "{mode}" instead' + ) + + n_queries = A_ind.shape[0] + n_samples_fit = self.n_samples_fit_ + n_nonzero = n_queries * n_neighbors + A_indptr = np.arange(0, n_nonzero + 1, n_neighbors) + + kneighbors_graph = csr_matrix( + (A_data, A_ind.ravel(), A_indptr), shape=(n_queries, n_samples_fit) + ) + + return kneighbors_graph + + +class RadiusNeighborsMixin: + """Mixin for radius-based neighbors searches.""" + + def _radius_neighbors_reduce_func(self, dist, start, radius, return_distance): + """Reduce a chunk of distances to the nearest neighbors. + + Callback to :func:`sklearn.metrics.pairwise.pairwise_distances_chunked` + + Parameters + ---------- + dist : ndarray of shape (n_samples_chunk, n_samples) + The distance matrix. + + start : int + The index in X which the first row of dist corresponds to. + + radius : float + The radius considered when making the nearest neighbors search. + + return_distance : bool + Whether or not to return the distances. + + Returns + ------- + dist : list of ndarray of shape (n_samples_chunk,) + Returned only if `return_distance=True`. + + neigh : list of ndarray of shape (n_samples_chunk,) + The neighbors indices. + """ + neigh_ind = [np.where(d <= radius)[0] for d in dist] + + if return_distance: + if self.effective_metric_ == "euclidean": + dist = [np.sqrt(d[neigh_ind[i]]) for i, d in enumerate(dist)] + else: + dist = [d[neigh_ind[i]] for i, d in enumerate(dist)] + results = dist, neigh_ind + else: + results = neigh_ind + return results + + def radius_neighbors( + self, X=None, radius=None, return_distance=True, sort_results=False + ): + """Find the neighbors within a given radius of a point or points. + + Return the indices and distances of each point from the dataset + lying in a ball with size ``radius`` around the points of the query + array. Points lying on the boundary are included in the results. + + The result points are *not* necessarily sorted by distance to their + query point. + + Parameters + ---------- + X : {array-like, sparse matrix} of (n_samples, n_features), default=None + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. + + radius : float, default=None + Limiting distance of neighbors to return. The default is the value + passed to the constructor. + + return_distance : bool, default=True + Whether or not to return the distances. + + sort_results : bool, default=False + If True, the distances and indices will be sorted by increasing + distances before being returned. If False, the results may not + be sorted. If `return_distance=False`, setting `sort_results=True` + will result in an error. + + .. versionadded:: 0.22 + + Returns + ------- + neigh_dist : ndarray of shape (n_samples,) of arrays + Array representing the distances to each point, only present if + `return_distance=True`. The distance values are computed according + to the ``metric`` constructor parameter. + + neigh_ind : ndarray of shape (n_samples,) of arrays + An array of arrays of indices of the approximate nearest points + from the population matrix that lie within a ball of size + ``radius`` around the query points. + + Notes + ----- + Because the number of neighbors of each point is not necessarily + equal, the results for multiple query points cannot be fit in a + standard data array. + For efficiency, `radius_neighbors` returns arrays of objects, where + each object is a 1D array of indices or distances. + + Examples + -------- + In the following example, we construct a NeighborsClassifier + class from an array representing our data set and ask who's + the closest point to [1, 1, 1]: + + >>> import numpy as np + >>> samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]] + >>> from sklearn.neighbors import NearestNeighbors + >>> neigh = NearestNeighbors(radius=1.6) + >>> neigh.fit(samples) + NearestNeighbors(radius=1.6) + >>> rng = neigh.radius_neighbors([[1., 1., 1.]]) + >>> print(np.asarray(rng[0][0])) + [1.5 0.5] + >>> print(np.asarray(rng[1][0])) + [1 2] + + The first array returned contains the distances to all points which + are closer than 1.6, while the second array returned contains their + indices. In general, multiple points can be queried at the same time. + """ + check_is_fitted(self) + + if sort_results and not return_distance: + raise ValueError("return_distance must be True if sort_results is True.") + + ensure_all_finite = "allow-nan" if get_tags(self).input_tags.allow_nan else True + query_is_train = X is None + if query_is_train: + X = self._fit_X + else: + if self.metric == "precomputed": + X = _check_precomputed(X) + else: + X = validate_data( + self, + X, + ensure_all_finite=ensure_all_finite, + accept_sparse="csr", + reset=False, + order="C", + ) + + if radius is None: + radius = self.radius + + use_pairwise_distances_reductions = ( + self._fit_method == "brute" + and RadiusNeighbors.is_usable_for( + X if X is not None else self._fit_X, self._fit_X, self.effective_metric_ + ) + ) + + if use_pairwise_distances_reductions: + results = RadiusNeighbors.compute( + X=X, + Y=self._fit_X, + radius=radius, + metric=self.effective_metric_, + metric_kwargs=self.effective_metric_params_, + strategy="auto", + return_distance=return_distance, + sort_results=sort_results, + ) + + elif ( + self._fit_method == "brute" and self.metric == "precomputed" and issparse(X) + ): + results = _radius_neighbors_from_graph( + X, radius=radius, return_distance=return_distance + ) + + elif self._fit_method == "brute": + # Joblib-based backend, which is used when user-defined callable + # are passed for metric. + + # This won't be used in the future once PairwiseDistancesReductions + # support: + # - DistanceMetrics which work on supposedly binary data + # - CSR-dense and dense-CSR case if 'euclidean' in metric. + + # for efficiency, use squared euclidean distances + if self.effective_metric_ == "euclidean": + radius *= radius + kwds = {"squared": True} + else: + kwds = self.effective_metric_params_ + + reduce_func = partial( + self._radius_neighbors_reduce_func, + radius=radius, + return_distance=return_distance, + ) + + chunked_results = pairwise_distances_chunked( + X, + self._fit_X, + reduce_func=reduce_func, + metric=self.effective_metric_, + n_jobs=self.n_jobs, + **kwds, + ) + if return_distance: + neigh_dist_chunks, neigh_ind_chunks = zip(*chunked_results) + neigh_dist_list = list(itertools.chain.from_iterable(neigh_dist_chunks)) + neigh_ind_list = list(itertools.chain.from_iterable(neigh_ind_chunks)) + neigh_dist = _to_object_array(neigh_dist_list) + neigh_ind = _to_object_array(neigh_ind_list) + results = neigh_dist, neigh_ind + else: + neigh_ind_list = list(itertools.chain.from_iterable(chunked_results)) + results = _to_object_array(neigh_ind_list) + + if sort_results: + for ii in range(len(neigh_dist)): + order = np.argsort(neigh_dist[ii], kind="mergesort") + neigh_ind[ii] = neigh_ind[ii][order] + neigh_dist[ii] = neigh_dist[ii][order] + results = neigh_dist, neigh_ind + + elif self._fit_method in ["ball_tree", "kd_tree"]: + if issparse(X): + raise ValueError( + "%s does not work with sparse matrices. Densify the data, " + "or set algorithm='brute'" % self._fit_method + ) + + n_jobs = effective_n_jobs(self.n_jobs) + delayed_query = delayed(self._tree.query_radius) + chunked_results = Parallel(n_jobs, prefer="threads")( + delayed_query(X[s], radius, return_distance, sort_results=sort_results) + for s in gen_even_slices(X.shape[0], n_jobs) + ) + if return_distance: + neigh_ind, neigh_dist = tuple(zip(*chunked_results)) + results = np.hstack(neigh_dist), np.hstack(neigh_ind) + else: + results = np.hstack(chunked_results) + else: + raise ValueError("internal: _fit_method not recognized") + + if not query_is_train: + return results + else: + # If the query data is the same as the indexed data, we would like + # to ignore the first nearest neighbor of every sample, i.e + # the sample itself. + if return_distance: + neigh_dist, neigh_ind = results + else: + neigh_ind = results + + for ind, ind_neighbor in enumerate(neigh_ind): + mask = ind_neighbor != ind + + neigh_ind[ind] = ind_neighbor[mask] + if return_distance: + neigh_dist[ind] = neigh_dist[ind][mask] + + if return_distance: + return neigh_dist, neigh_ind + return neigh_ind + + def radius_neighbors_graph( + self, X=None, radius=None, mode="connectivity", sort_results=False + ): + """Compute the (weighted) graph of Neighbors for points in X. + + Neighborhoods are restricted the points at a distance lower than + radius. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None + The query point or points. + If not provided, neighbors of each indexed point are returned. + In this case, the query point is not considered its own neighbor. + + radius : float, default=None + Radius of neighborhoods. The default is the value passed to the + constructor. + + mode : {'connectivity', 'distance'}, default='connectivity' + Type of returned matrix: 'connectivity' will return the + connectivity matrix with ones and zeros, in 'distance' the + edges are distances between points, type of distance + depends on the selected metric parameter in + NearestNeighbors class. + + sort_results : bool, default=False + If True, in each row of the result, the non-zero entries will be + sorted by increasing distances. If False, the non-zero entries may + not be sorted. Only used with mode='distance'. + + .. versionadded:: 0.22 + + Returns + ------- + A : sparse-matrix of shape (n_queries, n_samples_fit) + `n_samples_fit` is the number of samples in the fitted data. + `A[i, j]` gives the weight of the edge connecting `i` to `j`. + The matrix is of CSR format. + + See Also + -------- + kneighbors_graph : Compute the (weighted) graph of k-Neighbors for + points in X. + + Examples + -------- + >>> X = [[0], [3], [1]] + >>> from sklearn.neighbors import NearestNeighbors + >>> neigh = NearestNeighbors(radius=1.5) + >>> neigh.fit(X) + NearestNeighbors(radius=1.5) + >>> A = neigh.radius_neighbors_graph(X) + >>> A.toarray() + array([[1., 0., 1.], + [0., 1., 0.], + [1., 0., 1.]]) + """ + check_is_fitted(self) + + # check the input only in self.radius_neighbors + + if radius is None: + radius = self.radius + + # construct CSR matrix representation of the NN graph + if mode == "connectivity": + A_ind = self.radius_neighbors(X, radius, return_distance=False) + A_data = None + elif mode == "distance": + dist, A_ind = self.radius_neighbors( + X, radius, return_distance=True, sort_results=sort_results + ) + A_data = np.concatenate(list(dist)) + else: + raise ValueError( + 'Unsupported mode, must be one of "connectivity", ' + f'or "distance" but got "{mode}" instead' + ) + + n_queries = A_ind.shape[0] + n_samples_fit = self.n_samples_fit_ + n_neighbors = np.array([len(a) for a in A_ind]) + A_ind = np.concatenate(list(A_ind)) + if A_data is None: + A_data = np.ones(len(A_ind)) + A_indptr = np.concatenate((np.zeros(1, dtype=int), np.cumsum(n_neighbors))) + + return csr_matrix((A_data, A_ind, A_indptr), shape=(n_queries, n_samples_fit)) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = self.metric == "nan_euclidean" + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp new file mode 100644 index 0000000000000000000000000000000000000000..de3bcb0e5d916d3153b7d41c8c975927385b8aac --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_binary_tree.pxi.tp @@ -0,0 +1,2478 @@ +{{py: + +# Generated file: _binary_tree.pxi + +implementation_specific_values = [ + # The values are arranged as follows: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE + # + ('64', 'float64_t', 'np.float64', 'cnp.NPY_DOUBLE'), + ('32', 'float32_t', 'np.float32', 'cnp.NPY_FLOAT') +] + +# KD Tree and Ball Tree +# ===================== +# +# _binary_tree.pxi is generated and is then literally Cython included in +# ball_tree.pyx and kd_tree.pyx. See ball_tree.pyx.tp and kd_tree.pyx.tp. + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause +}} + + +# KD Tree and Ball Tree +# ===================== +# +# The routines here are the core algorithms of the KDTree and BallTree +# structures. If Cython supported polymorphism, we would be able to +# create a subclass and derive KDTree and BallTree from it. Because +# polymorphism is not an option, we use this single BinaryTree class +# as a literal include to avoid duplicating the entire file. +# +# A series of functions are implemented in kd_tree.pyx and ball_tree.pyx +# which use the information here to calculate the lower and upper bounds +# between a node and a point, and between two nodes. These functions are +# used here, and are all that are needed to differentiate between the two +# tree types. +# +# Description of Binary Tree Algorithms +# ------------------------------------- +# A binary tree can be thought of as a collection of nodes. The top node +# contains all the points. The next level consists of two nodes with half +# the points in each, and this continues recursively. Each node contains +# metadata which allow fast computation of distance bounds: in the case of +# a ball tree, the metadata is a center and a radius. In the case of a +# KD tree, the metadata is the minimum and maximum bound along each dimension. +# +# In a typical KD Tree or Ball Tree implementation, the nodes are implemented +# as dynamically allocated structures with pointers linking them. Here we +# take a different approach, storing all relevant data in a set of arrays +# so that the entire tree object can be saved in a pickle file. For efficiency, +# the data can be stored in such a way that explicit pointers are not +# necessary: for node data stored at index i, the two child nodes are at +# index (2 * i + 1) and (2 * i + 2); the parent node is (i - 1) // 2 +# (where // indicates integer division). +# +# The data arrays used here are as follows: +# data : the [n_samples x n_features] array of data from which the tree +# is built +# idx_array : the length n_samples array used to keep track of the indices +# of data within each node. Each node has values idx_start and +# idx_end: the points within the node are given by (using numpy +# syntax) data[idx_array[idx_start:idx_end]]. +# node_data : the length n_nodes array of structures which store the node +# indices, node radii, and leaf information for each node. +# node_bounds : the [* x n_nodes x n_features] array containing the node +# bound information. For ball tree, the first dimension is 1, and +# each row contains the centroid of the node. For kd tree, the first +# dimension is 2 and the rows for each point contain the arrays of +# lower bounds and upper bounds in each direction. +# +# The lack of dynamic allocation means the number of nodes must be computed +# before the building of the tree. This can be done assuming the points are +# divided equally between child nodes at each step; although this removes +# some flexibility in tree creation, it ensures a balanced tree and ensures +# that the number of nodes required can be computed beforehand. Given a +# specified leaf_size (the minimum number of points in any node), it is +# possible to show that a balanced tree will have +# +# n_levels = 1 + max(0, floor(log2((n_samples - 1) / leaf_size))) +# +# in order to satisfy +# +# leaf_size <= min(n_points) <= 2 * leaf_size +# +# with the exception of the special case where n_samples < leaf_size. +# for a given number of levels, the number of nodes in the tree is given by +# +# n_nodes = 2 ** n_levels - 1 +# +# both these results can be straightforwardly shown by induction. The +# following code uses these values in the construction of the tree. +# +# Distance Metrics +# ---------------- +# For flexibility, the trees can be built using a variety of distance metrics. +# The metrics are described in the DistanceMetric class: the standard +# Euclidean distance is the default, and is inlined to be faster than other +# metrics. In addition, each metric defines both a distance and a +# "reduced distance", which is often faster to compute, and is therefore +# used in the query architecture whenever possible. (For example, in the +# case of the standard Euclidean distance, the reduced distance is the +# squared-distance). +# +# Implementation Notes +# -------------------- +# This implementation uses the common object-oriented approach of having an +# abstract base class which is extended by the KDTree and BallTree +# specializations. +# +# The BinaryTree "base class" is defined here and then subclassed in the BallTree +# and KDTree pyx files. These files include implementations of the +# "abstract" methods. + +# Necessary Helper Functions +# -------------------------- +# These are the names and descriptions of the "abstract" functions which are +# defined in kd_tree.pyx and ball_tree.pyx: + +# cdef int allocate_data(BinaryTree tree, intp_t n_nodes, intp_t n_features): +# """Allocate arrays needed for the KD Tree""" + +# cdef int init_node(BinaryTree tree, intp_t i_node, +# intp_t idx_start, intp_t idx_end): +# """Initialize the node for the dataset stored in tree.data""" + +# cdef float64_t min_rdist(BinaryTree tree, intp_t i_node, float64_t* pt): +# """Compute the minimum reduced-distance between a point and a node""" + +# cdef float64_t min_dist(BinaryTree tree, intp_t i_node, float64_t* pt): +# """Compute the minimum distance between a point and a node""" + +# cdef float64_t max_rdist(BinaryTree tree, intp_t i_node, float64_t* pt): +# """Compute the maximum reduced-distance between a point and a node""" + +# cdef float64_t max_dist(BinaryTree tree, intp_t i_node, float64_t* pt): +# """Compute the maximum distance between a point and a node""" + +# cdef inline int min_max_dist(BinaryTree tree, intp_t i_node, float64_t* pt, +# float64_t* min_dist, float64_t* max_dist): +# """Compute the minimum and maximum distance between a point and a node""" + +# cdef inline float64_t min_rdist_dual(BinaryTree tree1, intp_t i_node1, +# BinaryTree tree2, intp_t i_node2): +# """Compute the minimum reduced distance between two nodes""" + +# cdef inline float64_t min_dist_dual(BinaryTree tree1, intp_t i_node1, +# BinaryTree tree2, intp_t i_node2): +# """Compute the minimum distance between two nodes""" + +# cdef inline float64_t max_rdist_dual(BinaryTree tree1, intp_t i_node1, +# BinaryTree tree2, intp_t i_node2): +# """Compute the maximum reduced distance between two nodes""" + +# cdef inline float64_t max_dist_dual(BinaryTree tree1, intp_t i_node1, +# BinaryTree tree2, intp_t i_node2): +# """Compute the maximum distance between two nodes""" + +cimport numpy as cnp +from cython cimport floating +from libc.math cimport fabs, sqrt, exp, cos, pow, log, lgamma +from libc.math cimport fmin, fmax +from libc.stdlib cimport calloc, malloc, free +from libc.string cimport memcpy + +import numpy as np +import warnings + +from ..metrics._dist_metrics cimport ( + DistanceMetric, + DistanceMetric64, + DistanceMetric32, + euclidean_dist64, + euclidean_dist32, + euclidean_rdist64, + euclidean_rdist32, + euclidean_dist_to_rdist64, + euclidean_dist_to_rdist32, +) + +from ._partition_nodes cimport partition_node_indices + +from ..utils import check_array +from ..utils._typedefs cimport float32_t, float64_t, intp_t +from ..utils._heap cimport heap_push +from ..utils._sorting cimport simultaneous_sort as _simultaneous_sort + +cnp.import_array() + + +# TODO: use cnp.PyArray_ENABLEFLAGS when Cython>=3.0 is used. +cdef extern from "numpy/arrayobject.h": + void PyArray_ENABLEFLAGS(cnp.ndarray arr, int flags) + + +# some handy constants +cdef float64_t INF = np.inf +cdef float64_t NEG_INF = -np.inf +cdef float64_t PI = np.pi +cdef float64_t ROOT_2PI = sqrt(2 * PI) +cdef float64_t LOG_PI = log(PI) +cdef float64_t LOG_2PI = log(2 * PI) + + +# Some compound datatypes used below: +cdef struct NodeHeapData_t: + float64_t val + intp_t i1 + intp_t i2 + +# build the corresponding numpy dtype for NodeHeapData +cdef NodeHeapData_t nhd_tmp +NodeHeapData = np.asarray((&nhd_tmp)).dtype + +cdef struct NodeData_t: + intp_t idx_start + intp_t idx_end + intp_t is_leaf + float64_t radius + +# build the corresponding numpy dtype for NodeData +cdef NodeData_t nd_tmp +NodeData = np.asarray((&nd_tmp)).dtype + + +###################################################################### +# Define doc strings, substituting the appropriate class name using +# the DOC_DICT variable defined in the pyx files. +CLASS_DOC = """{BinaryTree} for fast generalized N-point problems + +Read more in the :ref:`User Guide `. + +Parameters +---------- +X : array-like of shape (n_samples, n_features) + n_samples is the number of points in the data set, and + n_features is the dimension of the parameter space. + Note: if X is a C-contiguous array of doubles then data will + not be copied. Otherwise, an internal copy will be made. + +leaf_size : positive int, default=40 + Number of points at which to switch to brute-force. Changing + leaf_size will not affect the results of a query, but can + significantly impact the speed of a query and the memory required + to store the constructed tree. The amount of memory needed to + store the tree scales as approximately n_samples / leaf_size. + For a specified ``leaf_size``, a leaf node is guaranteed to + satisfy ``leaf_size <= n_points <= 2 * leaf_size``, except in + the case that ``n_samples < leaf_size``. + +metric : str or DistanceMetric64 object, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. + A list of valid metrics for {BinaryTree} is given by the attribute + `valid_metrics`. + See the documentation of `scipy.spatial.distance + `_ and + the metrics listed in :class:`~sklearn.metrics.pairwise.distance_metrics` for + more information on any distance metric. + +Additional keywords are passed to the distance metric class. +Note: Callable functions in the metric parameter are NOT supported for KDTree +and Ball Tree. Function call overhead will result in very poor performance. + +Attributes +---------- +data : memory view + The training data +valid_metrics: list of str + List of valid distance metrics. + +Examples +-------- +Query for k-nearest neighbors + + >>> import numpy as np + >>> from sklearn.neighbors import {BinaryTree} + >>> rng = np.random.RandomState(0) + >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> dist, ind = tree.query(X[:1], k=3) # doctest: +SKIP + >>> print(ind) # indices of 3 closest neighbors + [0 3 1] + >>> print(dist) # distances to 3 closest neighbors + [ 0. 0.19662693 0.29473397] + +Pickle and Unpickle a tree. Note that the state of the tree is saved in the +pickle operation: the tree needs not be rebuilt upon unpickling. + + >>> import numpy as np + >>> import pickle + >>> rng = np.random.RandomState(0) + >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> s = pickle.dumps(tree) # doctest: +SKIP + >>> tree_copy = pickle.loads(s) # doctest: +SKIP + >>> dist, ind = tree_copy.query(X[:1], k=3) # doctest: +SKIP + >>> print(ind) # indices of 3 closest neighbors + [0 3 1] + >>> print(dist) # distances to 3 closest neighbors + [ 0. 0.19662693 0.29473397] + +Query for neighbors within a given radius + + >>> import numpy as np + >>> rng = np.random.RandomState(0) + >>> X = rng.random_sample((10, 3)) # 10 points in 3 dimensions + >>> tree = {BinaryTree}(X, leaf_size=2) # doctest: +SKIP + >>> print(tree.query_radius(X[:1], r=0.3, count_only=True)) + 3 + >>> ind = tree.query_radius(X[:1], r=0.3) # doctest: +SKIP + >>> print(ind) # indices of neighbors within distance 0.3 + [3 0 1] + + +Compute a gaussian kernel density estimate: + + >>> import numpy as np + >>> rng = np.random.RandomState(42) + >>> X = rng.random_sample((100, 3)) + >>> tree = {BinaryTree}(X) # doctest: +SKIP + >>> tree.kernel_density(X[:3], h=0.1, kernel='gaussian') + array([ 6.94114649, 7.83281226, 7.2071716 ]) + +Compute a two-point auto-correlation function + + >>> import numpy as np + >>> rng = np.random.RandomState(0) + >>> X = rng.random_sample((30, 3)) + >>> r = np.linspace(0, 1, 5) + >>> tree = {BinaryTree}(X) # doctest: +SKIP + >>> tree.two_point_correlation(X, r) + array([ 30, 62, 278, 580, 820]) + +""" + + +###################################################################### +# Utility functions +cdef float64_t logaddexp(float64_t x1, float64_t x2): + """logaddexp(x1, x2) -> log(exp(x1) + exp(x2))""" + cdef float64_t a = fmax(x1, x2) + if a == NEG_INF: + return NEG_INF + else: + return a + log(exp(x1 - a) + exp(x2 - a)) + +cdef float64_t logsubexp(float64_t x1, float64_t x2): + """logsubexp(x1, x2) -> log(exp(x1) - exp(x2))""" + if x1 <= x2: + return NEG_INF + else: + return x1 + log(1 - exp(x2 - x1)) + + +###################################################################### +# Kernel functions +# +# Note: Kernels assume dist is non-negative and h is positive +# All kernel functions are normalized such that K(0, h) = 1. +# The fully normalized kernel is: +# K = exp[kernel_norm(h, d, kernel) + compute_kernel(dist, h, kernel)] +# The code only works with non-negative kernels: i.e. K(d, h) >= 0 +# for all valid d and h. Note that for precision, the log of both +# the kernel and kernel norm is returned. +cdef enum KernelType: + GAUSSIAN_KERNEL = 1 + TOPHAT_KERNEL = 2 + EPANECHNIKOV_KERNEL = 3 + EXPONENTIAL_KERNEL = 4 + LINEAR_KERNEL = 5 + COSINE_KERNEL = 6 + + +cdef inline float64_t log_gaussian_kernel(float64_t dist, float64_t h): + """log of the gaussian kernel for bandwidth h (unnormalized)""" + return -0.5 * (dist * dist) / (h * h) + + +cdef inline float64_t log_tophat_kernel(float64_t dist, float64_t h): + """log of the tophat kernel for bandwidth h (unnormalized)""" + if dist < h: + return 0.0 + else: + return NEG_INF + + +cdef inline float64_t log_epanechnikov_kernel(float64_t dist, float64_t h): + """log of the epanechnikov kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(1.0 - (dist * dist) / (h * h)) + else: + return NEG_INF + + +cdef inline float64_t log_exponential_kernel(float64_t dist, float64_t h): + """log of the exponential kernel for bandwidth h (unnormalized)""" + return -dist / h + + +cdef inline float64_t log_linear_kernel(float64_t dist, float64_t h): + """log of the linear kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(1 - dist / h) + else: + return NEG_INF + + +cdef inline float64_t log_cosine_kernel(float64_t dist, float64_t h): + """log of the cosine kernel for bandwidth h (unnormalized)""" + if dist < h: + return log(cos(0.5 * PI * dist / h)) + else: + return NEG_INF + + +cdef inline float64_t compute_log_kernel(float64_t dist, float64_t h, + KernelType kernel): + """Given a KernelType enumeration, compute the appropriate log-kernel""" + if kernel == GAUSSIAN_KERNEL: + return log_gaussian_kernel(dist, h) + elif kernel == TOPHAT_KERNEL: + return log_tophat_kernel(dist, h) + elif kernel == EPANECHNIKOV_KERNEL: + return log_epanechnikov_kernel(dist, h) + elif kernel == EXPONENTIAL_KERNEL: + return log_exponential_kernel(dist, h) + elif kernel == LINEAR_KERNEL: + return log_linear_kernel(dist, h) + elif kernel == COSINE_KERNEL: + return log_cosine_kernel(dist, h) + + +# ------------------------------------------------------------ +# Kernel norms are defined via the volume element V_n +# and surface element S_(n-1) of an n-sphere. +cdef float64_t logVn(intp_t n): + """V_n = pi^(n/2) / gamma(n/2 - 1)""" + return 0.5 * n * LOG_PI - lgamma(0.5 * n + 1) + + +cdef float64_t logSn(intp_t n): + """V_(n+1) = int_0^1 S_n r^n dr""" + return LOG_2PI + logVn(n - 1) + + +cdef float64_t _log_kernel_norm(float64_t h, intp_t d, + KernelType kernel) except -1: + """Given a KernelType enumeration, compute the kernel normalization. + + h is the bandwidth, d is the dimension. + """ + cdef float64_t tmp, factor = 0 + cdef intp_t k + if kernel == GAUSSIAN_KERNEL: + factor = 0.5 * d * LOG_2PI + elif kernel == TOPHAT_KERNEL: + factor = logVn(d) + elif kernel == EPANECHNIKOV_KERNEL: + factor = logVn(d) + log(2. / (d + 2.)) + elif kernel == EXPONENTIAL_KERNEL: + factor = logSn(d - 1) + lgamma(d) + elif kernel == LINEAR_KERNEL: + factor = logVn(d) - log(d + 1.) + elif kernel == COSINE_KERNEL: + # this is derived from a chain rule integration + factor = 0 + tmp = 2. / PI + for k in range(1, d + 1, 2): + factor += tmp + tmp *= -(d - k) * (d - k - 1) * (2. / PI) ** 2 + factor = log(factor) + logSn(d - 1) + else: + raise ValueError("Kernel code not recognized") + return -factor - d * log(h) + + +def kernel_norm(h, d, kernel, return_log=False): + """Given a string specification of a kernel, compute the normalization. + + Parameters + ---------- + h : float + The bandwidth of the kernel. + d : int + The dimension of the space in which the kernel norm is computed. + kernel : str + The kernel identifier. Must be one of + ['gaussian'|'tophat'|'epanechnikov'| + 'exponential'|'linear'|'cosine'] + return_log : bool, default=False + If True, return the log of the kernel norm. Otherwise, return the + kernel norm. + Returns + ------- + knorm or log_knorm : float + the kernel norm or logarithm of the kernel norm. + """ + if kernel == 'gaussian': + result = _log_kernel_norm(h, d, GAUSSIAN_KERNEL) + elif kernel == 'tophat': + result = _log_kernel_norm(h, d, TOPHAT_KERNEL) + elif kernel == 'epanechnikov': + result = _log_kernel_norm(h, d, EPANECHNIKOV_KERNEL) + elif kernel == 'exponential': + result = _log_kernel_norm(h, d, EXPONENTIAL_KERNEL) + elif kernel == 'linear': + result = _log_kernel_norm(h, d, LINEAR_KERNEL) + elif kernel == 'cosine': + result = _log_kernel_norm(h, d, COSINE_KERNEL) + else: + raise ValueError('kernel not recognized') + + if return_log: + return result + else: + return np.exp(result) + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE in implementation_specific_values}} + +cdef class NeighborsHeap{{name_suffix}}: + """A max-heap structure to keep track of distances/indices of neighbors + + This implements an efficient pre-allocated set of fixed-size heaps + for chasing neighbors, holding both an index and a distance. + When any row of the heap is full, adding an additional point will push + the furthest point off the heap. + + Parameters + ---------- + n_pts : int + the number of heaps to use + n_nbrs : int + the size of each heap. + """ + cdef {{INPUT_DTYPE_t}}[:, ::1] distances + cdef intp_t[:, ::1] indices + + def __cinit__(self): + # One-element arrays are used as placeholders to prevent + # any problem due to potential access to those attributes + # (e.g. assigning to NULL or a to value in another segment). + self.distances = np.zeros((1, 1), dtype={{INPUT_DTYPE}}, order='C') + self.indices = np.zeros((1, 1), dtype=np.intp, order='C') + + def __init__(self, n_pts, n_nbrs): + self.distances = np.full( + (n_pts, n_nbrs), np.inf, dtype={{INPUT_DTYPE}}, order='C' + ) + self.indices = np.zeros((n_pts, n_nbrs), dtype=np.intp, order='C') + + def get_arrays(self, sort=True): + """Get the arrays of distances and indices within the heap. + + If sort=True, then simultaneously sort the indices and distances, + so the closer points are listed first. + """ + if sort: + self._sort() + return self.distances.base, self.indices.base + + cdef inline float64_t largest(self, intp_t row) except -1 nogil: + """Return the largest distance in the given row""" + return self.distances[row, 0] + + def push(self, intp_t row, float64_t val, intp_t i_val): + return self._push(row, val, i_val) + + cdef int _push(self, intp_t row, float64_t val, + intp_t i_val) except -1 nogil: + """push (val, i_val) into the given row""" + return heap_push( + values=&self.distances[row, 0], + indices=&self.indices[row, 0], + size=self.distances.shape[1], + val=val, + val_idx=i_val, + ) + + cdef int _sort(self) except -1: + """simultaneously sort the distances and indices""" + cdef intp_t row + for row in range(self.distances.shape[0]): + _simultaneous_sort( + dist=&self.distances[row, 0], + idx=&self.indices[row, 0], + size=self.distances.shape[1], + ) + return 0 + +{{endfor}} + +#------------------------------------------------------------ +# find_node_split_dim: +# this computes the equivalent of +# j_max = np.argmax(np.max(data, 0) - np.min(data, 0)) +cdef intp_t find_node_split_dim(const floating* data, + const intp_t* node_indices, + intp_t n_features, + intp_t n_points) except -1: + """Find the dimension with the largest spread. + + Parameters + ---------- + data : double pointer + Pointer to a 2D array of the training data, of shape [N, n_features]. + N must be greater than any of the values in node_indices. + node_indices : int pointer + Pointer to a 1D array of length n_points. This lists the indices of + each of the points within the current node. + + Returns + ------- + i_max : int + The index of the feature (dimension) within the node that has the + largest spread. + + Notes + ----- + In numpy, this operation is equivalent to + + def find_node_split_dim(data, node_indices): + return np.argmax(data[node_indices].max(0) - data[node_indices].min(0)) + + The cython version is much more efficient in both computation and memory. + """ + cdef float64_t min_val, max_val, val, spread, max_spread + cdef intp_t i, j, j_max + + j_max = 0 + max_spread = 0 + + for j in range(n_features): + max_val = data[node_indices[0] * n_features + j] + min_val = max_val + for i in range(1, n_points): + val = data[node_indices[i] * n_features + j] + max_val = fmax(max_val, val) + min_val = fmin(min_val, val) + spread = max_val - min_val + if spread > max_spread: + max_spread = spread + j_max = j + return j_max + + +###################################################################### +# NodeHeap : min-heap used to keep track of nodes during +# breadth-first query +cdef inline void swap_nodes(NodeHeapData_t* arr, intp_t i1, intp_t i2): + cdef NodeHeapData_t tmp = arr[i1] + arr[i1] = arr[i2] + arr[i2] = tmp + + +cdef class NodeHeap: + """NodeHeap + + This is a min-heap implementation for keeping track of nodes + during a breadth-first search. Unlike the NeighborsHeap above, + the NodeHeap does not have a fixed size and must be able to grow + as elements are added. + + Internally, the data is stored in a simple binary heap which meets + the min heap condition: + + heap[i].val < min(heap[2 * i + 1].val, heap[2 * i + 2].val) + """ + cdef NodeHeapData_t[:] data + cdef intp_t n + + def __cinit__(self): + # A one-elements array is used as a placeholder to prevent + # any problem due to potential access to this attribute + # (e.g. assigning to NULL or a to value in another segment). + self.data = np.zeros(1, dtype=NodeHeapData, order='C') + + def __init__(self, size_guess=100): + size_guess = max(size_guess, 1) # need space for at least one item + self.data = np.zeros(size_guess, dtype=NodeHeapData, order='C') + self.n = size_guess + self.clear() + + cdef int resize(self, intp_t new_size) except -1: + """Resize the heap to be either larger or smaller""" + cdef: + NodeHeapData_t *data_ptr + NodeHeapData_t *new_data_ptr + intp_t i + intp_t size = self.data.shape[0] + NodeHeapData_t[:] new_data = np.zeros( + new_size, + dtype=NodeHeapData, + ) + + if size > 0 and new_size > 0: + data_ptr = &self.data[0] + new_data_ptr = &new_data[0] + for i in range(min(size, new_size)): + new_data_ptr[i] = data_ptr[i] + + if new_size < size: + self.n = new_size + + self.data = new_data + return 0 + + cdef int push(self, NodeHeapData_t data) except -1: + """Push a new item onto the heap""" + cdef intp_t i, i_parent + cdef NodeHeapData_t* data_arr + self.n += 1 + if self.n > self.data.shape[0]: + self.resize(2 * self.n) + + # put the new element at the end, + # and then perform swaps until the heap is in order + data_arr = &self.data[0] + i = self.n - 1 + data_arr[i] = data + + while i > 0: + i_parent = (i - 1) // 2 + if data_arr[i_parent].val <= data_arr[i].val: + break + else: + swap_nodes(data_arr, i, i_parent) + i = i_parent + return 0 + + cdef NodeHeapData_t peek(self): + """Peek at the root of the heap, without removing it""" + return self.data[0] + + cdef NodeHeapData_t pop(self): + """Remove the root of the heap, and update the remaining nodes""" + if self.n == 0: + raise ValueError('cannot pop on empty heap') + + cdef intp_t i, i_child1, i_child2, i_swap + cdef NodeHeapData_t* data_arr = &self.data[0] + cdef NodeHeapData_t popped_element = data_arr[0] + + # pop off the first element, move the last element to the front, + # and then perform swaps until the heap is back in order + data_arr[0] = data_arr[self.n - 1] + self.n -= 1 + + i = 0 + + while (i < self.n): + i_child1 = 2 * i + 1 + i_child2 = 2 * i + 2 + i_swap = 0 + + if i_child2 < self.n: + if data_arr[i_child1].val <= data_arr[i_child2].val: + i_swap = i_child1 + else: + i_swap = i_child2 + elif i_child1 < self.n: + i_swap = i_child1 + else: + break + + if (i_swap > 0) and (data_arr[i_swap].val <= data_arr[i].val): + swap_nodes(data_arr, i, i_swap) + i = i_swap + else: + break + + return popped_element + + cdef void clear(self): + """Clear the heap""" + self.n = 0 + + +###################################################################### +# newObj function +# this is a helper function for pickling +def newObj(obj): + return obj.__new__(obj) + + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE, NPY_TYPE in implementation_specific_values}} + +###################################################################### +# define the reverse mapping of VALID_METRICS{{name_suffix}} +from sklearn.metrics._dist_metrics import get_valid_metric_ids +VALID_METRIC_IDS{{name_suffix}} = get_valid_metric_ids(VALID_METRICS{{name_suffix}}) + + +###################################################################### +# Binary Tree class +cdef class BinaryTree{{name_suffix}}: + + cdef readonly const {{INPUT_DTYPE_t}}[:, ::1] data + cdef readonly const {{INPUT_DTYPE_t}}[::1] sample_weight + cdef public float64_t sum_weight + + # TODO: idx_array and node_bounds must not be const, but this change needs + # to happen in a way which preserves pickling + # See also: https://github.com/cython/cython/issues/5639 + cdef public const intp_t[::1] idx_array + cdef public const NodeData_t[::1] node_data + cdef public const {{INPUT_DTYPE_t}}[:, :, ::1] node_bounds + + cdef intp_t leaf_size + cdef intp_t n_levels + cdef intp_t n_nodes + + cdef DistanceMetric{{name_suffix}} dist_metric + cdef int euclidean + + # variables to keep track of building & querying stats + cdef int n_trims + cdef int n_leaves + cdef int n_splits + cdef int n_calls + + valid_metrics = VALID_METRIC_IDS{{name_suffix}} + + # Use cinit to initialize all arrays to empty: this will prevent memory + # errors and seg-faults in rare cases where __init__ is not called + # A one-elements array is used as a placeholder to prevent + # any problem due to potential access to this attribute + # (e.g. assigning to NULL or a to value in another segment). + def __cinit__(self): + self.data = np.empty((1, 1), dtype={{INPUT_DTYPE}}, order='C') + self.sample_weight = np.empty(1, dtype={{INPUT_DTYPE}}, order='C') + self.idx_array = np.empty(1, dtype=np.intp, order='C') + self.node_data = np.empty(1, dtype=NodeData, order='C') + self.node_bounds = np.empty((1, 1, 1), dtype={{INPUT_DTYPE}}) + + self.leaf_size = 0 + self.n_levels = 0 + self.n_nodes = 0 + + self.euclidean = False + + self.n_trims = 0 + self.n_leaves = 0 + self.n_splits = 0 + self.n_calls = 0 + + def __init__(self, data, + leaf_size=40, metric='minkowski', sample_weight=None, **kwargs): + # validate data + self.data = check_array(data, dtype={{INPUT_DTYPE}}, order='C') + if self.data.size == 0: + raise ValueError("X is an empty array") + + n_samples = self.data.shape[0] + n_features = self.data.shape[1] + + if leaf_size < 1: + raise ValueError("leaf_size must be greater than or equal to 1") + self.leaf_size = leaf_size + + self.dist_metric = DistanceMetric.get_metric(metric, dtype={{INPUT_DTYPE}}, **kwargs) + self.euclidean = (self.dist_metric.__class__.__name__ + == 'EuclideanDistance{{name_suffix}}') + + metric = self.dist_metric.__class__.__name__ + if metric not in VALID_METRICS{{name_suffix}}: + raise ValueError('metric {metric} is not valid for ' + '{BinaryTree}'.format(metric=metric, + **DOC_DICT{{name_suffix}})) + self.dist_metric._validate_data(self.data) + + # determine number of levels in the tree, and from this + # the number of nodes in the tree. This results in leaf nodes + # with numbers of points between leaf_size and 2 * leaf_size + self.n_levels = int( + np.log2(fmax(1, (n_samples - 1) / self.leaf_size)) + 1) + self.n_nodes = (2 ** self.n_levels) - 1 + + # allocate arrays for storage + self.idx_array = np.arange(n_samples, dtype=np.intp) + self.node_data = np.zeros(self.n_nodes, dtype=NodeData) + + self._update_sample_weight(n_samples, sample_weight) + + # Allocate tree-specific data + allocate_data{{name_suffix}}(self, self.n_nodes, n_features) + self._recursive_build( + node_data=self.node_data.base, + i_node=0, + idx_start=0, + idx_end=n_samples + ) + + def _update_sample_weight(self, n_samples, sample_weight): + if sample_weight is not None: + self.sample_weight = np.asarray( + sample_weight, dtype={{INPUT_DTYPE}}, order='C') + self.sum_weight = np.sum(self.sample_weight) + else: + self.sample_weight = None + self.sum_weight = n_samples + + def __reduce__(self): + """ + reduce method used for pickling + """ + return (newObj, (type(self),), self.__getstate__()) + + def __getstate__(self): + """ + get state for pickling + """ + if self.sample_weight is not None: + # pass the numpy array + sample_weight = self.sample_weight.base + else: + # pass None to avoid confusion with the empty place holder + # of size 1 from __cinit__ + sample_weight = None + return (self.data.base, + self.idx_array.base, + self.node_data.base, + self.node_bounds.base, + int(self.leaf_size), + int(self.n_levels), + int(self.n_nodes), + int(self.n_trims), + int(self.n_leaves), + int(self.n_splits), + int(self.n_calls), + self.dist_metric, + sample_weight) + + def __setstate__(self, state): + """ + set state for pickling + """ + self.data = state[0] + self.idx_array = state[1] + self.node_data = state[2] + self.node_bounds = state[3] + self.leaf_size = state[4] + self.n_levels = state[5] + self.n_nodes = state[6] + self.n_trims = state[7] + self.n_leaves = state[8] + self.n_splits = state[9] + self.n_calls = state[10] + self.dist_metric = state[11] + sample_weight = state[12] + + self.euclidean = (self.dist_metric.__class__.__name__ + == 'EuclideanDistance64') + n_samples = self.data.shape[0] + self._update_sample_weight(n_samples, sample_weight) + + def get_tree_stats(self): + """ + get_tree_stats() + + Get tree status. + + Returns + ------- + tree_stats: tuple of int + (number of trims, number of leaves, number of splits) + """ + return (self.n_trims, self.n_leaves, self.n_splits) + + def reset_n_calls(self): + """ + reset_n_calls() + + Reset number of calls to 0. + """ + self.n_calls = 0 + + def get_n_calls(self): + """ + get_n_calls() + + Get number of calls. + + Returns + ------- + n_calls: int + number of distance computation calls + """ + return self.n_calls + + def get_arrays(self): + """ + get_arrays() + + Get data and node arrays. + + Returns + ------- + arrays: tuple of array + Arrays for storing tree data, index, node data and node bounds. + """ + return ( + self.data.base, + self.idx_array.base, + self.node_data.base, + self.node_bounds.base, + ) + + cdef inline float64_t dist(self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, + intp_t size) except -1 nogil: + """Compute the distance between arrays x1 and x2""" + self.n_calls += 1 + if self.euclidean: + return euclidean_dist{{name_suffix}}(x1, x2, size) + else: + return self.dist_metric.dist(x1, x2, size) + + cdef inline float64_t rdist(self, const {{INPUT_DTYPE_t}}* x1, const {{INPUT_DTYPE_t}}* x2, + intp_t size) except -1 nogil: + """Compute the reduced distance between arrays x1 and x2. + + The reduced distance, defined for some metrics, is a quantity which + is more efficient to compute than the distance, but preserves the + relative rankings of the true distance. For example, the reduced + distance for the Euclidean metric is the squared-euclidean distance. + """ + self.n_calls += 1 + if self.euclidean: + return euclidean_rdist{{name_suffix}}(x1, x2, size) + else: + return self.dist_metric.rdist(x1, x2, size) + + cdef int _recursive_build(self, NodeData_t[::1] node_data, intp_t i_node, intp_t idx_start, + intp_t idx_end) except -1: + """Recursively build the tree. + + Parameters + ---------- + i_node : int + the node for the current step + idx_start, idx_end : int + the bounding indices in the idx_array which define the points that + belong to this node. + """ + cdef intp_t imax + cdef intp_t n_features = self.data.shape[1] + cdef intp_t n_points = idx_end - idx_start + cdef intp_t n_mid = n_points / 2 + cdef intp_t* idx_array = &self.idx_array[idx_start] + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + + # initialize node data + init_node{{name_suffix}}(self, node_data, i_node, idx_start, idx_end) + + if 2 * i_node + 1 >= self.n_nodes: + node_data[i_node].is_leaf = True + if idx_end - idx_start > 2 * self.leaf_size: + # this shouldn't happen if our memory allocation is correct + # we'll proactively prevent memory errors, but raise a + # warning saying we're doing so. + import warnings + warnings.warn("Internal: memory layout is flawed: " + "not enough nodes allocated") + + elif idx_end - idx_start < 2: + # again, this shouldn't happen if our memory allocation + # is correct. Raise a warning. + import warnings + warnings.warn("Internal: memory layout is flawed: " + "too many nodes allocated") + node_data[i_node].is_leaf = True + + else: + # split node and recursively construct child nodes. + node_data[i_node].is_leaf = False + i_max = find_node_split_dim(data, idx_array, + n_features, n_points) + partition_node_indices(data, idx_array, i_max, n_mid, + n_features, n_points) + self._recursive_build(node_data, 2 * i_node + 1, + idx_start, idx_start + n_mid) + self._recursive_build(node_data, 2 * i_node + 2, + idx_start + n_mid, idx_end) + + def query(self, X, k=1, return_distance=True, + dualtree=False, breadth_first=False, + sort_results=True): + """ + query(X, k=1, return_distance=True, + dualtree=False, breadth_first=False) + + query the tree for the k nearest neighbors + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array of points to query + k : int, default=1 + The number of nearest neighbors to return + return_distance : bool, default=True + if True, return a tuple (d, i) of distances and indices + if False, return array i + dualtree : bool, default=False + if True, use the dual tree formalism for the query: a tree is + built for the query points, and the pair of trees is used to + efficiently search this space. This can lead to better + performance as the number of points grows large. + breadth_first : bool, default=False + if True, then query the nodes in a breadth-first manner. + Otherwise, query the nodes in a depth-first manner. + sort_results : bool, default=True + if True, then distances and indices of each point are sorted + on return, so that the first column contains the closest points. + Otherwise, neighbors are returned in an arbitrary order. + + Returns + ------- + i : if return_distance == False + (d,i) : if return_distance == True + + d : ndarray of shape X.shape[:-1] + (k,), dtype=double + Each entry gives the list of distances to the neighbors of the + corresponding point. + + i : ndarray of shape X.shape[:-1] + (k,), dtype=int + Each entry gives the list of indices of neighbors of the + corresponding point. + """ + # XXX: we should allow X to be a pre-built tree. + X = check_array(X, dtype={{INPUT_DTYPE}}, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + if self.data.shape[0] < k: + raise ValueError("k must be less than or equal " + "to the number of training points") + + # flatten X, and save original shape information + np_Xarr = X.reshape((-1, self.data.shape[1])) + cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = np_Xarr + cdef float64_t reduced_dist_LB + cdef intp_t i + cdef const {{INPUT_DTYPE_t}}* pt + + # initialize heap for neighbors + cdef NeighborsHeap{{name_suffix}} heap = NeighborsHeap{{name_suffix}}(Xarr.shape[0], k) + + # node heap for breadth-first queries + cdef NodeHeap nodeheap + if breadth_first: + nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + + # bounds is needed for the dual tree algorithm + cdef float64_t[::1] bounds + + self.n_trims = 0 + self.n_leaves = 0 + self.n_splits = 0 + + if dualtree: + other = self.__class__(np_Xarr, metric=self.dist_metric, + leaf_size=self.leaf_size) + if breadth_first: + self._query_dual_breadthfirst(other, heap, nodeheap) + else: + reduced_dist_LB = min_rdist_dual{{name_suffix}}(self, 0, other, 0) + bounds = np.full(other.node_data.shape[0], np.inf) + self._query_dual_depthfirst(0, other, 0, bounds, + heap, reduced_dist_LB) + + else: + pt = &Xarr[0, 0] + if breadth_first: + for i in range(Xarr.shape[0]): + self._query_single_breadthfirst(pt, i, heap, nodeheap) + pt += Xarr.shape[1] + else: + with nogil: + for i in range(Xarr.shape[0]): + reduced_dist_LB = min_rdist{{name_suffix}}(self, 0, pt) + self._query_single_depthfirst(0, pt, i, heap, + reduced_dist_LB) + pt += Xarr.shape[1] + + distances, indices = heap.get_arrays(sort=sort_results) + distances = self.dist_metric.rdist_to_dist(distances) + + # deflatten results + if return_distance: + return (distances.reshape(X.shape[:X.ndim - 1] + (k,)), + indices.reshape(X.shape[:X.ndim - 1] + (k,))) + else: + return indices.reshape(X.shape[:X.ndim - 1] + (k,)) + + def query_radius(self, X, r, int return_distance=False, + int count_only=False, int sort_results=False): + """ + query_radius(X, r, return_distance=False, + count_only=False, sort_results=False) + + query the tree for neighbors within a radius r + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array of points to query + r : distance within which neighbors are returned + r can be a single value, or an array of values of shape + x.shape[:-1] if different radii are desired for each point. + return_distance : bool, default=False + if True, return distances to neighbors of each point + if False, return only neighbors + Note that unlike the query() method, setting return_distance=True + here adds to the computation time. Not all distances need to be + calculated explicitly for return_distance=False. Results are + not sorted by default: see ``sort_results`` keyword. + count_only : bool, default=False + if True, return only the count of points within distance r + if False, return the indices of all points within distance r + If return_distance==True, setting count_only=True will + result in an error. + sort_results : bool, default=False + if True, the distances and indices will be sorted before being + returned. If False, the results will not be sorted. If + return_distance == False, setting sort_results = True will + result in an error. + + Returns + ------- + count : if count_only == True + ind : if count_only == False and return_distance == False + (ind, dist) : if count_only == False and return_distance == True + + count : ndarray of shape X.shape[:-1], dtype=int + Each entry gives the number of neighbors within a distance r of the + corresponding point. + + ind : ndarray of shape X.shape[:-1], dtype=object + Each element is a numpy integer array listing the indices of + neighbors of the corresponding point. Note that unlike + the results of a k-neighbors query, the returned neighbors + are not sorted by distance by default. + + dist : ndarray of shape X.shape[:-1], dtype=object + Each element is a numpy double array listing the distances + corresponding to indices in i. + """ + if count_only and return_distance: + raise ValueError("count_only and return_distance " + "cannot both be true") + + if sort_results and not return_distance: + raise ValueError("return_distance must be True " + "if sort_results is True") + + cdef intp_t i, count_i = 0 + cdef intp_t n_features = self.data.shape[1] + cdef {{INPUT_DTYPE_t}}[::1] dist_arr_i + cdef intp_t[::1] idx_arr_i, counts + cdef const {{INPUT_DTYPE_t}}* pt + cdef intp_t** indices = NULL + cdef {{INPUT_DTYPE_t}}** distances = NULL + + # validate X and prepare for query + X = check_array(X, dtype={{INPUT_DTYPE}}, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = X.reshape((-1, self.data.shape[1])) + + # prepare r for query + r = np.asarray(r, dtype=np.float64, order='C') + r = np.atleast_1d(r) + if r.shape == (1,): + r = np.full(X.shape[:X.ndim - 1], r[0], dtype=np.float64) + else: + if r.shape != X.shape[:X.ndim - 1]: + raise ValueError("r must be broadcastable to X.shape") + + rarr_np = r.reshape(-1) # store explicitly to keep in scope + cdef float64_t[::1] rarr = rarr_np + + if not count_only: + indices = calloc(Xarr.shape[0], sizeof(intp_t*)) + if indices == NULL: + raise MemoryError() + if return_distance: + distances = <{{INPUT_DTYPE_t}}**>calloc(Xarr.shape[0], sizeof({{INPUT_DTYPE_t}}*)) + if distances == NULL: + free(indices) + raise MemoryError() + + np_idx_arr = np.zeros(self.data.shape[0], dtype=np.intp) + idx_arr_i = np_idx_arr + + np_dist_arr = np.zeros(self.data.shape[0], dtype={{INPUT_DTYPE}}) + dist_arr_i = np_dist_arr + + counts_arr = np.zeros(Xarr.shape[0], dtype=np.intp) + counts = counts_arr + + pt = &Xarr[0, 0] + memory_error = False + with nogil: + for i in range(Xarr.shape[0]): + counts[i] = self._query_radius_single(0, pt, rarr[i], + &idx_arr_i[0], + &dist_arr_i[0], + 0, count_only, + return_distance) + pt += n_features + + if count_only: + continue + + if sort_results: + _simultaneous_sort(&dist_arr_i[0], &idx_arr_i[0], + counts[i]) + + # equivalent to: indices[i] = np_idx_arr[:counts[i]].copy() + indices[i] = malloc(counts[i] * sizeof(intp_t)) + if indices[i] == NULL: + memory_error = True + break + memcpy(indices[i], &idx_arr_i[0], counts[i] * sizeof(intp_t)) + + if return_distance: + # equivalent to: distances[i] = np_dist_arr[:counts[i]].copy() + distances[i] = <{{INPUT_DTYPE_t}}*>malloc(counts[i] * sizeof({{INPUT_DTYPE_t}})) + if distances[i] == NULL: + memory_error = True + break + memcpy(distances[i], &dist_arr_i[0], counts[i] * sizeof({{INPUT_DTYPE_t}})) + + try: + if memory_error: + raise MemoryError() + + if count_only: + # deflatten results + return counts_arr.reshape(X.shape[:X.ndim - 1]) + elif return_distance: + indices_npy = np.zeros(Xarr.shape[0], dtype='object') + distances_npy = np.zeros(Xarr.shape[0], dtype='object') + for i in range(Xarr.shape[0]): + # make a new numpy array that wraps the existing data + # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0 + indices_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], cnp.NPY_INTP, indices[i]) + # make sure the data will be freed when the numpy array is garbage collected + PyArray_ENABLEFLAGS(indices_npy[i], cnp.NPY_ARRAY_OWNDATA) + # make sure the data is not freed twice + indices[i] = NULL + + # make a new numpy array that wraps the existing data + # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0 + distances_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], {{NPY_TYPE}}, distances[i]) + # make sure the data will be freed when the numpy array is garbage collected + PyArray_ENABLEFLAGS(distances_npy[i], cnp.NPY_ARRAY_OWNDATA) + # make sure the data is not freed twice + distances[i] = NULL + + # deflatten results + return (indices_npy.reshape(X.shape[:X.ndim - 1]), + distances_npy.reshape(X.shape[:X.ndim - 1])) + else: + indices_npy = np.zeros(Xarr.shape[0], dtype='object') + for i in range(Xarr.shape[0]): + # make a new numpy array that wraps the existing data + # TODO: remove the explicit cast to cnp.intp_t* when cython min version >= 3.0 + indices_npy[i] = cnp.PyArray_SimpleNewFromData(1, &counts[i], cnp.NPY_INTP, indices[i]) + # make sure the data will be freed when the numpy array is garbage collected + PyArray_ENABLEFLAGS(indices_npy[i], cnp.NPY_ARRAY_OWNDATA) + # make sure the data is not freed twice + indices[i] = NULL + + # deflatten results + return indices_npy.reshape(X.shape[:X.ndim - 1]) + except MemoryError: + # free any buffer that is not owned by a numpy array + for i in range(Xarr.shape[0]): + free(indices[i]) + if return_distance: + free(distances[i]) + raise + finally: + free(indices) + free(distances) + + def kernel_density(self, X, h, kernel='gaussian', + atol=0, rtol=1E-8, + breadth_first=True, return_log=False): + """ + kernel_density(X, h, kernel='gaussian', atol=0, rtol=1E-8, + breadth_first=True, return_log=False) + + Compute the kernel density estimate at points X with the given kernel, + using the distance metric specified at tree creation. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array of points to query. Last dimension should match dimension + of training data. + h : float + the bandwidth of the kernel + kernel : str, default="gaussian" + specify the kernel to use. Options are + - 'gaussian' + - 'tophat' + - 'epanechnikov' + - 'exponential' + - 'linear' + - 'cosine' + Default is kernel = 'gaussian' + atol : float, default=0 + Specify the desired absolute tolerance of the result. + If the true result is `K_true`, then the returned result `K_ret` + satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret`` + The default is zero (i.e. machine precision). + rtol : float, default=1e-8 + Specify the desired relative tolerance of the result. + If the true result is `K_true`, then the returned result `K_ret` + satisfies ``abs(K_true - K_ret) < atol + rtol * K_ret`` + The default is `1e-8` (i.e. machine precision). + breadth_first : bool, default=False + If True, use a breadth-first search. If False (default) use a + depth-first search. Breadth-first is generally faster for + compact kernels and/or high tolerances. + return_log : bool, default=False + Return the logarithm of the result. This can be more accurate + than returning the result itself for narrow kernels. + + Returns + ------- + density : ndarray of shape X.shape[:-1] + The array of (log)-density evaluations + """ + cdef float64_t h_c = h + cdef float64_t log_atol = log(atol) + cdef float64_t log_rtol = log(rtol) + cdef float64_t log_min_bound, log_max_bound, log_bound_spread + cdef float64_t dist_LB = 0, dist_UB = 0 + + cdef intp_t n_samples = self.data.shape[0] + cdef intp_t n_features = self.data.shape[1] + cdef intp_t i + cdef KernelType kernel_c + + # validate kernel + if kernel == 'gaussian': + kernel_c = GAUSSIAN_KERNEL + elif kernel == 'tophat': + kernel_c = TOPHAT_KERNEL + elif kernel == 'epanechnikov': + kernel_c = EPANECHNIKOV_KERNEL + elif kernel == 'exponential': + kernel_c = EXPONENTIAL_KERNEL + elif kernel == 'linear': + kernel_c = LINEAR_KERNEL + elif kernel == 'cosine': + kernel_c = COSINE_KERNEL + else: + raise ValueError("kernel = '%s' not recognized" % kernel) + + cdef float64_t log_knorm = _log_kernel_norm(h_c, n_features, kernel_c) + + # validate X and prepare for query + X = check_array(X, dtype={{INPUT_DTYPE}}, order='C') + + if X.shape[X.ndim - 1] != n_features: + raise ValueError("query data dimension must " + "match training data dimension") + Xarr_np = X.reshape((-1, n_features)) + cdef const {{INPUT_DTYPE_t}}[:, ::1] Xarr = Xarr_np + + log_density_arr = np.zeros(Xarr.shape[0], dtype={{INPUT_DTYPE}}) + cdef {{INPUT_DTYPE_t}}[::1] log_density = log_density_arr + + cdef const {{INPUT_DTYPE_t}}* pt = &Xarr[0, 0] + + cdef NodeHeap nodeheap + if breadth_first: + nodeheap = NodeHeap(self.data.shape[0] // self.leaf_size) + cdef float64_t[::1] node_log_min_bounds + cdef float64_t[::1] node_bound_widths + # TODO: implement dual tree approach. + # this is difficult because of the need to cache values + # computed between node pairs. + if breadth_first: + node_log_min_bounds_arr = np.full(self.n_nodes, -np.inf) + node_log_min_bounds = node_log_min_bounds_arr + node_bound_widths_arr = np.zeros(self.n_nodes) + node_bound_widths = node_bound_widths_arr + for i in range(Xarr.shape[0]): + log_density[i] = self._kde_single_breadthfirst( + pt, kernel_c, h_c, + log_knorm, log_atol, log_rtol, + nodeheap, + &node_log_min_bounds[0], + &node_bound_widths[0]) + pt += n_features + else: + for i in range(Xarr.shape[0]): + min_max_dist{{name_suffix}}(self, 0, pt, &dist_LB, &dist_UB) + # compute max & min bounds on density within top node + log_min_bound = (log(self.sum_weight) + + compute_log_kernel(dist_UB, + h_c, kernel_c)) + log_max_bound = (log(self.sum_weight) + + compute_log_kernel(dist_LB, + h_c, kernel_c)) + log_bound_spread = logsubexp(log_max_bound, log_min_bound) + self._kde_single_depthfirst(0, pt, kernel_c, h_c, + log_knorm, log_atol, log_rtol, + log_min_bound, + log_bound_spread, + &log_min_bound, + &log_bound_spread) + log_density[i] = logaddexp(log_min_bound, + log_bound_spread - log(2)) + pt += n_features + + # normalize the results + for i in range(log_density.shape[0]): + log_density[i] += log_knorm + + log_density_arr = log_density_arr.reshape(X.shape[:X.ndim - 1]) + + if return_log: + return log_density_arr + else: + return np.exp(log_density_arr) + + def two_point_correlation(self, X, r, dualtree=False): + """ + two_point_correlation(X, r, dualtree=False) + + Compute the two-point correlation function + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array of points to query. Last dimension should match dimension + of training data. + r : array-like + A one-dimensional array of distances + dualtree : bool, default=False + If True, use a dualtree algorithm. Otherwise, use a single-tree + algorithm. Dual tree algorithms can have better scaling for + large N. + + Returns + ------- + counts : ndarray + counts[i] contains the number of pairs of points with distance + less than or equal to r[i] + """ + cdef intp_t n_features = self.data.shape[1] + cdef intp_t i + + # validate X and prepare for query + X = check_array(X, dtype={{INPUT_DTYPE}}, order='C') + + if X.shape[X.ndim - 1] != self.data.shape[1]: + raise ValueError("query data dimension must " + "match training data dimension") + + np_Xarr = X.reshape((-1, self.data.shape[1])) + cdef {{INPUT_DTYPE_t}}[:, ::1] Xarr = np_Xarr + + # prepare r for query + r = np.asarray(r, dtype=np.float64, order='C') + r = np.atleast_1d(r) + if r.ndim != 1: + raise ValueError("r must be a 1-dimensional array") + i_rsort = np.argsort(r) + rarr_np = r[i_rsort] # needed to keep memory in scope + cdef float64_t[::1] rarr = rarr_np + + # create array to hold counts + count = np.zeros(r.shape[0], dtype=np.intp) + cdef intp_t[::1] carr = count + + cdef const {{INPUT_DTYPE_t}}* pt = &Xarr[0, 0] + + if dualtree: + other = self.__class__(Xarr, metric=self.dist_metric, + leaf_size=self.leaf_size) + self._two_point_dual(0, other, 0, &rarr[0], &carr[0], + 0, rarr.shape[0]) + else: + for i in range(Xarr.shape[0]): + self._two_point_single(0, pt, &rarr[0], &carr[0], + 0, rarr.shape[0]) + pt += n_features + + return count + + cdef int _query_single_depthfirst( + self, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + intp_t i_pt, + NeighborsHeap{{name_suffix}} heap, + float64_t reduced_dist_LB, + ) except -1 nogil: + """Recursive Single-tree k-neighbors query, depth-first approach""" + cdef NodeData_t node_info = self.node_data[i_node] + + cdef float64_t dist_pt, reduced_dist_LB_1, reduced_dist_LB_2 + cdef intp_t i, i1, i2 + + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + + # ------------------------------------------------------------ + # Case 1: query point is outside node radius: + # trim it from the query + if reduced_dist_LB > heap.largest(i_pt): + self.n_trims += 1 + + # ------------------------------------------------------------ + # Case 2: this is a leaf node. Update set of nearby points + elif node_info.is_leaf: + self.n_leaves += 1 + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.rdist(pt, + &self.data[self.idx_array[i], 0], + self.data.shape[1]) + heap._push(i_pt, dist_pt, self.idx_array[i]) + + # ------------------------------------------------------------ + # Case 3: Node is not a leaf. Recursively query subnodes + # starting with the closest + else: + self.n_splits += 1 + i1 = 2 * i_node + 1 + i2 = i1 + 1 + reduced_dist_LB_1 = min_rdist{{name_suffix}}(self, i1, pt) + reduced_dist_LB_2 = min_rdist{{name_suffix}}(self, i2, pt) + + # recursively query subnodes + if reduced_dist_LB_1 <= reduced_dist_LB_2: + self._query_single_depthfirst(i1, pt, i_pt, heap, + reduced_dist_LB_1) + self._query_single_depthfirst(i2, pt, i_pt, heap, + reduced_dist_LB_2) + else: + self._query_single_depthfirst(i2, pt, i_pt, heap, + reduced_dist_LB_2) + self._query_single_depthfirst(i1, pt, i_pt, heap, + reduced_dist_LB_1) + return 0 + + cdef int _query_single_breadthfirst( + self, + const {{INPUT_DTYPE_t}}* pt, + intp_t i_pt, + NeighborsHeap{{name_suffix}} heap, + NodeHeap nodeheap, + ) except -1: + """Non-recursive single-tree k-neighbors query, breadth-first search""" + cdef intp_t i, i_node + cdef float64_t dist_pt, reduced_dist_LB + cdef const NodeData_t* node_data = &self.node_data[0] + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + + # Set up the node heap and push the head node onto it + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_rdist{{name_suffix}}(self, 0, pt) + nodeheap_item.i1 = 0 + nodeheap.push(nodeheap_item) + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + reduced_dist_LB = nodeheap_item.val + i_node = nodeheap_item.i1 + node_info = node_data[i_node] + + # ------------------------------------------------------------ + # Case 1: query point is outside node radius: + # trim it from the query + if reduced_dist_LB > heap.largest(i_pt): + self.n_trims += 1 + + # ------------------------------------------------------------ + # Case 2: this is a leaf node. Update set of nearby points + elif node_data[i_node].is_leaf: + self.n_leaves += 1 + for i in range(node_data[i_node].idx_start, + node_data[i_node].idx_end): + dist_pt = self.rdist(pt, + &self.data[self.idx_array[i], 0], + self.data.shape[1]) + heap._push(i_pt, dist_pt, self.idx_array[i]) + + # ------------------------------------------------------------ + # Case 3: Node is not a leaf. Add subnodes to the node heap + else: + self.n_splits += 1 + for i in range(2 * i_node + 1, 2 * i_node + 3): + nodeheap_item.i1 = i + nodeheap_item.val = min_rdist{{name_suffix}}(self, i, pt) + nodeheap.push(nodeheap_item) + return 0 + + cdef int _query_dual_depthfirst( + self, + intp_t i_node1, + BinaryTree{{name_suffix}} other, + intp_t i_node2, + float64_t[::1] bounds, + NeighborsHeap{{name_suffix}} heap, + float64_t reduced_dist_LB, + ) except -1: + """Recursive dual-tree k-neighbors query, depth-first""" + # note that the array `bounds` is maintained such that + # bounds[i] is the largest distance among any of the + # current neighbors in node i of the other tree. + cdef NodeData_t node_info1 = self.node_data[i_node1] + cdef NodeData_t node_info2 = other.node_data[i_node2] + + cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0] + cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0] + cdef intp_t n_features = self.data.shape[1] + + cdef float64_t bound_max, dist_pt, reduced_dist_LB1, reduced_dist_LB2 + cdef intp_t i1, i2, i_pt, i_parent + + # ------------------------------------------------------------ + # Case 1: nodes are further apart than the current bound: + # trim both from the query + if reduced_dist_LB > bounds[i_node2]: + pass + + # ------------------------------------------------------------ + # Case 2: both nodes are leaves: + # do a brute-force search comparing all pairs + elif node_info1.is_leaf and node_info2.is_leaf: + bounds[i_node2] = 0 + + for i2 in range(node_info2.idx_start, node_info2.idx_end): + i_pt = other.idx_array[i2] + + if heap.largest(i_pt) <= reduced_dist_LB: + continue + + for i1 in range(node_info1.idx_start, node_info1.idx_end): + dist_pt = self.rdist( + data1 + n_features * self.idx_array[i1], + data2 + n_features * i_pt, + n_features) + heap._push(i_pt, dist_pt, self.idx_array[i1]) + + # keep track of node bound + bounds[i_node2] = fmax(bounds[i_node2], + heap.largest(i_pt)) + + # update bounds up the tree + while i_node2 > 0: + i_parent = (i_node2 - 1) // 2 + bound_max = fmax(bounds[2 * i_parent + 1], + bounds[2 * i_parent + 2]) + if bound_max < bounds[i_parent]: + bounds[i_parent] = bound_max + i_node2 = i_parent + else: + break + + # ------------------------------------------------------------ + # Case 3a: node 1 is a leaf or is smaller: split node 2 and + # recursively query, starting with the nearest subnode + elif node_info1.is_leaf or (not node_info2.is_leaf + and node_info2.radius > node_info1.radius): + reduced_dist_LB1 = min_rdist_dual{{name_suffix}}(self, i_node1, + other, 2 * i_node2 + 1) + reduced_dist_LB2 = min_rdist_dual{{name_suffix}}(self, i_node1, + other, 2 * i_node2 + 2) + + if reduced_dist_LB1 < reduced_dist_LB2: + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + bounds, heap, reduced_dist_LB1) + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + bounds, heap, reduced_dist_LB2) + else: + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 2, + bounds, heap, reduced_dist_LB2) + self._query_dual_depthfirst(i_node1, other, 2 * i_node2 + 1, + bounds, heap, reduced_dist_LB1) + + # ------------------------------------------------------------ + # Case 3b: node 2 is a leaf or is smaller: split node 1 and + # recursively query, starting with the nearest subnode + else: + reduced_dist_LB1 = min_rdist_dual{{name_suffix}}(self, 2 * i_node1 + 1, + other, i_node2) + reduced_dist_LB2 = min_rdist_dual{{name_suffix}}(self, 2 * i_node1 + 2, + other, i_node2) + + if reduced_dist_LB1 < reduced_dist_LB2: + self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + bounds, heap, reduced_dist_LB1) + self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + bounds, heap, reduced_dist_LB2) + else: + self._query_dual_depthfirst(2 * i_node1 + 2, other, i_node2, + bounds, heap, reduced_dist_LB2) + self._query_dual_depthfirst(2 * i_node1 + 1, other, i_node2, + bounds, heap, reduced_dist_LB1) + return 0 + + cdef int _query_dual_breadthfirst( + self, + BinaryTree{{name_suffix}} other, + NeighborsHeap{{name_suffix}} heap, + NodeHeap nodeheap, + ) except -1: + """Non-recursive dual-tree k-neighbors query, breadth-first""" + cdef intp_t i, i1, i2, i_node1, i_node2, i_pt + cdef float64_t dist_pt, reduced_dist_LB + cdef float64_t[::1] bounds = np.full(other.node_data.shape[0], np.inf) + cdef const NodeData_t* node_data1 = &self.node_data[0] + cdef const NodeData_t* node_data2 = &other.node_data[0] + cdef NodeData_t node_info1, node_info2 + cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0] + cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0] + cdef intp_t n_features = self.data.shape[1] + + # Set up the node heap and push the head nodes onto it + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, 0, other, 0) + nodeheap_item.i1 = 0 + nodeheap_item.i2 = 0 + nodeheap.push(nodeheap_item) + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + reduced_dist_LB = nodeheap_item.val + i_node1 = nodeheap_item.i1 + i_node2 = nodeheap_item.i2 + + node_info1 = node_data1[i_node1] + node_info2 = node_data2[i_node2] + + # ------------------------------------------------------------ + # Case 1: nodes are further apart than the current bound: + # trim both from the query + if reduced_dist_LB > bounds[i_node2]: + pass + + # ------------------------------------------------------------ + # Case 2: both nodes are leaves: + # do a brute-force search comparing all pairs + elif node_info1.is_leaf and node_info2.is_leaf: + bounds[i_node2] = -1 + + for i2 in range(node_info2.idx_start, node_info2.idx_end): + i_pt = other.idx_array[i2] + + if heap.largest(i_pt) <= reduced_dist_LB: + continue + + for i1 in range(node_info1.idx_start, node_info1.idx_end): + dist_pt = self.rdist( + data1 + n_features * self.idx_array[i1], + data2 + n_features * i_pt, + n_features) + heap._push(i_pt, dist_pt, self.idx_array[i1]) + + # keep track of node bound + bounds[i_node2] = fmax(bounds[i_node2], + heap.largest(i_pt)) + + # ------------------------------------------------------------ + # Case 3a: node 1 is a leaf or is smaller: split node 2 and + # recursively query, starting with the nearest subnode + elif node_info1.is_leaf or (not node_info2.is_leaf + and (node_info2.radius + > node_info1.radius)): + nodeheap_item.i1 = i_node1 + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + nodeheap_item.i2 = i2 + nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, i_node1, + other, i2) + nodeheap.push(nodeheap_item) + + # ------------------------------------------------------------ + # Case 3b: node 2 is a leaf or is smaller: split node 1 and + # recursively query, starting with the nearest subnode + else: + nodeheap_item.i2 = i_node2 + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + nodeheap_item.i1 = i1 + nodeheap_item.val = min_rdist_dual{{name_suffix}}(self, i1, + other, i_node2) + nodeheap.push(nodeheap_item) + return 0 + + cdef intp_t _query_radius_single( + self, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + float64_t r, + intp_t* indices, + {{INPUT_DTYPE_t}}* distances, + intp_t count, + int count_only, + int return_distance, + ) noexcept nogil: + """recursive single-tree radius query, depth-first""" + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + cdef intp_t* idx_array = &self.idx_array[0] + cdef intp_t n_features = self.data.shape[1] + cdef NodeData_t node_info = self.node_data[i_node] + + cdef intp_t i + cdef float64_t reduced_r + + cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0 + min_max_dist{{name_suffix}}(self, i_node, pt, &dist_LB, &dist_UB) + + # ------------------------------------------------------------ + # Case 1: all node points are outside distance r. + # prune this branch. + if dist_LB > r: + pass + + # ------------------------------------------------------------ + # Case 2: all node points are within distance r + # add all points to neighbors + elif dist_UB <= r: + if count_only: + count += (node_info.idx_end - node_info.idx_start) + else: + for i in range(node_info.idx_start, node_info.idx_end): + if (count < 0) or (count >= self.data.shape[0]): + return -1 + indices[count] = idx_array[i] + if return_distance: + distances[count] = self.dist(pt, (data + n_features + * idx_array[i]), + n_features) + count += 1 + + # ------------------------------------------------------------ + # Case 3: this is a leaf node. Go through all points to + # determine if they fall within radius + elif node_info.is_leaf: + reduced_r = self.dist_metric._dist_to_rdist(r) + + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.rdist(pt, (data + n_features * idx_array[i]), + n_features) + if dist_pt <= reduced_r: + if (count < 0) or (count >= self.data.shape[0]): + return -1 + if count_only: + pass + else: + indices[count] = idx_array[i] + if return_distance: + distances[count] =\ + self.dist_metric._rdist_to_dist(dist_pt) + count += 1 + + # ------------------------------------------------------------ + # Case 4: Node is not a leaf. Recursively query subnodes + else: + count = self._query_radius_single(2 * i_node + 1, pt, r, + indices, distances, count, + count_only, return_distance) + count = self._query_radius_single(2 * i_node + 2, pt, r, + indices, distances, count, + count_only, return_distance) + + return count + + cdef float64_t _kde_single_breadthfirst( + self, const {{INPUT_DTYPE_t}}* pt, + KernelType kernel, + float64_t h, + float64_t log_knorm, + float64_t log_atol, + float64_t log_rtol, + NodeHeap nodeheap, + float64_t* node_log_min_bounds, + float64_t* node_log_bound_spreads, + ): + """non-recursive single-tree kernel density estimation""" + # For the given point, node_log_min_bounds and node_log_bound_spreads + # will encode the current bounds on the density between the point + # and the associated node. + # The variables global_log_min_bound and global_log_bound_spread + # keep track of the global bounds on density. The procedure here is + # to split nodes, updating these bounds, until the bounds are within + # atol & rtol. + cdef intp_t i, i1, i2, i_node + cdef float64_t N1, N2 + cdef float64_t global_log_min_bound, global_log_bound_spread + cdef float64_t global_log_max_bound + + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + cdef bint with_sample_weight = self.sample_weight is not None + cdef const {{INPUT_DTYPE_t}}* sample_weight + if with_sample_weight: + sample_weight = &self.sample_weight[0] + cdef intp_t* idx_array = &self.idx_array[0] + cdef const NodeData_t* node_data = &self.node_data[0] + cdef float64_t N + cdef float64_t log_weight + if with_sample_weight: + N = self.sum_weight + else: + N = self.data.shape[0] + cdef intp_t n_features = self.data.shape[1] + + cdef NodeData_t node_info + cdef float64_t dist_pt, log_density + cdef float64_t dist_LB_1 = 0, dist_LB_2 = 0 + cdef float64_t dist_UB_1 = 0, dist_UB_2 = 0 + + cdef float64_t dist_UB, dist_LB + + # push the top node to the heap + cdef NodeHeapData_t nodeheap_item + nodeheap_item.val = min_dist{{name_suffix}}(self, 0, pt) + nodeheap_item.i1 = 0 + nodeheap.push(nodeheap_item) + + global_log_min_bound = log(N) + compute_log_kernel( + max_dist{{name_suffix}}(self, 0, pt), h, kernel + ) + global_log_max_bound = log(N) + compute_log_kernel(nodeheap_item.val, + h, kernel) + global_log_bound_spread = logsubexp(global_log_max_bound, + global_log_min_bound) + + node_log_min_bounds[0] = global_log_min_bound + node_log_bound_spreads[0] = global_log_bound_spread + + while nodeheap.n > 0: + nodeheap_item = nodeheap.pop() + i_node = nodeheap_item.i1 + + node_info = node_data[i_node] + if with_sample_weight: + N1 = _total_node_weight(node_data, sample_weight, + idx_array, i_node) + else: + N1 = node_info.idx_end - node_info.idx_start + + # ------------------------------------------------------------ + # Case 1: local bounds are equal to within per-point tolerance. + if (log_knorm + node_log_bound_spreads[i_node] - log(N1) + log(N) + <= logaddexp(log_atol, (log_rtol + log_knorm + + node_log_min_bounds[i_node]))): + pass + + # ------------------------------------------------------------ + # Case 2: global bounds are within rtol & atol. + elif (log_knorm + global_log_bound_spread + <= logaddexp(log_atol, + log_rtol + log_knorm + global_log_min_bound)): + break + + # ------------------------------------------------------------ + # Case 3: node is a leaf. Count contributions from all points + elif node_info.is_leaf: + global_log_min_bound =\ + logsubexp(global_log_min_bound, + node_log_min_bounds[i_node]) + global_log_bound_spread =\ + logsubexp(global_log_bound_spread, + node_log_bound_spreads[i_node]) + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, data + n_features * idx_array[i], + n_features) + log_density = compute_log_kernel(dist_pt, h, kernel) + if with_sample_weight: + log_weight = np.log(sample_weight[idx_array[i]]) + else: + log_weight = 0. + global_log_min_bound = logaddexp(global_log_min_bound, + log_density + log_weight) + + # ------------------------------------------------------------ + # Case 4: split node and query subnodes + else: + i1 = 2 * i_node + 1 + i2 = 2 * i_node + 2 + + if with_sample_weight: + N1 = _total_node_weight(node_data, sample_weight, + idx_array, i1) + N2 = _total_node_weight(node_data, sample_weight, + idx_array, i2) + else: + N1 = node_data[i1].idx_end - node_data[i1].idx_start + N2 = node_data[i2].idx_end - node_data[i2].idx_start + + min_max_dist{{name_suffix}}(self, i1, pt, &dist_LB_1, &dist_UB_1) + min_max_dist{{name_suffix}}(self, i2, pt, &dist_LB_2, &dist_UB_2) + + node_log_min_bounds[i1] = (log(N1) + + compute_log_kernel(dist_UB_1, + h, kernel)) + node_log_bound_spreads[i1] = (log(N1) + + compute_log_kernel(dist_LB_1, + h, kernel)) + + node_log_min_bounds[i2] = (log(N2) + + compute_log_kernel(dist_UB_2, + h, kernel)) + node_log_bound_spreads[i2] = (log(N2) + + compute_log_kernel(dist_LB_2, + h, kernel)) + + global_log_min_bound = logsubexp(global_log_min_bound, + node_log_min_bounds[i_node]) + global_log_min_bound = logaddexp(global_log_min_bound, + node_log_min_bounds[i1]) + global_log_min_bound = logaddexp(global_log_min_bound, + node_log_min_bounds[i2]) + + global_log_bound_spread =\ + logsubexp(global_log_bound_spread, + node_log_bound_spreads[i_node]) + global_log_bound_spread = logaddexp(global_log_bound_spread, + node_log_bound_spreads[i1]) + global_log_bound_spread = logaddexp(global_log_bound_spread, + node_log_bound_spreads[i2]) + + # TODO: rank by the spread rather than the distance? + nodeheap_item.val = dist_LB_1 + nodeheap_item.i1 = i1 + nodeheap.push(nodeheap_item) + + nodeheap_item.val = dist_LB_2 + nodeheap_item.i1 = i2 + nodeheap.push(nodeheap_item) + + nodeheap.clear() + return logaddexp(global_log_min_bound, + global_log_bound_spread - log(2)) + + cdef int _kde_single_depthfirst( + self, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + KernelType kernel, + float64_t h, + float64_t log_knorm, + float64_t log_atol, + float64_t log_rtol, + float64_t local_log_min_bound, + float64_t local_log_bound_spread, + float64_t* global_log_min_bound, + float64_t* global_log_bound_spread, + ) except -1: + """recursive single-tree kernel density estimate, depth-first""" + # For the given point, local_min_bound and local_max_bound give the + # minimum and maximum density for the current node, while + # global_min_bound and global_max_bound give the minimum and maximum + # density over the entire tree. We recurse down until global_min_bound + # and global_max_bound are within rtol and atol. + cdef intp_t i, i1, i2, iw, start, end + cdef float64_t N1, N2 + + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + cdef const NodeData_t* node_data = &self.node_data[0] + cdef bint with_sample_weight = self.sample_weight is not None + cdef const {{INPUT_DTYPE_t}}* sample_weight + cdef float64_t log_weight + if with_sample_weight: + sample_weight = &self.sample_weight[0] + cdef intp_t* idx_array = &self.idx_array[0] + cdef intp_t n_features = self.data.shape[1] + + cdef NodeData_t node_info = self.node_data[i_node] + cdef float64_t dist_pt, log_dens_contribution + + cdef float64_t child1_log_min_bound, child2_log_min_bound + cdef float64_t child1_log_bound_spread, child2_log_bound_spread + cdef float64_t dist_UB = 0, dist_LB = 0 + + if with_sample_weight: + N1 = _total_node_weight(node_data, sample_weight, + idx_array, i_node) + N2 = self.sum_weight + else: + N1 = (node_info.idx_end - node_info.idx_start) + N2 = self.data.shape[0] + + # ------------------------------------------------------------ + # Case 1: local bounds are equal to within errors. Return + if ( + log_knorm + local_log_bound_spread - log(N1) + log(N2) + <= logaddexp(log_atol, (log_rtol + log_knorm + local_log_min_bound)) + ): + pass + + # ------------------------------------------------------------ + # Case 2: global bounds are within rtol & atol. Return + elif ( + log_knorm + global_log_bound_spread[0] + <= logaddexp(log_atol, (log_rtol + log_knorm + global_log_min_bound[0])) + ): + pass + + # ------------------------------------------------------------ + # Case 3: node is a leaf. Count contributions from all points + elif node_info.is_leaf: + global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + local_log_min_bound) + global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + local_log_bound_spread) + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + n_features) + log_dens_contribution = compute_log_kernel(dist_pt, h, kernel) + if with_sample_weight: + log_weight = np.log(sample_weight[idx_array[i]]) + else: + log_weight = 0. + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + (log_dens_contribution + + log_weight)) + + # ------------------------------------------------------------ + # Case 4: split node and query subnodes + else: + i1 = 2 * i_node + 1 + i2 = 2 * i_node + 2 + + if with_sample_weight: + N1 = _total_node_weight(node_data, sample_weight, + idx_array, i1) + N2 = _total_node_weight(node_data, sample_weight, + idx_array, i2) + else: + N1 = (self.node_data[i1].idx_end - self.node_data[i1].idx_start) + N2 = (self.node_data[i2].idx_end - self.node_data[i2].idx_start) + + min_max_dist{{name_suffix}}(self, i1, pt, &dist_LB, &dist_UB) + child1_log_min_bound = log(N1) + compute_log_kernel(dist_UB, h, + kernel) + child1_log_bound_spread = logsubexp(log(N1) + + compute_log_kernel(dist_LB, h, + kernel), + child1_log_min_bound) + + min_max_dist{{name_suffix}}(self, i2, pt, &dist_LB, &dist_UB) + child2_log_min_bound = log(N2) + compute_log_kernel(dist_UB, h, + kernel) + child2_log_bound_spread = logsubexp(log(N2) + + compute_log_kernel(dist_LB, h, + kernel), + child2_log_min_bound) + + global_log_min_bound[0] = logsubexp(global_log_min_bound[0], + local_log_min_bound) + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + child1_log_min_bound) + global_log_min_bound[0] = logaddexp(global_log_min_bound[0], + child2_log_min_bound) + + global_log_bound_spread[0] = logsubexp(global_log_bound_spread[0], + local_log_bound_spread) + global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + child1_log_bound_spread) + global_log_bound_spread[0] = logaddexp(global_log_bound_spread[0], + child2_log_bound_spread) + + self._kde_single_depthfirst(i1, pt, kernel, h, log_knorm, + log_atol, log_rtol, + child1_log_min_bound, + child1_log_bound_spread, + global_log_min_bound, + global_log_bound_spread) + self._kde_single_depthfirst(i2, pt, kernel, h, log_knorm, + log_atol, log_rtol, + child2_log_min_bound, + child2_log_bound_spread, + global_log_min_bound, + global_log_bound_spread) + return 0 + + cdef int _two_point_single( + self, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + float64_t* r, + intp_t* count, + intp_t i_min, + intp_t i_max, + ) except -1: + """recursive single-tree two-point correlation function query""" + cdef const {{INPUT_DTYPE_t}}* data = &self.data[0, 0] + cdef intp_t* idx_array = &self.idx_array[0] + cdef intp_t n_features = self.data.shape[1] + cdef NodeData_t node_info = self.node_data[i_node] + + cdef intp_t i, j, Npts + cdef float64_t reduced_r + + cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0 + min_max_dist{{name_suffix}}(self, i_node, pt, &dist_LB, &dist_UB) + + # ------------------------------------------------------------ + # Go through bounds and check for cuts + while i_min < i_max: + if dist_LB > r[i_min]: + i_min += 1 + else: + break + + while i_max > i_min: + Npts = (node_info.idx_end - node_info.idx_start) + if dist_UB <= r[i_max - 1]: + count[i_max - 1] += Npts + i_max -= 1 + else: + break + + if i_min < i_max: + # If node is a leaf, go through all points + if node_info.is_leaf: + for i in range(node_info.idx_start, node_info.idx_end): + dist_pt = self.dist(pt, (data + n_features * idx_array[i]), + n_features) + j = i_max - 1 + while (j >= i_min) and (dist_pt <= r[j]): + count[j] += 1 + j -= 1 + + else: + self._two_point_single(2 * i_node + 1, pt, r, + count, i_min, i_max) + self._two_point_single(2 * i_node + 2, pt, r, + count, i_min, i_max) + return 0 + + cdef int _two_point_dual( + self, + intp_t i_node1, + BinaryTree{{name_suffix}} other, + intp_t i_node2, + float64_t* r, + intp_t* count, + intp_t i_min, + intp_t i_max, + ) except -1: + """recursive dual-tree two-point correlation function query""" + cdef const {{INPUT_DTYPE_t}}* data1 = &self.data[0, 0] + cdef const {{INPUT_DTYPE_t}}* data2 = &other.data[0, 0] + cdef intp_t* idx_array1 = &self.idx_array[0] + cdef intp_t* idx_array2 = &other.idx_array[0] + cdef NodeData_t node_info1 = self.node_data[i_node1] + cdef NodeData_t node_info2 = other.node_data[i_node2] + + cdef intp_t n_features = self.data.shape[1] + + cdef intp_t i1, i2, j, Npts + cdef float64_t reduced_r + + cdef float64_t dist_pt, dist_LB = 0, dist_UB = 0 + dist_LB = min_dist_dual{{name_suffix}}(self, i_node1, other, i_node2) + dist_UB = max_dist_dual{{name_suffix}}(self, i_node1, other, i_node2) + + # ------------------------------------------------------------ + # Go through bounds and check for cuts + while i_min < i_max: + if dist_LB > r[i_min]: + i_min += 1 + else: + break + + while i_max > i_min: + Npts = ((node_info1.idx_end - node_info1.idx_start) + * (node_info2.idx_end - node_info2.idx_start)) + if dist_UB <= r[i_max - 1]: + count[i_max - 1] += Npts + i_max -= 1 + else: + break + + if i_min < i_max: + if node_info1.is_leaf and node_info2.is_leaf: + # If both nodes are leaves, go through all points + for i1 in range(node_info1.idx_start, node_info1.idx_end): + for i2 in range(node_info2.idx_start, node_info2.idx_end): + dist_pt = self.dist((data1 + n_features + * idx_array1[i1]), + (data2 + n_features + * idx_array2[i2]), + n_features) + j = i_max - 1 + while (j >= i_min) and (dist_pt <= r[j]): + count[j] += 1 + j -= 1 + + elif node_info1.is_leaf: + # If only one is a leaf, split the other + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + self._two_point_dual(i_node1, other, i2, + r, count, i_min, i_max) + + elif node_info2.is_leaf: + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + self._two_point_dual(i1, other, i_node2, + r, count, i_min, i_max) + + else: + # neither is a leaf: split & query both + for i1 in range(2 * i_node1 + 1, 2 * i_node1 + 3): + for i2 in range(2 * i_node2 + 1, 2 * i_node2 + 3): + self._two_point_dual(i1, other, i2, + r, count, i_min, i_max) + return 0 + +{{endfor}} + +###################################################################### +# Python functions for benchmarking and testing C implementations + +def simultaneous_sort(float64_t[:, ::1] distances, intp_t[:, ::1] indices): + """In-place simultaneous sort the given row of the arrays + + This python wrapper exists primarily to enable unit testing + of the _simultaneous_sort C routine. + """ + assert distances.shape[0] == indices.shape[0] + assert distances.shape[1] == indices.shape[1] + cdef intp_t row + for row in range(distances.shape[0]): + _simultaneous_sort(&distances[row, 0], + &indices[row, 0], + distances.shape[1]) + + +def nodeheap_sort(float64_t[::1] vals): + """In-place reverse sort of vals using NodeHeap""" + cdef intp_t[::1] indices = np.zeros(vals.shape[0], dtype=np.intp) + cdef float64_t[::1] vals_sorted = np.zeros_like(vals) + + # use initial size 0 to check corner case + cdef NodeHeap heap = NodeHeap(0) + cdef NodeHeapData_t data + cdef intp_t i + for i in range(vals.shape[0]): + data.val = vals[i] + data.i1 = i + data.i2 = i + 1 + heap.push(data) + + for i in range(vals.shape[0]): + data = heap.pop() + vals_sorted[i] = data.val + indices[i] = data.i1 + + return np.asarray(vals_sorted), np.asarray(indices) + + +cdef inline float64_t _total_node_weight( + const NodeData_t* node_data, + const floating* sample_weight, + const intp_t* idx_array, + intp_t i_node, +): + cdef intp_t i + cdef float64_t N = 0.0 + for i in range(node_data[i_node].idx_start, node_data[i_node].idx_end): + N += sample_weight[idx_array[i]] + return N diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_classification.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..c70b83cb1d3bdbcab4f241bf19416d410cbaf9e4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_classification.py @@ -0,0 +1,919 @@ +"""Nearest Neighbor Classification""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Integral + +import numpy as np + +from sklearn.neighbors._base import _check_precomputed + +from ..base import ClassifierMixin, _fit_context +from ..metrics._pairwise_distances_reduction import ( + ArgKminClassMode, + RadiusNeighborsClassMode, +) +from ..utils._param_validation import StrOptions +from ..utils.arrayfuncs import _all_with_any_reduction_axis_1 +from ..utils.extmath import weighted_mode +from ..utils.fixes import _mode +from ..utils.validation import ( + _is_arraylike, + _num_samples, + check_is_fitted, + validate_data, +) +from ._base import KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin, _get_weights + + +def _adjusted_metric(metric, metric_kwargs, p=None): + metric_kwargs = metric_kwargs or {} + if metric == "minkowski": + metric_kwargs["p"] = p + if p == 2: + metric = "euclidean" + return metric, metric_kwargs + + +class KNeighborsClassifier(KNeighborsMixin, ClassifierMixin, NeighborsBase): + """Classifier implementing the k-nearest neighbors vote. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_neighbors : int, default=5 + Number of neighbors to use by default for :meth:`kneighbors` queries. + + weights : {'uniform', 'distance'}, callable or None, default='uniform' + Weight function used in prediction. Possible values: + + - 'uniform' : uniform weights. All points in each neighborhood + are weighted equally. + - 'distance' : weight points by the inverse of their distance. + in this case, closer neighbors of a query point will have a + greater influence than neighbors which are further away. + - [callable] : a user-defined function which accepts an + array of distances, and returns an array of the same shape + containing the weights. + + Refer to the example entitled + :ref:`sphx_glr_auto_examples_neighbors_plot_classification.py` + showing the impact of the `weights` parameter on the decision + boundary. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree` + - 'kd_tree' will use :class:`KDTree` + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to BallTree or KDTree. This can affect the + speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + p : float, default=2 + Power parameter for the Minkowski metric. When p = 1, this is equivalent + to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. + For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected + to be positive. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + If metric is "precomputed", X is assumed to be a distance matrix and + must be square during fit. X may be a :term:`sparse graph`, in which + case only "nonzero" elements may be considered neighbors. + + If metric is a callable function, it takes two arrays representing 1D + vectors as inputs and must return one value indicating the distance + between those vectors. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + Doesn't affect :meth:`fit` method. + + Attributes + ---------- + classes_ : array of shape (n_classes,) + Class labels known to the classifier + + effective_metric_ : str or callble + The distance metric used. It will be same as the `metric` parameter + or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to + 'minkowski' and `p` parameter set to 2. + + effective_metric_params_ : dict + Additional keyword arguments for the metric function. For most metrics + will be same with `metric_params` parameter, but may also contain the + `p` parameter value if the `effective_metric_` attribute is set to + 'minkowski'. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_fit_ : int + Number of samples in the fitted data. + + outputs_2d_ : bool + False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit + otherwise True. + + See Also + -------- + RadiusNeighborsClassifier: Classifier based on neighbors within a fixed radius. + KNeighborsRegressor: Regression based on k-nearest neighbors. + RadiusNeighborsRegressor: Regression based on neighbors within a fixed radius. + NearestNeighbors: Unsupervised learner for implementing neighbor searches. + + Notes + ----- + See :ref:`Nearest Neighbors ` in the online documentation + for a discussion of the choice of ``algorithm`` and ``leaf_size``. + + .. warning:: + + Regarding the Nearest Neighbors algorithms, if it is found that two + neighbors, neighbor `k+1` and `k`, have identical distances + but different labels, the results will depend on the ordering of the + training data. + + https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm + + Examples + -------- + >>> X = [[0], [1], [2], [3]] + >>> y = [0, 0, 1, 1] + >>> from sklearn.neighbors import KNeighborsClassifier + >>> neigh = KNeighborsClassifier(n_neighbors=3) + >>> neigh.fit(X, y) + KNeighborsClassifier(...) + >>> print(neigh.predict([[1.1]])) + [0] + >>> print(neigh.predict_proba([[0.9]])) + [[0.666 0.333]] + """ + + _parameter_constraints: dict = {**NeighborsBase._parameter_constraints} + _parameter_constraints.pop("radius") + _parameter_constraints.update( + {"weights": [StrOptions({"uniform", "distance"}), callable, None]} + ) + + def __init__( + self, + n_neighbors=5, + *, + weights="uniform", + algorithm="auto", + leaf_size=30, + p=2, + metric="minkowski", + metric_params=None, + n_jobs=None, + ): + super().__init__( + n_neighbors=n_neighbors, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ) + self.weights = weights + + @_fit_context( + # KNeighborsClassifier.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y): + """Fit the k-nearest neighbors classifier from the training dataset. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) if metric='precomputed' + Training data. + + y : {array-like, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_outputs) + Target values. + + Returns + ------- + self : KNeighborsClassifier + The fitted k-nearest neighbors classifier. + """ + return self._fit(X, y) + + def predict(self, X): + """Predict the class labels for the provided data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', or None + Test samples. If `None`, predictions for all indexed points are + returned; in this case, points are not considered their own + neighbors. + + Returns + ------- + y : ndarray of shape (n_queries,) or (n_queries, n_outputs) + Class labels for each data sample. + """ + check_is_fitted(self, "_fit_method") + if self.weights == "uniform": + if self._fit_method == "brute" and ArgKminClassMode.is_usable_for( + X, self._fit_X, self.metric + ): + probabilities = self.predict_proba(X) + if self.outputs_2d_: + return np.stack( + [ + self.classes_[idx][np.argmax(probas, axis=1)] + for idx, probas in enumerate(probabilities) + ], + axis=1, + ) + return self.classes_[np.argmax(probabilities, axis=1)] + # In that case, we do not need the distances to perform + # the weighting so we do not compute them. + neigh_ind = self.kneighbors(X, return_distance=False) + neigh_dist = None + else: + neigh_dist, neigh_ind = self.kneighbors(X) + + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + n_outputs = len(classes_) + n_queries = _num_samples(self._fit_X if X is None else X) + weights = _get_weights(neigh_dist, self.weights) + if weights is not None and _all_with_any_reduction_axis_1(weights, value=0): + raise ValueError( + "All neighbors of some sample is getting zero weights. " + "Please modify 'weights' to avoid this case if you are " + "using a user-defined function." + ) + + y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) + for k, classes_k in enumerate(classes_): + if weights is None: + mode, _ = _mode(_y[neigh_ind, k], axis=1) + else: + mode, _ = weighted_mode(_y[neigh_ind, k], weights, axis=1) + + mode = np.asarray(mode.ravel(), dtype=np.intp) + y_pred[:, k] = classes_k.take(mode) + + if not self.outputs_2d_: + y_pred = y_pred.ravel() + + return y_pred + + def predict_proba(self, X): + """Return probability estimates for the test data X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', or None + Test samples. If `None`, predictions for all indexed points are + returned; in this case, points are not considered their own + neighbors. + + Returns + ------- + p : ndarray of shape (n_queries, n_classes), or a list of n_outputs \ + of such arrays if n_outputs > 1. + The class probabilities of the input samples. Classes are ordered + by lexicographic order. + """ + check_is_fitted(self, "_fit_method") + if self.weights == "uniform": + # TODO: systematize this mapping of metric for + # PairwiseDistancesReductions. + metric, metric_kwargs = _adjusted_metric( + metric=self.metric, metric_kwargs=self.metric_params, p=self.p + ) + if ( + self._fit_method == "brute" + and ArgKminClassMode.is_usable_for(X, self._fit_X, metric) + # TODO: Implement efficient multi-output solution + and not self.outputs_2d_ + ): + if self.metric == "precomputed": + X = _check_precomputed(X) + else: + X = validate_data( + self, X, accept_sparse="csr", reset=False, order="C" + ) + + probabilities = ArgKminClassMode.compute( + X, + self._fit_X, + k=self.n_neighbors, + weights=self.weights, + Y_labels=self._y, + unique_Y_labels=self.classes_, + metric=metric, + metric_kwargs=metric_kwargs, + # `strategy="parallel_on_X"` has in practice be shown + # to be more efficient than `strategy="parallel_on_Y`` + # on many combination of datasets. + # Hence, we choose to enforce it here. + # For more information, see: + # https://github.com/scikit-learn/scikit-learn/pull/24076#issuecomment-1445258342 + # TODO: adapt the heuristic for `strategy="auto"` for + # `ArgKminClassMode` and use `strategy="auto"`. + strategy="parallel_on_X", + ) + return probabilities + + # In that case, we do not need the distances to perform + # the weighting so we do not compute them. + neigh_ind = self.kneighbors(X, return_distance=False) + neigh_dist = None + else: + neigh_dist, neigh_ind = self.kneighbors(X) + + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + n_queries = _num_samples(self._fit_X if X is None else X) + + weights = _get_weights(neigh_dist, self.weights) + if weights is None: + weights = np.ones_like(neigh_ind) + elif _all_with_any_reduction_axis_1(weights, value=0): + raise ValueError( + "All neighbors of some sample is getting zero weights. " + "Please modify 'weights' to avoid this case if you are " + "using a user-defined function." + ) + + all_rows = np.arange(n_queries) + probabilities = [] + for k, classes_k in enumerate(classes_): + pred_labels = _y[:, k][neigh_ind] + proba_k = np.zeros((n_queries, classes_k.size)) + + # a simple ':' index doesn't work right + for i, idx in enumerate(pred_labels.T): # loop is O(n_neighbors) + proba_k[all_rows, idx] += weights[:, i] + + # normalize 'votes' into real [0,1] probabilities + normalizer = proba_k.sum(axis=1)[:, np.newaxis] + proba_k /= normalizer + + probabilities.append(proba_k) + + if not self.outputs_2d_: + probabilities = probabilities[0] + + return probabilities + + # This function is defined here only to modify the parent docstring + # and add information about X=None + def score(self, X, y, sample_weight=None): + """ + Return the mean accuracy on the given test data and labels. + + In multi-label classification, this is the subset accuracy + which is a harsh metric since you require for each sample that + each label set be correctly predicted. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features), or None + Test samples. If `None`, predictions for all indexed points are + used; in this case, points are not considered their own + neighbors. This means that `knn.fit(X, y).score(None, y)` + implicitly performs a leave-one-out cross-validation procedure + and is equivalent to `cross_val_score(knn, X, y, cv=LeaveOneOut())` + but typically much faster. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + True labels for `X`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float + Mean accuracy of ``self.predict(X)`` w.r.t. `y`. + """ + return super().score(X, y, sample_weight) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_label = True + tags.input_tags.pairwise = self.metric == "precomputed" + return tags + + +class RadiusNeighborsClassifier(RadiusNeighborsMixin, ClassifierMixin, NeighborsBase): + """Classifier implementing a vote among neighbors within a given radius. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + radius : float, default=1.0 + Range of parameter space to use by default for :meth:`radius_neighbors` + queries. + + weights : {'uniform', 'distance'}, callable or None, default='uniform' + Weight function used in prediction. Possible values: + + - 'uniform' : uniform weights. All points in each neighborhood + are weighted equally. + - 'distance' : weight points by the inverse of their distance. + in this case, closer neighbors of a query point will have a + greater influence than neighbors which are further away. + - [callable] : a user-defined function which accepts an + array of distances, and returns an array of the same shape + containing the weights. + + Uniform weights are used by default. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree` + - 'kd_tree' will use :class:`KDTree` + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to BallTree or KDTree. This can affect the + speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + p : float, default=2 + Power parameter for the Minkowski metric. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + This parameter is expected to be positive. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + If metric is "precomputed", X is assumed to be a distance matrix and + must be square during fit. X may be a :term:`sparse graph`, in which + case only "nonzero" elements may be considered neighbors. + + If metric is a callable function, it takes two arrays representing 1D + vectors as inputs and must return one value indicating the distance + between those vectors. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + outlier_label : {manual label, 'most_frequent'}, default=None + Label for outlier samples (samples with no neighbors in given radius). + + - manual label: str or int label (should be the same type as y) + or list of manual labels if multi-output is used. + - 'most_frequent' : assign the most frequent label of y to outliers. + - None : when any outlier is detected, ValueError will be raised. + + The outlier label should be selected from among the unique 'Y' labels. + If it is specified with a different value a warning will be raised and + all class probabilities of outliers will be assigned to be 0. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + classes_ : ndarray of shape (n_classes,) + Class labels known to the classifier. + + effective_metric_ : str or callable + The distance metric used. It will be same as the `metric` parameter + or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to + 'minkowski' and `p` parameter set to 2. + + effective_metric_params_ : dict + Additional keyword arguments for the metric function. For most metrics + will be same with `metric_params` parameter, but may also contain the + `p` parameter value if the `effective_metric_` attribute is set to + 'minkowski'. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_fit_ : int + Number of samples in the fitted data. + + outlier_label_ : int or array-like of shape (n_class,) + Label which is given for outlier samples (samples with no neighbors + on given radius). + + outputs_2d_ : bool + False when `y`'s shape is (n_samples, ) or (n_samples, 1) during fit + otherwise True. + + See Also + -------- + KNeighborsClassifier : Classifier implementing the k-nearest neighbors + vote. + RadiusNeighborsRegressor : Regression based on neighbors within a + fixed radius. + KNeighborsRegressor : Regression based on k-nearest neighbors. + NearestNeighbors : Unsupervised learner for implementing neighbor + searches. + + Notes + ----- + See :ref:`Nearest Neighbors ` in the online documentation + for a discussion of the choice of ``algorithm`` and ``leaf_size``. + + https://en.wikipedia.org/wiki/K-nearest_neighbor_algorithm + + Examples + -------- + >>> X = [[0], [1], [2], [3]] + >>> y = [0, 0, 1, 1] + >>> from sklearn.neighbors import RadiusNeighborsClassifier + >>> neigh = RadiusNeighborsClassifier(radius=1.0) + >>> neigh.fit(X, y) + RadiusNeighborsClassifier(...) + >>> print(neigh.predict([[1.5]])) + [0] + >>> print(neigh.predict_proba([[1.0]])) + [[0.66666667 0.33333333]] + """ + + _parameter_constraints: dict = { + **NeighborsBase._parameter_constraints, + "weights": [StrOptions({"uniform", "distance"}), callable, None], + "outlier_label": [Integral, str, "array-like", None], + } + _parameter_constraints.pop("n_neighbors") + + def __init__( + self, + radius=1.0, + *, + weights="uniform", + algorithm="auto", + leaf_size=30, + p=2, + metric="minkowski", + outlier_label=None, + metric_params=None, + n_jobs=None, + ): + super().__init__( + radius=radius, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ) + self.weights = weights + self.outlier_label = outlier_label + + @_fit_context( + # RadiusNeighborsClassifier.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y): + """Fit the radius neighbors classifier from the training dataset. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) if metric='precomputed' + Training data. + + y : {array-like, sparse matrix} of shape (n_samples,) or \ + (n_samples, n_outputs) + Target values. + + Returns + ------- + self : RadiusNeighborsClassifier + The fitted radius neighbors classifier. + """ + self._fit(X, y) + + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + if self.outlier_label is None: + outlier_label_ = None + + elif self.outlier_label == "most_frequent": + outlier_label_ = [] + # iterate over multi-output, get the most frequent label for each + # output. + for k, classes_k in enumerate(classes_): + label_count = np.bincount(_y[:, k]) + outlier_label_.append(classes_k[label_count.argmax()]) + + else: + if _is_arraylike(self.outlier_label) and not isinstance( + self.outlier_label, str + ): + if len(self.outlier_label) != len(classes_): + raise ValueError( + "The length of outlier_label: {} is " + "inconsistent with the output " + "length: {}".format(self.outlier_label, len(classes_)) + ) + outlier_label_ = self.outlier_label + else: + outlier_label_ = [self.outlier_label] * len(classes_) + + for classes, label in zip(classes_, outlier_label_): + if _is_arraylike(label) and not isinstance(label, str): + # ensure the outlier label for each output is a scalar. + raise TypeError( + "The outlier_label of classes {} is " + "supposed to be a scalar, got " + "{}.".format(classes, label) + ) + if np.append(classes, label).dtype != classes.dtype: + # ensure the dtype of outlier label is consistent with y. + raise TypeError( + "The dtype of outlier_label {} is " + "inconsistent with classes {} in " + "y.".format(label, classes) + ) + + self.outlier_label_ = outlier_label_ + + return self + + def predict(self, X): + """Predict the class labels for the provided data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', or None + Test samples. If `None`, predictions for all indexed points are + returned; in this case, points are not considered their own + neighbors. + + Returns + ------- + y : ndarray of shape (n_queries,) or (n_queries, n_outputs) + Class labels for each data sample. + """ + + probs = self.predict_proba(X) + classes_ = self.classes_ + + if not self.outputs_2d_: + probs = [probs] + classes_ = [self.classes_] + + n_outputs = len(classes_) + n_queries = probs[0].shape[0] + y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype) + + for k, prob in enumerate(probs): + # iterate over multi-output, assign labels based on probabilities + # of each output. + max_prob_index = prob.argmax(axis=1) + y_pred[:, k] = classes_[k].take(max_prob_index) + + outlier_zero_probs = (prob == 0).all(axis=1) + if outlier_zero_probs.any(): + zero_prob_index = np.flatnonzero(outlier_zero_probs) + y_pred[zero_prob_index, k] = self.outlier_label_[k] + + if not self.outputs_2d_: + y_pred = y_pred.ravel() + + return y_pred + + def predict_proba(self, X): + """Return probability estimates for the test data X. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_queries, n_features), \ + or (n_queries, n_indexed) if metric == 'precomputed', or None + Test samples. If `None`, predictions for all indexed points are + returned; in this case, points are not considered their own + neighbors. + + Returns + ------- + p : ndarray of shape (n_queries, n_classes), or a list of \ + n_outputs of such arrays if n_outputs > 1. + The class probabilities of the input samples. Classes are ordered + by lexicographic order. + """ + check_is_fitted(self, "_fit_method") + n_queries = _num_samples(self._fit_X if X is None else X) + + metric, metric_kwargs = _adjusted_metric( + metric=self.metric, metric_kwargs=self.metric_params, p=self.p + ) + + if ( + self.weights == "uniform" + and self._fit_method == "brute" + and not self.outputs_2d_ + and RadiusNeighborsClassMode.is_usable_for(X, self._fit_X, metric) + ): + probabilities = RadiusNeighborsClassMode.compute( + X=X, + Y=self._fit_X, + radius=self.radius, + weights=self.weights, + Y_labels=self._y, + unique_Y_labels=self.classes_, + outlier_label=self.outlier_label, + metric=metric, + metric_kwargs=metric_kwargs, + strategy="parallel_on_X", + # `strategy="parallel_on_X"` has in practice be shown + # to be more efficient than `strategy="parallel_on_Y`` + # on many combination of datasets. + # Hence, we choose to enforce it here. + # For more information, see: + # https://github.com/scikit-learn/scikit-learn/pull/26828/files#r1282398471 + ) + return probabilities + + neigh_dist, neigh_ind = self.radius_neighbors(X) + outlier_mask = np.zeros(n_queries, dtype=bool) + outlier_mask[:] = [len(nind) == 0 for nind in neigh_ind] + outliers = np.flatnonzero(outlier_mask) + inliers = np.flatnonzero(~outlier_mask) + + classes_ = self.classes_ + _y = self._y + if not self.outputs_2d_: + _y = self._y.reshape((-1, 1)) + classes_ = [self.classes_] + + if self.outlier_label_ is None and outliers.size > 0: + raise ValueError( + "No neighbors found for test samples %r, " + "you can try using larger radius, " + "giving a label for outliers, " + "or considering removing them from your dataset." % outliers + ) + + weights = _get_weights(neigh_dist, self.weights) + if weights is not None: + weights = weights[inliers] + + probabilities = [] + # iterate over multi-output, measure probabilities of the k-th output. + for k, classes_k in enumerate(classes_): + pred_labels = np.zeros(len(neigh_ind), dtype=object) + pred_labels[:] = [_y[ind, k] for ind in neigh_ind] + + proba_k = np.zeros((n_queries, classes_k.size)) + proba_inl = np.zeros((len(inliers), classes_k.size)) + + # samples have different size of neighbors within the same radius + if weights is None: + for i, idx in enumerate(pred_labels[inliers]): + proba_inl[i, :] = np.bincount(idx, minlength=classes_k.size) + else: + for i, idx in enumerate(pred_labels[inliers]): + proba_inl[i, :] = np.bincount( + idx, weights[i], minlength=classes_k.size + ) + proba_k[inliers, :] = proba_inl + + if outliers.size > 0: + _outlier_label = self.outlier_label_[k] + label_index = np.flatnonzero(classes_k == _outlier_label) + if label_index.size == 1: + proba_k[outliers, label_index[0]] = 1.0 + else: + warnings.warn( + "Outlier label {} is not in training " + "classes. All class probabilities of " + "outliers will be assigned with 0." + "".format(self.outlier_label_[k]) + ) + + # normalize 'votes' into real [0,1] probabilities + normalizer = proba_k.sum(axis=1)[:, np.newaxis] + normalizer[normalizer == 0.0] = 1.0 + proba_k /= normalizer + + probabilities.append(proba_k) + + if not self.outputs_2d_: + probabilities = probabilities[0] + + return probabilities + + # This function is defined here only to modify the parent docstring + # and add information about X=None + def score(self, X, y, sample_weight=None): + """ + Return the mean accuracy on the given test data and labels. + + In multi-label classification, this is the subset accuracy + which is a harsh metric since you require for each sample that + each label set be correctly predicted. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features), or None + Test samples. If `None`, predictions for all indexed points are + used; in this case, points are not considered their own + neighbors. This means that `knn.fit(X, y).score(None, y)` + implicitly performs a leave-one-out cross-validation procedure + and is equivalent to `cross_val_score(knn, X, y, cv=LeaveOneOut())` + but typically much faster. + + y : array-like of shape (n_samples,) or (n_samples, n_outputs) + True labels for `X`. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + Returns + ------- + score : float + Mean accuracy of ``self.predict(X)`` w.r.t. `y`. + """ + return super().score(X, y, sample_weight) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_label = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_graph.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..3562fab1fcf01b5487d210a11d83d203bffd7835 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_graph.py @@ -0,0 +1,704 @@ +"""Nearest Neighbors graph functions""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools + +from ..base import ClassNamePrefixFeaturesOutMixin, TransformerMixin, _fit_context +from ..utils._param_validation import ( + Integral, + Interval, + Real, + StrOptions, + validate_params, +) +from ..utils.validation import check_is_fitted +from ._base import VALID_METRICS, KNeighborsMixin, NeighborsBase, RadiusNeighborsMixin +from ._unsupervised import NearestNeighbors + + +def _check_params(X, metric, p, metric_params): + """Check the validity of the input parameters""" + params = zip(["metric", "p", "metric_params"], [metric, p, metric_params]) + est_params = X.get_params() + for param_name, func_param in params: + if func_param != est_params[param_name]: + raise ValueError( + "Got %s for %s, while the estimator has %s for the same parameter." + % (func_param, param_name, est_params[param_name]) + ) + + +def _query_include_self(X, include_self, mode): + """Return the query based on include_self param""" + if include_self == "auto": + include_self = mode == "connectivity" + + # it does not include each sample as its own neighbors + if not include_self: + X = None + + return X + + +@validate_params( + { + "X": ["array-like", "sparse matrix", KNeighborsMixin], + "n_neighbors": [Interval(Integral, 1, None, closed="left")], + "mode": [StrOptions({"connectivity", "distance"})], + "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable], + "p": [Interval(Real, 0, None, closed="right"), None], + "metric_params": [dict, None], + "include_self": ["boolean", StrOptions({"auto"})], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def kneighbors_graph( + X, + n_neighbors, + *, + mode="connectivity", + metric="minkowski", + p=2, + metric_params=None, + include_self=False, + n_jobs=None, +): + """Compute the (weighted) graph of k-Neighbors for points in X. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Sample data. + + n_neighbors : int + Number of neighbors for each sample. + + mode : {'connectivity', 'distance'}, default='connectivity' + Type of returned matrix: 'connectivity' will return the connectivity + matrix with ones and zeros, and 'distance' will return the distances + between neighbors according to the given metric. + + metric : str, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + p : float, default=2 + Power parameter for the Minkowski metric. When p = 1, this is equivalent + to using manhattan_distance (l1), and euclidean_distance (l2) for p = 2. + For arbitrary p, minkowski_distance (l_p) is used. This parameter is expected + to be positive. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + include_self : bool or 'auto', default=False + Whether or not to mark each sample as the first nearest neighbor to + itself. If 'auto', then True is used for mode='connectivity' and False + for mode='distance'. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + A : sparse matrix of shape (n_samples, n_samples) + Graph where A[i, j] is assigned the weight of edge that + connects i to j. The matrix is of CSR format. + + See Also + -------- + radius_neighbors_graph: Compute the (weighted) graph of Neighbors for points in X. + + Examples + -------- + >>> X = [[0], [3], [1]] + >>> from sklearn.neighbors import kneighbors_graph + >>> A = kneighbors_graph(X, 2, mode='connectivity', include_self=True) + >>> A.toarray() + array([[1., 0., 1.], + [0., 1., 1.], + [1., 0., 1.]]) + """ + if not isinstance(X, KNeighborsMixin): + X = NearestNeighbors( + n_neighbors=n_neighbors, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ).fit(X) + else: + _check_params(X, metric, p, metric_params) + + query = _query_include_self(X._fit_X, include_self, mode) + return X.kneighbors_graph(X=query, n_neighbors=n_neighbors, mode=mode) + + +@validate_params( + { + "X": ["array-like", "sparse matrix", RadiusNeighborsMixin], + "radius": [Interval(Real, 0, None, closed="both")], + "mode": [StrOptions({"connectivity", "distance"})], + "metric": [StrOptions(set(itertools.chain(*VALID_METRICS.values()))), callable], + "p": [Interval(Real, 0, None, closed="right"), None], + "metric_params": [dict, None], + "include_self": ["boolean", StrOptions({"auto"})], + "n_jobs": [Integral, None], + }, + prefer_skip_nested_validation=False, # metric is not validated yet +) +def radius_neighbors_graph( + X, + radius, + *, + mode="connectivity", + metric="minkowski", + p=2, + metric_params=None, + include_self=False, + n_jobs=None, +): + """Compute the (weighted) graph of Neighbors for points in X. + + Neighborhoods are restricted the points at a distance lower than + radius. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Sample data. + + radius : float + Radius of neighborhoods. + + mode : {'connectivity', 'distance'}, default='connectivity' + Type of returned matrix: 'connectivity' will return the connectivity + matrix with ones and zeros, and 'distance' will return the distances + between neighbors according to the given metric. + + metric : str, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + p : float, default=2 + Power parameter for the Minkowski metric. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + include_self : bool or 'auto', default=False + Whether or not to mark each sample as the first nearest neighbor to + itself. If 'auto', then True is used for mode='connectivity' and False + for mode='distance'. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Returns + ------- + A : sparse matrix of shape (n_samples, n_samples) + Graph where A[i, j] is assigned the weight of edge that connects + i to j. The matrix is of CSR format. + + See Also + -------- + kneighbors_graph: Compute the weighted graph of k-neighbors for points in X. + + Examples + -------- + >>> X = [[0], [3], [1]] + >>> from sklearn.neighbors import radius_neighbors_graph + >>> A = radius_neighbors_graph(X, 1.5, mode='connectivity', + ... include_self=True) + >>> A.toarray() + array([[1., 0., 1.], + [0., 1., 0.], + [1., 0., 1.]]) + """ + if not isinstance(X, RadiusNeighborsMixin): + X = NearestNeighbors( + radius=radius, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ).fit(X) + else: + _check_params(X, metric, p, metric_params) + + query = _query_include_self(X._fit_X, include_self, mode) + return X.radius_neighbors_graph(query, radius, mode) + + +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. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.22 + + Parameters + ---------- + mode : {'distance', 'connectivity'}, default='distance' + Type of returned matrix: 'connectivity' will return the connectivity + matrix with ones and zeros, and 'distance' will return the distances + between neighbors according to the given metric. + + n_neighbors : int, default=5 + Number of neighbors for each sample in the transformed sparse graph. + For compatibility reasons, as each sample is considered as its own + neighbor, one extra neighbor will be computed when mode == 'distance'. + In this case, the sparse graph contains (n_neighbors + 1) neighbors. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree` + - 'kd_tree' will use :class:`KDTree` + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to BallTree or KDTree. This can affect the + speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + If metric is a callable function, it takes two arrays representing 1D + vectors as inputs and must return one value indicating the distance + between those vectors. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + p : float, default=2 + Parameter for the Minkowski metric from + sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + This parameter is expected to be positive. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + If ``-1``, then the number of jobs is set to the number of CPU cores. + + Attributes + ---------- + effective_metric_ : str or callable + The distance metric used. It will be same as the `metric` parameter + or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to + 'minkowski' and `p` parameter set to 2. + + effective_metric_params_ : dict + Additional keyword arguments for the metric function. For most metrics + will be same with `metric_params` parameter, but may also contain the + `p` parameter value if the `effective_metric_` attribute is set to + 'minkowski'. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_fit_ : int + Number of samples in the fitted data. + + See Also + -------- + kneighbors_graph : Compute the weighted graph of k-neighbors for + points in X. + RadiusNeighborsTransformer : Transform X into a weighted graph of + neighbors nearer than a radius. + + Notes + ----- + For an example of using :class:`~sklearn.neighbors.KNeighborsTransformer` + in combination with :class:`~sklearn.manifold.TSNE` see + :ref:`sphx_glr_auto_examples_neighbors_approximate_nearest_neighbors.py`. + + Examples + -------- + >>> from sklearn.datasets import load_wine + >>> from sklearn.neighbors import KNeighborsTransformer + >>> X, _ = load_wine(return_X_y=True) + >>> X.shape + (178, 13) + >>> transformer = KNeighborsTransformer(n_neighbors=5, mode='distance') + >>> X_dist_graph = transformer.fit_transform(X) + >>> X_dist_graph.shape + (178, 178) + """ + + _parameter_constraints: dict = { + **NeighborsBase._parameter_constraints, + "mode": [StrOptions({"distance", "connectivity"})], + } + _parameter_constraints.pop("radius") + + def __init__( + self, + *, + mode="distance", + n_neighbors=5, + algorithm="auto", + leaf_size=30, + metric="minkowski", + p=2, + metric_params=None, + n_jobs=None, + ): + super().__init__( + n_neighbors=n_neighbors, + radius=None, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ) + self.mode = mode + + @_fit_context( + # KNeighborsTransformer.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Fit the k-nearest neighbors transformer from the training dataset. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) if metric='precomputed' + Training data. + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : KNeighborsTransformer + The fitted k-nearest neighbors transformer. + """ + 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. + + Parameters + ---------- + X : array-like of shape (n_samples_transform, n_features) + Sample data. + + Returns + ------- + Xt : sparse matrix of shape (n_samples_transform, n_samples_fit) + Xt[i, j] is assigned the weight of edge that connects i to j. + Only the neighbors have an explicit value. + The diagonal is always explicit. + The matrix is of CSR format. + """ + check_is_fitted(self) + add_one = self.mode == "distance" + return self.kneighbors_graph( + X, mode=self.mode, n_neighbors=self.n_neighbors + add_one + ) + + def fit_transform(self, X, y=None): + """Fit to data, then transform it. + + Fits transformer to X and y with optional parameters fit_params + and returns a transformed version of X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training set. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + Xt : sparse matrix of shape (n_samples, n_samples) + Xt[i, j] is assigned the weight of edge that connects i to j. + Only the neighbors have an explicit value. + The diagonal is always explicit. + The matrix is of CSR format. + """ + return self.fit(X).transform(X) + + +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 + `radius_neighbors_graph`. + + Read more in the :ref:`User Guide `. + + .. versionadded:: 0.22 + + Parameters + ---------- + mode : {'distance', 'connectivity'}, default='distance' + Type of returned matrix: 'connectivity' will return the connectivity + matrix with ones and zeros, and 'distance' will return the distances + between neighbors according to the given metric. + + radius : float, default=1.0 + Radius of neighborhood in the transformed sparse graph. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree` + - 'kd_tree' will use :class:`KDTree` + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf size passed to BallTree or KDTree. This can affect the + speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + If metric is a callable function, it takes two arrays representing 1D + vectors as inputs and must return one value indicating the distance + between those vectors. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + Distance matrices are not supported. + + p : float, default=2 + Parameter for the Minkowski metric from + sklearn.metrics.pairwise.pairwise_distances. When p = 1, this is + equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + This parameter is expected to be positive. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + If ``-1``, then the number of jobs is set to the number of CPU cores. + + Attributes + ---------- + effective_metric_ : str or callable + The distance metric used. It will be same as the `metric` parameter + or a synonym of it, e.g. 'euclidean' if the `metric` parameter set to + 'minkowski' and `p` parameter set to 2. + + effective_metric_params_ : dict + Additional keyword arguments for the metric function. For most metrics + will be same with `metric_params` parameter, but may also contain the + `p` parameter value if the `effective_metric_` attribute is set to + 'minkowski'. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_fit_ : int + Number of samples in the fitted data. + + See Also + -------- + kneighbors_graph : Compute the weighted graph of k-neighbors for + points in X. + KNeighborsTransformer : Transform X into a weighted graph of k + nearest neighbors. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.datasets import load_wine + >>> from sklearn.cluster import DBSCAN + >>> from sklearn.neighbors import RadiusNeighborsTransformer + >>> from sklearn.pipeline import make_pipeline + >>> X, _ = load_wine(return_X_y=True) + >>> estimator = make_pipeline( + ... RadiusNeighborsTransformer(radius=42.0, mode='distance'), + ... DBSCAN(eps=25.0, metric='precomputed')) + >>> X_clustered = estimator.fit_predict(X) + >>> clusters, counts = np.unique(X_clustered, return_counts=True) + >>> print(counts) + [ 29 15 111 11 12] + """ + + _parameter_constraints: dict = { + **NeighborsBase._parameter_constraints, + "mode": [StrOptions({"distance", "connectivity"})], + } + _parameter_constraints.pop("n_neighbors") + + def __init__( + self, + *, + mode="distance", + radius=1.0, + algorithm="auto", + leaf_size=30, + metric="minkowski", + p=2, + metric_params=None, + n_jobs=None, + ): + super().__init__( + n_neighbors=None, + radius=radius, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ) + self.mode = mode + + @_fit_context( + # RadiusNeighborsTransformer.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Fit the radius neighbors transformer from the training dataset. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) if metric='precomputed' + Training data. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : RadiusNeighborsTransformer + The fitted radius neighbors transformer. + """ + 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. + + Parameters + ---------- + X : array-like of shape (n_samples_transform, n_features) + Sample data. + + Returns + ------- + Xt : sparse matrix of shape (n_samples_transform, n_samples_fit) + Xt[i, j] is assigned the weight of edge that connects i to j. + Only the neighbors have an explicit value. + The diagonal is always explicit. + The matrix is of CSR format. + """ + check_is_fitted(self) + return self.radius_neighbors_graph(X, mode=self.mode, sort_results=True) + + def fit_transform(self, X, y=None): + """Fit to data, then transform it. + + Fits transformer to X and y with optional parameters fit_params + and returns a transformed version of X. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Training set. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + Xt : sparse matrix of shape (n_samples, n_samples) + Xt[i, j] is assigned the weight of edge that connects i to j. + Only the neighbors have an explicit value. + The diagonal is always explicit. + The matrix is of CSR format. + """ + return self.fit(X).transform(X) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp new file mode 100644 index 0000000000000000000000000000000000000000..d21af05270b9aad33560ea6ff72d55c3fa5c91b4 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kd_tree.pyx.tp @@ -0,0 +1,336 @@ +{{py: + +# Generated file: _kd_tree.pyx + +implementation_specific_values = [ + # The values are arranged as follows: + # + # name_suffix, INPUT_DTYPE_t, INPUT_DTYPE + # + ('64', 'float64_t', 'np.float64'), + ('32', 'float32_t', 'np.float32') +] + +# By Jake Vanderplas (2013) +# written for the scikit-learn project +# SPDX-License-Identifier: BSD-3-Clause + +}} + + +__all__ = ['KDTree', 'KDTree64', 'KDTree32'] + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +DOC_DICT{{name_suffix}} = { + 'BinaryTree': 'KDTree{{name_suffix}}', + 'binary_tree': 'kd_tree{{name_suffix}}', +} + +VALID_METRICS{{name_suffix}} = [ + 'EuclideanDistance{{name_suffix}}', + 'ManhattanDistance{{name_suffix}}', + 'ChebyshevDistance{{name_suffix}}', + 'MinkowskiDistance{{name_suffix}}' +] + +{{endfor}} + +include "_binary_tree.pxi" + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +# Inherit KDTree{{name_suffix}} from BinaryTree{{name_suffix}} +cdef class KDTree{{name_suffix}}(BinaryTree{{name_suffix}}): + __doc__ = CLASS_DOC.format(**DOC_DICT{{name_suffix}}) + pass + +{{endfor}} + + +# ---------------------------------------------------------------------- +# The functions below specialized the Binary Tree as a KD Tree +# +# Note that these functions use the concept of "reduced distance". +# The reduced distance, defined for some metrics, is a quantity which +# is more efficient to compute than the distance, but preserves the +# relative rankings of the true distance. For example, the reduced +# distance for the Euclidean metric is the squared-euclidean distance. +# For some metrics, the reduced distance is simply the distance. + +{{for name_suffix, INPUT_DTYPE_t, INPUT_DTYPE in implementation_specific_values}} + +cdef int allocate_data{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t n_nodes, + intp_t n_features, +) except -1: + """Allocate arrays needed for the KD Tree""" + tree.node_bounds = np.zeros((2, n_nodes, n_features), dtype={{INPUT_DTYPE}}) + return 0 + + +cdef int init_node{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + NodeData_t[::1] node_data, + intp_t i_node, + intp_t idx_start, + intp_t idx_end, +) except -1: + """Initialize the node for the dataset stored in tree.data""" + cdef intp_t n_features = tree.data.shape[1] + cdef intp_t i, j + cdef float64_t rad = 0 + + cdef {{INPUT_DTYPE_t}}* lower_bounds = &tree.node_bounds[0, i_node, 0] + cdef {{INPUT_DTYPE_t}}* upper_bounds = &tree.node_bounds[1, i_node, 0] + cdef const {{INPUT_DTYPE_t}}* data = &tree.data[0, 0] + cdef const intp_t* idx_array = &tree.idx_array[0] + + cdef const {{INPUT_DTYPE_t}}* data_row + + # determine Node bounds + for j in range(n_features): + lower_bounds[j] = INF + upper_bounds[j] = -INF + + # Compute the actual data range. At build time, this is slightly + # slower than using the previously-computed bounds of the parent node, + # but leads to more compact trees and thus faster queries. + for i in range(idx_start, idx_end): + data_row = data + idx_array[i] * n_features + for j in range(n_features): + lower_bounds[j] = fmin(lower_bounds[j], data_row[j]) + upper_bounds[j] = fmax(upper_bounds[j], data_row[j]) + + for j in range(n_features): + if tree.dist_metric.p == INF: + rad = fmax(rad, 0.5 * (upper_bounds[j] - lower_bounds[j])) + else: + rad += pow(0.5 * abs(upper_bounds[j] - lower_bounds[j]), + tree.dist_metric.p) + + node_data[i_node].idx_start = idx_start + node_data[i_node].idx_end = idx_end + + # The radius will hold the size of the circumscribed hypersphere measured + # with the specified metric: in querying, this is used as a measure of the + # size of each node when deciding which nodes to split. + node_data[i_node].radius = pow(rad, 1. / tree.dist_metric.p) + return 0 + + +cdef float64_t min_rdist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1 nogil: + """Compute the minimum reduced-distance between a point and a node""" + cdef intp_t n_features = tree.data.shape[1] + cdef float64_t d, d_lo, d_hi, rdist=0.0 + cdef intp_t j + + if tree.dist_metric.p == INF: + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + rdist = fmax(rdist, 0.5 * d) + else: + # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + rdist += pow(0.5 * d, tree.dist_metric.p) + + return rdist + + +cdef float64_t min_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1: + """Compute the minimum distance between a point and a node""" + if tree.dist_metric.p == INF: + return min_rdist{{name_suffix}}(tree, i_node, pt) + else: + return pow( + min_rdist{{name_suffix}}(tree, i_node, pt), + 1. / tree.dist_metric.p + ) + + +cdef float64_t max_rdist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1: + """Compute the maximum reduced-distance between a point and a node""" + cdef intp_t n_features = tree.data.shape[1] + + cdef float64_t d_lo, d_hi, rdist=0.0 + cdef intp_t j + + if tree.dist_metric.p == INF: + for j in range(n_features): + rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[0, i_node, j])) + rdist = fmax(rdist, fabs(pt[j] - tree.node_bounds[1, i_node, j])) + else: + for j in range(n_features): + d_lo = fabs(pt[j] - tree.node_bounds[0, i_node, j]) + d_hi = fabs(pt[j] - tree.node_bounds[1, i_node, j]) + rdist += pow(fmax(d_lo, d_hi), tree.dist_metric.p) + + return rdist + + +cdef float64_t max_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, +) except -1: + """Compute the maximum distance between a point and a node""" + if tree.dist_metric.p == INF: + return max_rdist{{name_suffix}}(tree, i_node, pt) + else: + return pow( + max_rdist{{name_suffix}}(tree, i_node, pt), + 1. / tree.dist_metric.p + ) + + +cdef inline int min_max_dist{{name_suffix}}( + BinaryTree{{name_suffix}} tree, + intp_t i_node, + const {{INPUT_DTYPE_t}}* pt, + float64_t* min_dist, + float64_t* max_dist, +) except -1 nogil: + """Compute the minimum and maximum distance between a point and a node""" + cdef intp_t n_features = tree.data.shape[1] + + cdef float64_t d, d_lo, d_hi + cdef intp_t j + + min_dist[0] = 0.0 + max_dist[0] = 0.0 + + if tree.dist_metric.p == INF: + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + min_dist[0] = fmax(min_dist[0], 0.5 * d) + max_dist[0] = fmax(max_dist[0], fabs(d_lo)) + max_dist[0] = fmax(max_dist[0], fabs(d_hi)) + else: + # as above, use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d_lo = tree.node_bounds[0, i_node, j] - pt[j] + d_hi = pt[j] - tree.node_bounds[1, i_node, j] + d = (d_lo + fabs(d_lo)) + (d_hi + fabs(d_hi)) + min_dist[0] += pow(0.5 * d, tree.dist_metric.p) + max_dist[0] += pow(fmax(fabs(d_lo), fabs(d_hi)), + tree.dist_metric.p) + + min_dist[0] = pow(min_dist[0], 1. / tree.dist_metric.p) + max_dist[0] = pow(max_dist[0], 1. / tree.dist_metric.p) + + return 0 + + +cdef inline float64_t min_rdist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """Compute the minimum reduced distance between two nodes""" + cdef intp_t n_features = tree1.data.shape[1] + + cdef float64_t d, d1, d2, rdist=0.0 + cdef intp_t j + + if tree1.dist_metric.p == INF: + for j in range(n_features): + d1 = (tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = (tree2.node_bounds[0, i_node2, j] + - tree1.node_bounds[1, i_node1, j]) + d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + + rdist = fmax(rdist, 0.5 * d) + else: + # here we'll use the fact that x + abs(x) = 2 * max(x, 0) + for j in range(n_features): + d1 = (tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = (tree2.node_bounds[0, i_node2, j] + - tree1.node_bounds[1, i_node1, j]) + d = (d1 + fabs(d1)) + (d2 + fabs(d2)) + + rdist += pow(0.5 * d, tree1.dist_metric.p) + + return rdist + + +cdef inline float64_t min_dist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """Compute the minimum distance between two nodes""" + return tree1.dist_metric._rdist_to_dist( + min_rdist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + + +cdef inline float64_t max_rdist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """Compute the maximum reduced distance between two nodes""" + cdef intp_t n_features = tree1.data.shape[1] + + cdef float64_t d1, d2, rdist=0.0 + cdef intp_t j + + if tree1.dist_metric.p == INF: + for j in range(n_features): + rdist = fmax(rdist, fabs(tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j])) + rdist = fmax(rdist, fabs(tree1.node_bounds[1, i_node1, j] + - tree2.node_bounds[0, i_node2, j])) + else: + for j in range(n_features): + d1 = fabs(tree1.node_bounds[0, i_node1, j] + - tree2.node_bounds[1, i_node2, j]) + d2 = fabs(tree1.node_bounds[1, i_node1, j] + - tree2.node_bounds[0, i_node2, j]) + rdist += pow(fmax(d1, d2), tree1.dist_metric.p) + + return rdist + + +cdef inline float64_t max_dist_dual{{name_suffix}}( + BinaryTree{{name_suffix}} tree1, + intp_t i_node1, + BinaryTree{{name_suffix}} tree2, + intp_t i_node2, +) except -1: + """Compute the maximum distance between two nodes""" + return tree1.dist_metric._rdist_to_dist( + max_rdist_dual{{name_suffix}}(tree1, i_node1, tree2, i_node2) + ) + +{{endfor}} + + +class KDTree(KDTree64): + __doc__ = CLASS_DOC.format(BinaryTree="KDTree") + pass diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kde.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kde.py new file mode 100644 index 0000000000000000000000000000000000000000..7661308db2e01665c82cf82985586006b7c39a56 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_kde.py @@ -0,0 +1,359 @@ +""" +Kernel Density Estimation +------------------------- +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import itertools +from numbers import Integral, Real + +import numpy as np +from scipy.special import gammainc + +from ..base import BaseEstimator, _fit_context +from ..neighbors._base import VALID_METRICS +from ..utils import check_random_state +from ..utils._param_validation import Interval, StrOptions +from ..utils.extmath import row_norms +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data +from ._ball_tree import BallTree +from ._kd_tree import KDTree + +VALID_KERNELS = [ + "gaussian", + "tophat", + "epanechnikov", + "exponential", + "linear", + "cosine", +] + +TREE_DICT = {"ball_tree": BallTree, "kd_tree": KDTree} + + +# TODO: implement a brute force version for testing purposes +# TODO: create a density estimation base class? +class KernelDensity(BaseEstimator): + """Kernel Density Estimation. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + bandwidth : float or {"scott", "silverman"}, default=1.0 + The bandwidth of the kernel. If bandwidth is a float, it defines the + bandwidth of the kernel. If bandwidth is a string, one of the estimation + methods is implemented. + + algorithm : {'kd_tree', 'ball_tree', 'auto'}, default='auto' + The tree algorithm to use. + + kernel : {'gaussian', 'tophat', 'epanechnikov', 'exponential', 'linear', \ + 'cosine'}, default='gaussian' + The kernel to use. + + metric : str, default='euclidean' + Metric to use for distance computation. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + Not all metrics are valid with all algorithms: refer to the + documentation of :class:`BallTree` and :class:`KDTree`. Note that the + normalization of the density output is correct only for the Euclidean + distance metric. + + atol : float, default=0 + The desired absolute tolerance of the result. A larger tolerance will + generally lead to faster execution. + + rtol : float, default=0 + The desired relative tolerance of the result. A larger tolerance will + generally lead to faster execution. + + breadth_first : bool, default=True + If true (default), use a breadth-first approach to the problem. + Otherwise use a depth-first approach. + + leaf_size : int, default=40 + Specify the leaf size of the underlying tree. See :class:`BallTree` + or :class:`KDTree` for details. + + metric_params : dict, default=None + Additional parameters to be passed to the tree for use with the + metric. For more information, see the documentation of + :class:`BallTree` or :class:`KDTree`. + + Attributes + ---------- + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + tree_ : ``BinaryTree`` instance + The tree algorithm for fast generalized N-point problems. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + bandwidth_ : float + Value of the bandwidth, given directly by the bandwidth parameter or + estimated using the 'scott' or 'silverman' method. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.neighbors.KDTree : K-dimensional tree for fast generalized N-point + problems. + sklearn.neighbors.BallTree : Ball tree for fast generalized N-point + problems. + + Examples + -------- + Compute a gaussian kernel density estimate with a fixed bandwidth. + + >>> from sklearn.neighbors import KernelDensity + >>> import numpy as np + >>> rng = np.random.RandomState(42) + >>> X = rng.random_sample((100, 3)) + >>> kde = KernelDensity(kernel='gaussian', bandwidth=0.5).fit(X) + >>> log_density = kde.score_samples(X[:3]) + >>> log_density + array([-1.52955942, -1.51462041, -1.60244657]) + """ + + _parameter_constraints: dict = { + "bandwidth": [ + Interval(Real, 0, None, closed="neither"), + StrOptions({"scott", "silverman"}), + ], + "algorithm": [StrOptions(set(TREE_DICT.keys()) | {"auto"})], + "kernel": [StrOptions(set(VALID_KERNELS))], + "metric": [ + StrOptions( + set(itertools.chain(*[VALID_METRICS[alg] for alg in TREE_DICT.keys()])) + ) + ], + "atol": [Interval(Real, 0, None, closed="left")], + "rtol": [Interval(Real, 0, None, closed="left")], + "breadth_first": ["boolean"], + "leaf_size": [Interval(Integral, 1, None, closed="left")], + "metric_params": [None, dict], + } + + def __init__( + self, + *, + bandwidth=1.0, + algorithm="auto", + kernel="gaussian", + metric="euclidean", + atol=0, + rtol=0, + breadth_first=True, + leaf_size=40, + metric_params=None, + ): + self.algorithm = algorithm + self.bandwidth = bandwidth + self.kernel = kernel + self.metric = metric + self.atol = atol + self.rtol = rtol + self.breadth_first = breadth_first + self.leaf_size = leaf_size + self.metric_params = metric_params + + def _choose_algorithm(self, algorithm, metric): + # given the algorithm string + metric string, choose the optimal + # algorithm to compute the result. + if algorithm == "auto": + # use KD Tree if possible + if metric in KDTree.valid_metrics: + return "kd_tree" + elif metric in BallTree.valid_metrics: + return "ball_tree" + else: # kd_tree or ball_tree + if metric not in TREE_DICT[algorithm].valid_metrics: + raise ValueError( + "invalid metric for {0}: '{1}'".format(TREE_DICT[algorithm], metric) + ) + return algorithm + + @_fit_context( + # KernelDensity.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None, sample_weight=None): + """Fit the Kernel Density model on the data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + y : None + Ignored. This parameter exists only for compatibility with + :class:`~sklearn.pipeline.Pipeline`. + + sample_weight : array-like of shape (n_samples,), default=None + List of sample weights attached to the data X. + + .. versionadded:: 0.20 + + Returns + ------- + self : object + Returns the instance itself. + """ + algorithm = self._choose_algorithm(self.algorithm, self.metric) + + if isinstance(self.bandwidth, str): + if self.bandwidth == "scott": + self.bandwidth_ = X.shape[0] ** (-1 / (X.shape[1] + 4)) + elif self.bandwidth == "silverman": + self.bandwidth_ = (X.shape[0] * (X.shape[1] + 2) / 4) ** ( + -1 / (X.shape[1] + 4) + ) + else: + self.bandwidth_ = self.bandwidth + + X = validate_data(self, X, order="C", dtype=np.float64) + + if sample_weight is not None: + sample_weight = _check_sample_weight( + sample_weight, X, dtype=np.float64, ensure_non_negative=True + ) + + kwargs = self.metric_params + if kwargs is None: + kwargs = {} + self.tree_ = TREE_DICT[algorithm]( + X, + metric=self.metric, + leaf_size=self.leaf_size, + sample_weight=sample_weight, + **kwargs, + ) + return self + + def score_samples(self, X): + """Compute the log-likelihood of each sample under the model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + An array of points to query. Last dimension should match dimension + of training data (n_features). + + Returns + ------- + density : ndarray of shape (n_samples,) + Log-likelihood of each sample in `X`. These are normalized to be + probability densities, so values will be low for high-dimensional + data. + """ + check_is_fitted(self) + # The returned density is normalized to the number of points. + # For it to be a probability, we must scale it. For this reason + # we'll also scale atol. + X = validate_data(self, X, order="C", dtype=np.float64, reset=False) + if self.tree_.sample_weight is None: + N = self.tree_.data.shape[0] + else: + N = self.tree_.sum_weight + atol_N = self.atol * N + log_density = self.tree_.kernel_density( + X, + h=self.bandwidth_, + kernel=self.kernel, + atol=atol_N, + rtol=self.rtol, + breadth_first=self.breadth_first, + return_log=True, + ) + log_density -= np.log(N) + return log_density + + def score(self, X, y=None): + """Compute the total log-likelihood under the model. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + List of n_features-dimensional data points. Each row + corresponds to a single data point. + + y : None + Ignored. This parameter exists only for compatibility with + :class:`~sklearn.pipeline.Pipeline`. + + Returns + ------- + logprob : float + Total log-likelihood of the data in X. This is normalized to be a + probability density, so the value will be low for high-dimensional + data. + """ + return np.sum(self.score_samples(X)) + + def sample(self, n_samples=1, random_state=None): + """Generate random samples from the model. + + Currently, this is implemented only for gaussian and tophat kernels. + + Parameters + ---------- + n_samples : int, default=1 + Number of samples to generate. + + random_state : int, RandomState instance or None, default=None + Determines random number generation used to generate + random samples. Pass an int for reproducible results + across multiple function calls. + See :term:`Glossary `. + + Returns + ------- + X : array-like of shape (n_samples, n_features) + List of samples. + """ + check_is_fitted(self) + # TODO: implement sampling for other valid kernel shapes + if self.kernel not in ["gaussian", "tophat"]: + raise NotImplementedError() + + data = np.asarray(self.tree_.data) + + rng = check_random_state(random_state) + u = rng.uniform(0, 1, size=n_samples) + if self.tree_.sample_weight is None: + i = (u * data.shape[0]).astype(np.int64) + else: + cumsum_weight = np.cumsum(np.asarray(self.tree_.sample_weight)) + sum_weight = cumsum_weight[-1] + i = np.searchsorted(cumsum_weight, u * sum_weight) + if self.kernel == "gaussian": + return np.atleast_2d(rng.normal(data[i], self.bandwidth_)) + + elif self.kernel == "tophat": + # we first draw points from a d-dimensional normal distribution, + # then use an incomplete gamma function to map them to a uniform + # d-dimensional tophat distribution. + dim = data.shape[1] + X = rng.normal(size=(n_samples, dim)) + s_sq = row_norms(X, squared=True) + correction = ( + gammainc(0.5 * dim, 0.5 * s_sq) ** (1.0 / dim) + * self.bandwidth_ + / np.sqrt(s_sq) + ) + return data[i] + X * correction[:, np.newaxis] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_lof.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_lof.py new file mode 100644 index 0000000000000000000000000000000000000000..d9f00be42570e2841e5445b5fd68e1dec5413c6a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_lof.py @@ -0,0 +1,518 @@ +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np + +from ..base import OutlierMixin, _fit_context +from ..utils import check_array +from ..utils._param_validation import Interval, StrOptions +from ..utils.metaestimators import available_if +from ..utils.validation import check_is_fitted +from ._base import KNeighborsMixin, NeighborsBase + +__all__ = ["LocalOutlierFactor"] + + +class LocalOutlierFactor(KNeighborsMixin, OutlierMixin, NeighborsBase): + """Unsupervised Outlier Detection using the Local Outlier Factor (LOF). + + The anomaly score of each sample is called the Local Outlier Factor. + It measures the local deviation of the density of a given sample with respect + to its neighbors. + It is local in that the anomaly score depends on how isolated the object + is with respect to the surrounding neighborhood. + More precisely, locality is given by k-nearest neighbors, whose distance + is used to estimate the local density. + By comparing the local density of a sample to the local densities of its + neighbors, one can identify samples that have a substantially lower density + than their neighbors. These are considered outliers. + + .. versionadded:: 0.19 + + Parameters + ---------- + n_neighbors : int, default=20 + Number of neighbors to use by default for :meth:`kneighbors` queries. + If n_neighbors is larger than the number of samples provided, + all samples will be used. + + algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute'}, default='auto' + Algorithm used to compute the nearest neighbors: + + - 'ball_tree' will use :class:`BallTree` + - 'kd_tree' will use :class:`KDTree` + - 'brute' will use a brute-force search. + - 'auto' will attempt to decide the most appropriate algorithm + based on the values passed to :meth:`fit` method. + + Note: fitting on sparse input will override the setting of + this parameter, using brute force. + + leaf_size : int, default=30 + Leaf is size passed to :class:`BallTree` or :class:`KDTree`. This can + affect the speed of the construction and query, as well as the memory + required to store the tree. The optimal value depends on the + nature of the problem. + + metric : str or callable, default='minkowski' + Metric to use for distance computation. Default is "minkowski", which + results in the standard Euclidean distance when p = 2. See the + documentation of `scipy.spatial.distance + `_ and + the metrics listed in + :class:`~sklearn.metrics.pairwise.distance_metrics` for valid metric + values. + + If metric is "precomputed", X is assumed to be a distance matrix and + must be square during fit. X may be a :term:`sparse graph`, in which + case only "nonzero" elements may be considered neighbors. + + If metric is a callable function, it takes two arrays representing 1D + vectors as inputs and must return one value indicating the distance + between those vectors. This works for Scipy's metrics, but is less + efficient than passing the metric name as a string. + + p : float, default=2 + Parameter for the Minkowski metric from + :func:`sklearn.metrics.pairwise_distances`. When p = 1, this + is equivalent to using manhattan_distance (l1), and euclidean_distance + (l2) for p = 2. For arbitrary p, minkowski_distance (l_p) is used. + + metric_params : dict, default=None + Additional keyword arguments for the metric function. + + contamination : 'auto' or float, default='auto' + The amount of contamination of the data set, i.e. the proportion + of outliers in the data set. When fitting this is used to define the + threshold on the scores of the samples. + + - if 'auto', the threshold is determined as in the + original paper, + - if a float, the contamination should be in the range (0, 0.5]. + + .. versionchanged:: 0.22 + The default value of ``contamination`` changed from 0.1 + to ``'auto'``. + + novelty : bool, default=False + By default, LocalOutlierFactor is only meant to be used for outlier + detection (novelty=False). Set novelty to True if you want to use + LocalOutlierFactor for novelty detection. In this case be aware that + you should only use predict, decision_function and score_samples + on new unseen data and not on the training set; and note that the + results obtained this way may differ from the standard LOF results. + + .. versionadded:: 0.20 + + n_jobs : int, default=None + The number of parallel jobs to run for neighbors search. + ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. + ``-1`` means using all processors. See :term:`Glossary ` + for more details. + + Attributes + ---------- + negative_outlier_factor_ : ndarray of shape (n_samples,) + The opposite LOF of the training samples. The higher, the more normal. + Inliers tend to have a LOF score close to 1 + (``negative_outlier_factor_`` close to -1), while outliers tend to have + a larger LOF score. + + The local outlier factor (LOF) of a sample captures its + supposed 'degree of abnormality'. + It is the average of the ratio of the local reachability density of + a sample and those of its k-nearest neighbors. + + n_neighbors_ : int + The actual number of neighbors used for :meth:`kneighbors` queries. + + offset_ : float + Offset used to obtain binary labels from the raw scores. + Observations having a negative_outlier_factor smaller than `offset_` + are detected as abnormal. + The offset is set to -1.5 (inliers score around -1), except when a + contamination parameter different than "auto" is provided. In that + case, the offset is defined in such a way we obtain the expected + number of outliers in training. + + .. versionadded:: 0.20 + + effective_metric_ : str + The effective metric used for the distance computation. + + effective_metric_params_ : dict + The effective additional keyword arguments for the metric function. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_samples_fit_ : int + It is the number of samples in the fitted data. + + See Also + -------- + sklearn.svm.OneClassSVM: Unsupervised Outlier Detection using + Support Vector Machine. + + References + ---------- + .. [1] Breunig, M. M., Kriegel, H. P., Ng, R. T., & Sander, J. (2000, May). + LOF: identifying density-based local outliers. In ACM sigmod record. + + Examples + -------- + >>> import numpy as np + >>> from sklearn.neighbors import LocalOutlierFactor + >>> X = [[-1.1], [0.2], [101.1], [0.3]] + >>> clf = LocalOutlierFactor(n_neighbors=2) + >>> clf.fit_predict(X) + array([ 1, 1, -1, 1]) + >>> clf.negative_outlier_factor_ + array([ -0.9821, -1.0370, -73.3697, -0.9821]) + """ + + _parameter_constraints: dict = { + **NeighborsBase._parameter_constraints, + "contamination": [ + StrOptions({"auto"}), + Interval(Real, 0, 0.5, closed="right"), + ], + "novelty": ["boolean"], + } + _parameter_constraints.pop("radius") + + def __init__( + self, + n_neighbors=20, + *, + algorithm="auto", + leaf_size=30, + metric="minkowski", + p=2, + metric_params=None, + contamination="auto", + novelty=False, + n_jobs=None, + ): + super().__init__( + n_neighbors=n_neighbors, + algorithm=algorithm, + leaf_size=leaf_size, + metric=metric, + p=p, + metric_params=metric_params, + n_jobs=n_jobs, + ) + self.contamination = contamination + self.novelty = novelty + + def _check_novelty_fit_predict(self): + if self.novelty: + msg = ( + "fit_predict is not available when novelty=True. Use " + "novelty=False if you want to predict on the training set." + ) + raise AttributeError(msg) + return True + + @available_if(_check_novelty_fit_predict) + def fit_predict(self, X, y=None): + """Fit the model to the training set X and return the labels. + + **Not available for novelty detection (when novelty is set to True).** + Label is 1 for an inlier and -1 for an outlier according to the LOF + score and the contamination parameter. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None + The query sample or samples to compute the Local Outlier Factor + w.r.t. the training samples. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + is_inlier : ndarray of shape (n_samples,) + Returns -1 for anomalies/outliers and 1 for inliers. + """ + + # As fit_predict would be different from fit.predict, fit_predict is + # only available for outlier detection (novelty=False) + + return self.fit(X)._predict() + + @_fit_context( + # LocalOutlierFactor.metric is not validated yet + prefer_skip_nested_validation=False + ) + def fit(self, X, y=None): + """Fit the local outlier factor detector from the training dataset. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) or \ + (n_samples, n_samples) if metric='precomputed' + Training data. + + y : Ignored + Not used, present for API consistency by convention. + + Returns + ------- + self : LocalOutlierFactor + The fitted local outlier factor detector. + """ + self._fit(X) + + n_samples = self.n_samples_fit_ + if self.n_neighbors > n_samples: + warnings.warn( + "n_neighbors (%s) is greater than the " + "total number of samples (%s). n_neighbors " + "will be set to (n_samples - 1) for estimation." + % (self.n_neighbors, n_samples) + ) + self.n_neighbors_ = max(1, min(self.n_neighbors, n_samples - 1)) + + self._distances_fit_X_, _neighbors_indices_fit_X_ = self.kneighbors( + n_neighbors=self.n_neighbors_ + ) + + if self._fit_X.dtype == np.float32: + self._distances_fit_X_ = self._distances_fit_X_.astype( + self._fit_X.dtype, + copy=False, + ) + + self._lrd = self._local_reachability_density( + self._distances_fit_X_, _neighbors_indices_fit_X_ + ) + + # Compute lof score over training samples to define offset_: + lrd_ratios_array = ( + self._lrd[_neighbors_indices_fit_X_] / self._lrd[:, np.newaxis] + ) + + self.negative_outlier_factor_ = -np.mean(lrd_ratios_array, axis=1) + + if self.contamination == "auto": + # inliers score around -1 (the higher, the less abnormal). + self.offset_ = -1.5 + else: + self.offset_ = np.percentile( + self.negative_outlier_factor_, 100.0 * self.contamination + ) + + # Verify if negative_outlier_factor_ values are within acceptable range. + # Novelty must also be false to detect outliers + if np.min(self.negative_outlier_factor_) < -1e7 and not self.novelty: + warnings.warn( + "Duplicate values are leading to incorrect results. " + "Increase the number of neighbors for more accurate results." + ) + + return self + + def _check_novelty_predict(self): + if not self.novelty: + msg = ( + "predict is not available when novelty=False, use " + "fit_predict if you want to predict on training data. Use " + "novelty=True if you want to use LOF for novelty detection " + "and predict on new unseen data." + ) + raise AttributeError(msg) + return True + + @available_if(_check_novelty_predict) + def predict(self, X=None): + """Predict the labels (1 inlier, -1 outlier) of X according to LOF. + + **Only available for novelty detection (when novelty is set to True).** + This method allows to generalize prediction to *new observations* (not + in the training set). Note that the result of ``clf.fit(X)`` then + ``clf.predict(X)`` with ``novelty=True`` may differ from the result + obtained by ``clf.fit_predict(X)`` with ``novelty=False``. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The query sample or samples to compute the Local Outlier Factor + w.r.t. the training samples. + + Returns + ------- + is_inlier : ndarray of shape (n_samples,) + Returns -1 for anomalies/outliers and +1 for inliers. + """ + return self._predict(X) + + def _predict(self, X=None): + """Predict the labels (1 inlier, -1 outlier) of X according to LOF. + + If X is None, returns the same as fit_predict(X_train). + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features), default=None + The query sample or samples to compute the Local Outlier Factor + w.r.t. the training samples. If None, makes prediction on the + training data without considering them as their own neighbors. + + Returns + ------- + is_inlier : ndarray of shape (n_samples,) + Returns -1 for anomalies/outliers and +1 for inliers. + """ + check_is_fitted(self) + + if X is not None: + shifted_opposite_lof_scores = self.decision_function(X) + is_inlier = np.ones(shifted_opposite_lof_scores.shape[0], dtype=int) + is_inlier[shifted_opposite_lof_scores < 0] = -1 + else: + is_inlier = np.ones(self.n_samples_fit_, dtype=int) + is_inlier[self.negative_outlier_factor_ < self.offset_] = -1 + + return is_inlier + + def _check_novelty_decision_function(self): + if not self.novelty: + msg = ( + "decision_function is not available when novelty=False. " + "Use novelty=True if you want to use LOF for novelty " + "detection and compute decision_function for new unseen " + "data. Note that the opposite LOF of the training samples " + "is always available by considering the " + "negative_outlier_factor_ attribute." + ) + raise AttributeError(msg) + return True + + @available_if(_check_novelty_decision_function) + def decision_function(self, X): + """Shifted opposite of the Local Outlier Factor of X. + + Bigger is better, i.e. large values correspond to inliers. + + **Only available for novelty detection (when novelty is set to True).** + The shift offset allows a zero threshold for being an outlier. + The argument X is supposed to contain *new data*: if X contains a + point from training, it considers the later in its own neighborhood. + Also, the samples in X are not considered in the neighborhood of any + point. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The query sample or samples to compute the Local Outlier Factor + w.r.t. the training samples. + + Returns + ------- + shifted_opposite_lof_scores : ndarray of shape (n_samples,) + The shifted opposite of the Local Outlier Factor of each input + samples. The lower, the more abnormal. Negative scores represent + outliers, positive scores represent inliers. + """ + return self.score_samples(X) - self.offset_ + + def _check_novelty_score_samples(self): + if not self.novelty: + msg = ( + "score_samples is not available when novelty=False. The " + "scores of the training samples are always available " + "through the negative_outlier_factor_ attribute. Use " + "novelty=True if you want to use LOF for novelty detection " + "and compute score_samples for new unseen data." + ) + raise AttributeError(msg) + return True + + @available_if(_check_novelty_score_samples) + def score_samples(self, X): + """Opposite of the Local Outlier Factor of X. + + It is the opposite as bigger is better, i.e. large values correspond + to inliers. + + **Only available for novelty detection (when novelty is set to True).** + The argument X is supposed to contain *new data*: if X contains a + point from training, it considers the later in its own neighborhood. + Also, the samples in X are not considered in the neighborhood of any + point. Because of this, the scores obtained via ``score_samples`` may + differ from the standard LOF scores. + The standard LOF scores for the training data is available via the + ``negative_outlier_factor_`` attribute. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The query sample or samples to compute the Local Outlier Factor + w.r.t. the training samples. + + Returns + ------- + opposite_lof_scores : ndarray of shape (n_samples,) + The opposite of the Local Outlier Factor of each input samples. + The lower, the more abnormal. + """ + check_is_fitted(self) + X = check_array(X, accept_sparse="csr") + + distances_X, neighbors_indices_X = self.kneighbors( + X, n_neighbors=self.n_neighbors_ + ) + + if X.dtype == np.float32: + distances_X = distances_X.astype(X.dtype, copy=False) + + X_lrd = self._local_reachability_density( + distances_X, + neighbors_indices_X, + ) + + lrd_ratios_array = self._lrd[neighbors_indices_X] / X_lrd[:, np.newaxis] + + # as bigger is better: + return -np.mean(lrd_ratios_array, axis=1) + + def _local_reachability_density(self, distances_X, neighbors_indices): + """The local reachability density (LRD) + + The LRD of a sample is the inverse of the average reachability + distance of its k-nearest neighbors. + + Parameters + ---------- + distances_X : ndarray of shape (n_queries, self.n_neighbors) + Distances to the neighbors (in the training samples `self._fit_X`) + of each query point to compute the LRD. + + neighbors_indices : ndarray of shape (n_queries, self.n_neighbors) + Neighbors indices (of each query point) among training samples + self._fit_X. + + Returns + ------- + local_reachability_density : ndarray of shape (n_queries,) + The local reachability density of each sample. + """ + dist_k = self._distances_fit_X_[neighbors_indices, self.n_neighbors_ - 1] + reach_dist_array = np.maximum(distances_X, dist_k) + + # 1e-10 to avoid `nan' when nb of duplicates > n_neighbors_: + return 1.0 / (np.mean(reach_dist_array, axis=1) + 1e-10) diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nca.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nca.py new file mode 100644 index 0000000000000000000000000000000000000000..8383f95338932cd4a5a88fda6e5e5b9211b9ca0a --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nca.py @@ -0,0 +1,534 @@ +""" +Neighborhood Component Analysis +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import sys +import time +from numbers import Integral, Real +from warnings import warn + +import numpy as np +from scipy.optimize import minimize + +from ..base import ( + BaseEstimator, + ClassNamePrefixFeaturesOutMixin, + TransformerMixin, + _fit_context, +) +from ..decomposition import PCA +from ..exceptions import ConvergenceWarning +from ..metrics import pairwise_distances +from ..preprocessing import LabelEncoder +from ..utils._param_validation import Interval, StrOptions +from ..utils.extmath import softmax +from ..utils.fixes import _get_additional_lbfgs_options_dict +from ..utils.multiclass import check_classification_targets +from ..utils.random import check_random_state +from ..utils.validation import check_array, check_is_fitted, validate_data + + +class NeighborhoodComponentsAnalysis( + ClassNamePrefixFeaturesOutMixin, TransformerMixin, BaseEstimator +): + """Neighborhood Components Analysis. + + Neighborhood Component Analysis (NCA) is a machine learning algorithm for + metric learning. It learns a linear transformation in a supervised fashion + to improve the classification accuracy of a stochastic nearest neighbors + rule in the transformed space. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + n_components : int, default=None + Preferred dimensionality of the projected space. + If None it will be set to `n_features`. + + init : {'auto', 'pca', 'lda', 'identity', 'random'} or ndarray of shape \ + (n_features_a, n_features_b), default='auto' + Initialization of the linear transformation. Possible options are + `'auto'`, `'pca'`, `'lda'`, `'identity'`, `'random'`, and a numpy + array of shape `(n_features_a, n_features_b)`. + + - `'auto'` + Depending on `n_components`, the most reasonable initialization + is chosen. If `n_components <= min(n_features, n_classes - 1)` + we use `'lda'`, as it uses labels information. If not, but + `n_components < min(n_features, n_samples)`, we use `'pca'`, as + it projects data in meaningful directions (those of higher + variance). Otherwise, we just use `'identity'`. + + - `'pca'` + `n_components` principal components of the inputs passed + to :meth:`fit` will be used to initialize the transformation. + (See :class:`~sklearn.decomposition.PCA`) + + - `'lda'` + `min(n_components, n_classes)` most discriminative + components of the inputs passed to :meth:`fit` will be used to + initialize the transformation. (If `n_components > n_classes`, + the rest of the components will be zero.) (See + :class:`~sklearn.discriminant_analysis.LinearDiscriminantAnalysis`) + + - `'identity'` + If `n_components` is strictly smaller than the + dimensionality of the inputs passed to :meth:`fit`, the identity + matrix will be truncated to the first `n_components` rows. + + - `'random'` + The initial transformation will be a random array of shape + `(n_components, n_features)`. Each value is sampled from the + standard normal distribution. + + - numpy array + `n_features_b` must match the dimensionality of the inputs passed + to :meth:`fit` and n_features_a must be less than or equal to that. + If `n_components` is not `None`, `n_features_a` must match it. + + warm_start : bool, default=False + If `True` and :meth:`fit` has been called before, the solution of the + previous call to :meth:`fit` is used as the initial linear + transformation (`n_components` and `init` will be ignored). + + max_iter : int, default=50 + Maximum number of iterations in the optimization. + + tol : float, default=1e-5 + Convergence tolerance for the optimization. + + callback : callable, default=None + If not `None`, this function is called after every iteration of the + optimizer, taking as arguments the current solution (flattened + transformation matrix) and the number of iterations. This might be + useful in case one wants to examine or store the transformation + found after each iteration. + + verbose : int, default=0 + If 0, no progress messages will be printed. + If 1, progress messages will be printed to stdout. + If > 1, progress messages will be printed and the `disp` + parameter of :func:`scipy.optimize.minimize` will be set to + `verbose - 2`. + + random_state : int or numpy.RandomState, default=None + A pseudo random number generator object or a seed for it if int. If + `init='random'`, `random_state` is used to initialize the random + transformation. If `init='pca'`, `random_state` is passed as an + argument to PCA when initializing the transformation. Pass an int + for reproducible results across multiple function calls. + See :term:`Glossary `. + + Attributes + ---------- + components_ : ndarray of shape (n_components, n_features) + The linear transformation learned during fitting. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + n_iter_ : int + Counts the number of iterations performed by the optimizer. + + random_state_ : numpy.RandomState + Pseudo random number generator object used during initialization. + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + See Also + -------- + sklearn.discriminant_analysis.LinearDiscriminantAnalysis : Linear + Discriminant Analysis. + sklearn.decomposition.PCA : Principal component analysis (PCA). + + References + ---------- + .. [1] J. Goldberger, G. Hinton, S. Roweis, R. Salakhutdinov. + "Neighbourhood Components Analysis". Advances in Neural Information + Processing Systems. 17, 513-520, 2005. + http://www.cs.nyu.edu/~roweis/papers/ncanips.pdf + + .. [2] Wikipedia entry on Neighborhood Components Analysis + https://en.wikipedia.org/wiki/Neighbourhood_components_analysis + + Examples + -------- + >>> from sklearn.neighbors import NeighborhoodComponentsAnalysis + >>> from sklearn.neighbors import KNeighborsClassifier + >>> from sklearn.datasets import load_iris + >>> from sklearn.model_selection import train_test_split + >>> X, y = load_iris(return_X_y=True) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... stratify=y, test_size=0.7, random_state=42) + >>> nca = NeighborhoodComponentsAnalysis(random_state=42) + >>> nca.fit(X_train, y_train) + NeighborhoodComponentsAnalysis(...) + >>> knn = KNeighborsClassifier(n_neighbors=3) + >>> knn.fit(X_train, y_train) + KNeighborsClassifier(...) + >>> print(knn.score(X_test, y_test)) + 0.933333... + >>> knn.fit(nca.transform(X_train), y_train) + KNeighborsClassifier(...) + >>> print(knn.score(nca.transform(X_test), y_test)) + 0.961904... + """ + + _parameter_constraints: dict = { + "n_components": [ + Interval(Integral, 1, None, closed="left"), + None, + ], + "init": [ + StrOptions({"auto", "pca", "lda", "identity", "random"}), + np.ndarray, + ], + "warm_start": ["boolean"], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "tol": [Interval(Real, 0, None, closed="left")], + "callback": [callable, None], + "verbose": ["verbose"], + "random_state": ["random_state"], + } + + def __init__( + self, + n_components=None, + *, + init="auto", + warm_start=False, + max_iter=50, + tol=1e-5, + callback=None, + verbose=0, + random_state=None, + ): + self.n_components = n_components + self.init = init + self.warm_start = warm_start + self.max_iter = max_iter + self.tol = tol + self.callback = callback + self.verbose = verbose + self.random_state = random_state + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """Fit the model according to the given training data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training samples. + + y : array-like of shape (n_samples,) + The corresponding training labels. + + Returns + ------- + self : object + Fitted estimator. + """ + # Validate the inputs X and y, and converts y to numerical classes. + X, y = validate_data(self, X, y, ensure_min_samples=2) + check_classification_targets(y) + y = LabelEncoder().fit_transform(y) + + # Check the preferred dimensionality of the projected space + if self.n_components is not None and self.n_components > X.shape[1]: + raise ValueError( + "The preferred dimensionality of the " + f"projected space `n_components` ({self.n_components}) cannot " + "be greater than the given data " + f"dimensionality ({X.shape[1]})!" + ) + # If warm_start is enabled, check that the inputs are consistent + if ( + self.warm_start + and hasattr(self, "components_") + and self.components_.shape[1] != X.shape[1] + ): + raise ValueError( + f"The new inputs dimensionality ({X.shape[1]}) does not " + "match the input dimensionality of the " + f"previously learned transformation ({self.components_.shape[1]})." + ) + # Check how the linear transformation should be initialized + init = self.init + if isinstance(init, np.ndarray): + init = check_array(init) + # Assert that init.shape[1] = X.shape[1] + if init.shape[1] != X.shape[1]: + raise ValueError( + f"The input dimensionality ({init.shape[1]}) of the given " + "linear transformation `init` must match the " + f"dimensionality of the given inputs `X` ({X.shape[1]})." + ) + # Assert that init.shape[0] <= init.shape[1] + if init.shape[0] > init.shape[1]: + raise ValueError( + f"The output dimensionality ({init.shape[0]}) of the given " + "linear transformation `init` cannot be " + f"greater than its input dimensionality ({init.shape[1]})." + ) + # Assert that self.n_components = init.shape[0] + if self.n_components is not None and self.n_components != init.shape[0]: + raise ValueError( + "The preferred dimensionality of the " + f"projected space `n_components` ({self.n_components}) does" + " not match the output dimensionality of " + "the given linear transformation " + f"`init` ({init.shape[0]})!" + ) + + # Initialize the random generator + self.random_state_ = check_random_state(self.random_state) + + # Measure the total training time + t_train = time.time() + + # Compute a mask that stays fixed during optimization: + same_class_mask = y[:, np.newaxis] == y[np.newaxis, :] + # (n_samples, n_samples) + + # Initialize the transformation + transformation = np.ravel(self._initialize(X, y, init)) + + # Create a dictionary of parameters to be passed to the optimizer + disp = self.verbose - 2 if self.verbose > 1 else -1 + optimizer_params = { + "method": "L-BFGS-B", + "fun": self._loss_grad_lbfgs, + "args": (X, same_class_mask, -1.0), + "jac": True, + "x0": transformation, + "tol": self.tol, + "options": dict( + maxiter=self.max_iter, + **_get_additional_lbfgs_options_dict("disp", disp), + ), + "callback": self._callback, + } + + # Call the optimizer + self.n_iter_ = 0 + opt_result = minimize(**optimizer_params) + + # Reshape the solution found by the optimizer + self.components_ = opt_result.x.reshape(-1, X.shape[1]) + + # Stop timer + t_train = time.time() - t_train + if self.verbose: + cls_name = self.__class__.__name__ + + # Warn the user if the algorithm did not converge + if not opt_result.success: + warn( + "[{}] NCA did not converge: {}".format( + cls_name, opt_result.message + ), + ConvergenceWarning, + ) + + print("[{}] Training took {:8.2f}s.".format(cls_name, t_train)) + + return self + + def transform(self, X): + """Apply the learned transformation to the given data. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + Data samples. + + Returns + ------- + X_embedded: ndarray of shape (n_samples, n_components) + The data samples transformed. + + Raises + ------ + NotFittedError + If :meth:`fit` has not been called before. + """ + + check_is_fitted(self) + X = validate_data(self, X, reset=False) + + return np.dot(X, self.components_.T) + + def _initialize(self, X, y, init): + """Initialize the transformation. + + Parameters + ---------- + X : array-like of shape (n_samples, n_features) + The training samples. + + y : array-like of shape (n_samples,) + The training labels. + + init : str or ndarray of shape (n_features_a, n_features_b) + The validated initialization of the linear transformation. + + Returns + ------- + transformation : ndarray of shape (n_components, n_features) + The initialized linear transformation. + + """ + + transformation = init + if self.warm_start and hasattr(self, "components_"): + transformation = self.components_ + elif isinstance(init, np.ndarray): + pass + else: + n_samples, n_features = X.shape + n_components = self.n_components or n_features + if init == "auto": + n_classes = len(np.unique(y)) + if n_components <= min(n_features, n_classes - 1): + init = "lda" + elif n_components < min(n_features, n_samples): + init = "pca" + else: + init = "identity" + if init == "identity": + transformation = np.eye(n_components, X.shape[1]) + elif init == "random": + transformation = self.random_state_.standard_normal( + size=(n_components, X.shape[1]) + ) + elif init in {"pca", "lda"}: + init_time = time.time() + if init == "pca": + pca = PCA( + n_components=n_components, random_state=self.random_state_ + ) + if self.verbose: + print("Finding principal components... ", end="") + sys.stdout.flush() + pca.fit(X) + transformation = pca.components_ + elif init == "lda": + from ..discriminant_analysis import LinearDiscriminantAnalysis + + lda = LinearDiscriminantAnalysis(n_components=n_components) + if self.verbose: + print("Finding most discriminative components... ", end="") + sys.stdout.flush() + lda.fit(X, y) + transformation = lda.scalings_.T[:n_components] + if self.verbose: + print("done in {:5.2f}s".format(time.time() - init_time)) + return transformation + + def _callback(self, transformation): + """Called after each iteration of the optimizer. + + Parameters + ---------- + transformation : ndarray of shape (n_components * n_features,) + The solution computed by the optimizer in this iteration. + """ + if self.callback is not None: + self.callback(transformation, self.n_iter_) + + self.n_iter_ += 1 + + def _loss_grad_lbfgs(self, transformation, X, same_class_mask, sign=1.0): + """Compute the loss and the loss gradient w.r.t. `transformation`. + + Parameters + ---------- + transformation : ndarray of shape (n_components * n_features,) + The raveled linear transformation on which to compute loss and + evaluate gradient. + + X : ndarray of shape (n_samples, n_features) + The training samples. + + same_class_mask : ndarray of shape (n_samples, n_samples) + A mask where `mask[i, j] == 1` if `X[i]` and `X[j]` belong + to the same class, and `0` otherwise. + + Returns + ------- + loss : float + The loss computed for the given transformation. + + gradient : ndarray of shape (n_components * n_features,) + The new (flattened) gradient of the loss. + """ + + if self.n_iter_ == 0: + self.n_iter_ += 1 + if self.verbose: + header_fields = ["Iteration", "Objective Value", "Time(s)"] + header_fmt = "{:>10} {:>20} {:>10}" + header = header_fmt.format(*header_fields) + cls_name = self.__class__.__name__ + print("[{}]".format(cls_name)) + print( + "[{}] {}\n[{}] {}".format( + cls_name, header, cls_name, "-" * len(header) + ) + ) + + t_funcall = time.time() + + transformation = transformation.reshape(-1, X.shape[1]) + X_embedded = np.dot(X, transformation.T) # (n_samples, n_components) + + # Compute softmax distances + p_ij = pairwise_distances(X_embedded, squared=True) + np.fill_diagonal(p_ij, np.inf) + p_ij = softmax(-p_ij) # (n_samples, n_samples) + + # Compute loss + masked_p_ij = p_ij * same_class_mask + p = np.sum(masked_p_ij, axis=1, keepdims=True) # (n_samples, 1) + loss = np.sum(p) + + # Compute gradient of loss w.r.t. `transform` + weighted_p_ij = masked_p_ij - p_ij * p + weighted_p_ij_sym = weighted_p_ij + weighted_p_ij.T + np.fill_diagonal(weighted_p_ij_sym, -weighted_p_ij.sum(axis=0)) + gradient = 2 * X_embedded.T.dot(weighted_p_ij_sym).dot(X) + # time complexity of the gradient: O(n_components x n_samples x ( + # n_samples + n_features)) + + if self.verbose: + t_funcall = time.time() - t_funcall + values_fmt = "[{}] {:>10} {:>20.6e} {:>10.2f}" + print( + values_fmt.format( + self.__class__.__name__, self.n_iter_, loss, t_funcall + ) + ) + sys.stdout.flush() + + return sign * loss, sign * gradient.ravel() + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.target_tags.required = True + return tags + + @property + def _n_features_out(self): + """Number of transformed output features.""" + return self.components_.shape[0] diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py new file mode 100644 index 0000000000000000000000000000000000000000..a780c27587792478fcef0965127310d35238040d --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_nearest_centroid.py @@ -0,0 +1,359 @@ +""" +Nearest Centroid Classification +""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from numbers import Real + +import numpy as np +from scipy import sparse as sp + +from ..base import BaseEstimator, ClassifierMixin, _fit_context +from ..discriminant_analysis import DiscriminantAnalysisPredictionMixin +from ..metrics.pairwise import ( + pairwise_distances, + pairwise_distances_argmin, +) +from ..preprocessing import LabelEncoder +from ..utils import get_tags +from ..utils._available_if import available_if +from ..utils._param_validation import Interval, StrOptions +from ..utils.multiclass import check_classification_targets +from ..utils.sparsefuncs import csc_median_axis_0 +from ..utils.validation import check_is_fitted, validate_data + + +class NearestCentroid( + DiscriminantAnalysisPredictionMixin, ClassifierMixin, BaseEstimator +): + """Nearest centroid classifier. + + Each class is represented by its centroid, with test samples classified to + the class with the nearest centroid. + + Read more in the :ref:`User Guide `. + + Parameters + ---------- + metric : {"euclidean", "manhattan"}, default="euclidean" + Metric to use for distance computation. + + If `metric="euclidean"`, the centroid for the samples corresponding to each + class is the arithmetic mean, which minimizes the sum of squared L1 distances. + If `metric="manhattan"`, the centroid is the feature-wise median, which + minimizes the sum of L1 distances. + + .. versionchanged:: 1.5 + All metrics but `"euclidean"` and `"manhattan"` were deprecated and + now raise an error. + + .. versionchanged:: 0.19 + `metric='precomputed'` was deprecated and now raises an error + + shrink_threshold : float, default=None + Threshold for shrinking centroids to remove features. + + priors : {"uniform", "empirical"} or array-like of shape (n_classes,), \ + default="uniform" + The class prior probabilities. By default, the class proportions are + inferred from the training data. + + .. versionadded:: 1.6 + + Attributes + ---------- + centroids_ : array-like of shape (n_classes, n_features) + Centroid of each class. + + classes_ : array of shape (n_classes,) + The unique classes labels. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + deviations_ : ndarray of shape (n_classes, n_features) + Deviations (or shrinkages) of the centroids of each class from the + overall centroid. Equal to eq. (18.4) if `shrink_threshold=None`, + else (18.5) p. 653 of [2]. Can be used to identify features used + for classification. + + .. versionadded:: 1.6 + + within_class_std_dev_ : ndarray of shape (n_features,) + Pooled or within-class standard deviation of input data. + + .. versionadded:: 1.6 + + class_prior_ : ndarray of shape (n_classes,) + The class prior probabilities. + + .. versionadded:: 1.6 + + See Also + -------- + KNeighborsClassifier : Nearest neighbors classifier. + + Notes + ----- + When used for text classification with tf-idf vectors, this classifier is + also known as the Rocchio classifier. + + References + ---------- + [1] Tibshirani, R., Hastie, T., Narasimhan, B., & Chu, G. (2002). Diagnosis of + multiple cancer types by shrunken centroids of gene expression. Proceedings + of the National Academy of Sciences of the United States of America, + 99(10), 6567-6572. The National Academy of Sciences. + + [2] Hastie, T., Tibshirani, R., Friedman, J. (2009). The Elements of Statistical + Learning Data Mining, Inference, and Prediction. 2nd Edition. New York, Springer. + + Examples + -------- + >>> from sklearn.neighbors import NearestCentroid + >>> import numpy as np + >>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) + >>> y = np.array([1, 1, 1, 2, 2, 2]) + >>> clf = NearestCentroid() + >>> clf.fit(X, y) + NearestCentroid() + >>> print(clf.predict([[-0.8, -1]])) + [1] + """ + + _parameter_constraints: dict = { + "metric": [StrOptions({"manhattan", "euclidean"})], + "shrink_threshold": [Interval(Real, 0, None, closed="neither"), None], + "priors": ["array-like", StrOptions({"empirical", "uniform"})], + } + + def __init__( + self, + metric="euclidean", + *, + shrink_threshold=None, + priors="uniform", + ): + self.metric = metric + self.shrink_threshold = shrink_threshold + self.priors = priors + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y): + """ + Fit the NearestCentroid model according to the given training data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Training vector, where `n_samples` is the number of samples and + `n_features` is the number of features. + Note that centroid shrinking cannot be used with sparse matrices. + y : array-like of shape (n_samples,) + Target values. + + Returns + ------- + self : object + Fitted estimator. + """ + # If X is sparse and the metric is "manhattan", store it in a csc + # format is easier to calculate the median. + if self.metric == "manhattan": + X, y = validate_data(self, X, y, accept_sparse=["csc"]) + else: + ensure_all_finite = ( + "allow-nan" if get_tags(self).input_tags.allow_nan else True + ) + X, y = validate_data( + self, + X, + y, + ensure_all_finite=ensure_all_finite, + accept_sparse=["csr", "csc"], + ) + is_X_sparse = sp.issparse(X) + check_classification_targets(y) + + n_samples, n_features = X.shape + le = LabelEncoder() + y_ind = le.fit_transform(y) + self.classes_ = classes = le.classes_ + n_classes = classes.size + if n_classes < 2: + raise ValueError( + "The number of classes has to be greater than one; got %d class" + % (n_classes) + ) + + if self.priors == "empirical": # estimate priors from sample + _, class_counts = np.unique(y, return_inverse=True) # non-negative ints + self.class_prior_ = np.bincount(class_counts) / float(len(y)) + elif self.priors == "uniform": + self.class_prior_ = np.asarray([1 / n_classes] * n_classes) + else: + self.class_prior_ = np.asarray(self.priors) + + if (self.class_prior_ < 0).any(): + raise ValueError("priors must be non-negative") + if not np.isclose(self.class_prior_.sum(), 1.0): + warnings.warn( + "The priors do not sum to 1. Normalizing such that it sums to one.", + UserWarning, + ) + self.class_prior_ = self.class_prior_ / self.class_prior_.sum() + + # Mask mapping each class to its members. + self.centroids_ = np.empty((n_classes, n_features), dtype=np.float64) + + # Number of clusters in each class. + nk = np.zeros(n_classes) + + for cur_class in range(n_classes): + center_mask = y_ind == cur_class + nk[cur_class] = np.sum(center_mask) + if is_X_sparse: + center_mask = np.where(center_mask)[0] + + if self.metric == "manhattan": + # NumPy does not calculate median of sparse matrices. + if not is_X_sparse: + self.centroids_[cur_class] = np.median(X[center_mask], axis=0) + else: + self.centroids_[cur_class] = csc_median_axis_0(X[center_mask]) + else: # metric == "euclidean" + self.centroids_[cur_class] = X[center_mask].mean(axis=0) + + # Compute within-class std_dev with unshrunked centroids + variance = np.array(X - self.centroids_[y_ind], copy=False) ** 2 + self.within_class_std_dev_ = np.array( + np.sqrt(variance.sum(axis=0) / (n_samples - n_classes)), copy=False + ) + if any(self.within_class_std_dev_ == 0): + warnings.warn( + "self.within_class_std_dev_ has at least 1 zero standard deviation." + "Inputs within the same classes for at least 1 feature are identical." + ) + + err_msg = "All features have zero variance. Division by zero." + if is_X_sparse and np.all((X.max(axis=0) - X.min(axis=0)).toarray() == 0): + raise ValueError(err_msg) + elif not is_X_sparse and np.all(np.ptp(X, axis=0) == 0): + raise ValueError(err_msg) + + dataset_centroid_ = X.mean(axis=0) + # m parameter for determining deviation + m = np.sqrt((1.0 / nk) - (1.0 / n_samples)) + # Calculate deviation using the standard deviation of centroids. + # To deter outliers from affecting the results. + s = self.within_class_std_dev_ + np.median(self.within_class_std_dev_) + mm = m.reshape(len(m), 1) # Reshape to allow broadcasting. + ms = mm * s + self.deviations_ = np.array( + (self.centroids_ - dataset_centroid_) / ms, copy=False + ) + # Soft thresholding: if the deviation crosses 0 during shrinking, + # it becomes zero. + if self.shrink_threshold: + signs = np.sign(self.deviations_) + self.deviations_ = np.abs(self.deviations_) - self.shrink_threshold + np.clip(self.deviations_, 0, None, out=self.deviations_) + self.deviations_ *= signs + # Now adjust the centroids using the deviation + msd = ms * self.deviations_ + self.centroids_ = np.array(dataset_centroid_ + msd, copy=False) + return self + + def predict(self, X): + """Perform classification on an array of test vectors `X`. + + The predicted class `C` for each sample in `X` is returned. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + Input data. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) + The predicted classes. + """ + check_is_fitted(self) + if np.isclose(self.class_prior_, 1 / len(self.classes_)).all(): + # `validate_data` is called here since we are not calling `super()` + ensure_all_finite = ( + "allow-nan" if get_tags(self).input_tags.allow_nan else True + ) + X = validate_data( + self, + X, + ensure_all_finite=ensure_all_finite, + accept_sparse="csr", + reset=False, + ) + return self.classes_[ + pairwise_distances_argmin(X, self.centroids_, metric=self.metric) + ] + else: + return super().predict(X) + + def _decision_function(self, X): + # return discriminant scores, see eq. (18.2) p. 652 of the ESL. + check_is_fitted(self, "centroids_") + + X_normalized = validate_data( + self, X, copy=True, reset=False, accept_sparse="csr", dtype=np.float64 + ) + + discriminant_score = np.empty( + (X_normalized.shape[0], self.classes_.size), dtype=np.float64 + ) + + mask = self.within_class_std_dev_ != 0 + X_normalized[:, mask] /= self.within_class_std_dev_[mask] + centroids_normalized = self.centroids_.copy() + centroids_normalized[:, mask] /= self.within_class_std_dev_[mask] + + for class_idx in range(self.classes_.size): + distances = pairwise_distances( + X_normalized, centroids_normalized[[class_idx]], metric=self.metric + ).ravel() + distances **= 2 + discriminant_score[:, class_idx] = np.squeeze( + -distances + 2.0 * np.log(self.class_prior_[class_idx]) + ) + + return discriminant_score + + def _check_euclidean_metric(self): + return self.metric == "euclidean" + + decision_function = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.decision_function + ) + + predict_proba = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.predict_proba + ) + + predict_log_proba = available_if(_check_euclidean_metric)( + DiscriminantAnalysisPredictionMixin.predict_log_proba + ) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.allow_nan = self.metric == "nan_euclidean" + tags.input_tags.sparse = True + return tags diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..16d0fa305b66c2ccf6a57a23e285e8f3c6d5b4ae Binary files /dev/null and b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.cpython-310-x86_64-linux-gnu.so differ diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd new file mode 100644 index 0000000000000000000000000000000000000000..bd2160cc3b26f4eaf0821735aeb278fd3a16eb15 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pxd @@ -0,0 +1,10 @@ +from cython cimport floating +from ..utils._typedefs cimport float64_t, intp_t + +cdef int partition_node_indices( + const floating *data, + intp_t *node_indices, + intp_t split_dim, + intp_t split_index, + intp_t n_features, + intp_t n_points) except -1 diff --git a/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx new file mode 100644 index 0000000000000000000000000000000000000000..111353c49a22becb74cf2d3d609241d208784508 --- /dev/null +++ b/miniconda3/envs/ladir/lib/python3.10/site-packages/sklearn/neighbors/_partition_nodes.pyx @@ -0,0 +1,122 @@ +# BinaryTrees rely on partial sorts to partition their nodes during their +# initialisation. +# +# The C++ std library exposes nth_element, an efficient partial sort for this +# situation which has a linear time complexity as well as the best performances. +# +# To use std::algorithm::nth_element, a few fixture are defined using Cython: +# - partition_node_indices, a Cython function used in BinaryTrees, that calls +# - partition_node_indices_inner, a C++ function that wraps nth_element and uses +# - an IndexComparator to state how to compare KDTrees' indices +# +# IndexComparator has been defined so that partial sorts are stable with +# respect to the nodes initial indices. +# +# See for reference: +# - https://en.cppreference.com/w/cpp/algorithm/nth_element. +# - https://github.com/scikit-learn/scikit-learn/pull/11103 +# - https://github.com/scikit-learn/scikit-learn/pull/19473 +from cython cimport floating + + +cdef extern from *: + """ + #include + + template + class IndexComparator { + private: + const D *data; + I split_dim, n_features; + public: + IndexComparator(const D *data, const I &split_dim, const I &n_features): + data(data), split_dim(split_dim), n_features(n_features) {} + + bool operator()(const I &a, const I &b) const { + D a_value = data[a * n_features + split_dim]; + D b_value = data[b * n_features + split_dim]; + return a_value == b_value ? a < b : a_value < b_value; + } + }; + + template + void partition_node_indices_inner( + const D *data, + I *node_indices, + const I &split_dim, + const I &split_index, + const I &n_features, + const I &n_points) { + IndexComparator index_comparator(data, split_dim, n_features); + std::nth_element( + node_indices, + node_indices + split_index, + node_indices + n_points, + index_comparator); + } + """ + void partition_node_indices_inner[D, I]( + const D *data, + I *node_indices, + I split_dim, + I split_index, + I n_features, + I n_points) except + + + +cdef int partition_node_indices( + const floating *data, + intp_t *node_indices, + intp_t split_dim, + intp_t split_index, + intp_t n_features, + intp_t n_points) except -1: + """Partition points in the node into two equal-sized groups. + + Upon return, the values in node_indices will be rearranged such that + (assuming numpy-style indexing): + + data[node_indices[0:split_index], split_dim] + <= data[node_indices[split_index], split_dim] + + and + + data[node_indices[split_index], split_dim] + <= data[node_indices[split_index:n_points], split_dim] + + The algorithm is essentially a partial in-place quicksort around a + set pivot. + + Parameters + ---------- + data : double pointer + Pointer to a 2D array of the training data, of shape [N, n_features]. + N must be greater than any of the values in node_indices. + node_indices : int pointer + Pointer to a 1D array of length n_points. This lists the indices of + each of the points within the current node. This will be modified + in-place. + split_dim : int + the dimension on which to split. This will usually be computed via + the routine ``find_node_split_dim``. + split_index : int + the index within node_indices around which to split the points. + n_features: int + the number of features (i.e columns) in the 2D array pointed by data. + n_points : int + the length of node_indices. This is also the number of points in + the original dataset. + Returns + ------- + status : int + integer exit status. On return, the contents of node_indices are + modified as noted above. + """ + partition_node_indices_inner( + data, + node_indices, + split_dim, + split_index, + n_features, + n_points) + return 0