code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
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) | Check that expected error are raised during fit. | test_gpc_fit_error | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpc.py | BSD-3-Clause |
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_va... | Checks that the latent mean and variance have the right shape. | test_gpc_latent_mean_and_variance_shape | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpc.py | BSD-3-Clause |
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.... |
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.
| test_y_normalization | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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 G... |
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 'g... | test_large_variance_y | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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.
"""... | 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.
| test_constant_target | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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 st... | 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).
| test_gpr_consistency_std_cov_non_invertible_kernel | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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... | Check that we raise the proper error in the LML method. | test_gpr_lml_error | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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, ... | Check that we raise the proper error during predict. | test_gpr_predict_error | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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... | 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://... | test_predict_shapes | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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... | 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
| test_sample_y_shapes | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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=... | Check the output shape of `sample_y` is consistent before and after `fit`. | test_sample_y_shape_with_prior | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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_targ... | Check the output shape of `predict` with prior distribution. | test_predict_shape_with_prior | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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, m... | Check that an error is raised when the number of targets seen at fit is
inconsistent with n_targets.
| test_n_targets_error | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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(ker... |
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
| test_gpr_predict_input_not_modified | python | scikit-learn/scikit-learn | sklearn/gaussian_process/tests/test_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/tests/test_gpr.py | BSD-3-Clause |
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:... | 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. | _most_frequent | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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_"):... | 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.
| _transform_indicator | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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
# ma... | Concatenate indicator mask with the imputed data. | _concatenate_indicator | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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
... | 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... | fit | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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 str... | Fit the transformer on sparse data. | _sparse_fit | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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":
... | Fit the transformer on dense data. | _dense_fit | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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 \
... | 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)
... | transform | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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_tran... | 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
... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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 b... | 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:`tr... | _get_missing_features_info | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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.
... | 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 ... | _fit | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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... | 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... | transform | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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 conv... | 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
-------
... | fit_transform | python | scikit-learn/scikit-learn | sklearn/impute/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_base.py | BSD-3-Clause |
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)
... | 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.
| _assign_where | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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... | 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... | _impute_one_feature | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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_... | 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 f... | _get_neighbor_feat_idx | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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 feat... | 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
... | _get_ordered_idx | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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
... | 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
... | _get_abs_corr_mat | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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.
... | 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 funct... | _initial_imputation | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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 fe... | 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, presen... | fit_transform | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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)
... | 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.
... | transform | python | scikit-learn/scikit-learn | sklearn/impute/_iterative.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_iterative.py | BSD-3-Clause |
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 donor... | 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
... | _calc_impute | python | scikit-learn/scikit-learn | sklearn/impute/_knn.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_knn.py | BSD-3-Clause |
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, ... | 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 c... | fit | python | scikit-learn/scikit-learn | sklearn/impute/_knn.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_knn.py | BSD-3-Clause |
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 impute... | 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 t... | transform | python | scikit-learn/scikit-learn | sklearn/impute/_knn.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/_knn.py | BSD-3-Clause |
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.ran... | Check the behaviour of the private helpers `_assign_where`. | test_assign_where | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_base.py | BSD-3-Clause |
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, m... | Check feature names out for imputers. | test_imputers_feature_names_out_pandas | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_common.py | BSD-3-Clause |
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 ... | Check that the imputer keeps features with only missing values. | test_keep_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_common.py | BSD-3-Clause |
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 variab... | Check that missing indicator always exists when add_indicator=True.
Non-regression test for gh-26590.
| test_imputation_adds_missing_indicator_if_add_indicator_is_true | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_common.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_common.py | BSD-3-Clause |
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 ... | 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 | _check_statistics | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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 = IterativeImp... | Check the behaviour of the iterative imputer with different initial strategy
and keeping empty features (i.e. features containing only missing values).
| test_iterative_imputer_keep_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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",... | Check that we propagate properly the parameter `fill_value`. | test_iterative_imputer_constant_fill_value | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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 ... | 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
| test_iterative_imputer_min_max_value_remove_empty | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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_... | Check the behaviour of `keep_empty_features` for `KNNImputer`. | test_knn_imputer_keep_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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_valu... | Check that missing indicator return the feature names with a prefix. | test_missing_indicator_feature_names_out | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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.... | Check transform uses object dtype when fitted on an object dtype.
Non-regression test for #19572.
| test_imputer_lists_fit_transform | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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... | Check transform preserves numeric dtype independent of fit dtype. | test_imputer_transform_preserves_numeric_dtype | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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,... | 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.
| test_simple_imputer_constant_keep_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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(stra... | Check the behaviour of `keep_empty_features` with all strategies but
'constant'.
| test_simple_imputer_keep_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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
"""
... | 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
| test_simple_imputer_constant_fill_value_casting | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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-le... | 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
| test_iterative_imputer_no_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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:/... | 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
| test_iterative_imputer_with_empty_features | python | scikit-learn/scikit-learn | sklearn/impute/tests/test_impute.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/impute/tests/test_impute.py | BSD-3-Clause |
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... | 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 numbe... | _grid_from_X | python | scikit-learn/scikit-learn | sklearn/inspection/_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_partial_dependence.py | BSD-3-Clause |
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 interes... | 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; othe... | _partial_dependence_recursion | python | scikit-learn/scikit-learn | sklearn/inspection/_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_partial_dependence.py | BSD-3-Clause |
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 ... | 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... | _partial_dependence_brute | python | scikit-learn/scikit-learn | sklearn/inspection/_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_partial_dependence.py | BSD-3-Clause |
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... | 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 <part... | partial_dependence | python | scikit-learn/scikit-learn | sklearn/inspection/_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_partial_dependence.py | 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
-------
... | 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 vali... | _check_feature_names | python | scikit-learn/scikit-learn | sklearn/inspection/_pd_utils.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_pd_utils.py | BSD-3-Clause |
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 in... | 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.
| _get_feature_index | python | scikit-learn/scikit-learn | sklearn/inspection/_pd_utils.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_pd_utils.py | BSD-3-Clause |
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)
... | 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
-------... | _create_importances_bunch | python | scikit-learn/scikit-learn | sklearn/inspection/_permutation_importance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_permutation_importance.py | BSD-3-Clause |
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... | 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`... | permutation_importance | python | scikit-learn/scikit-learn | sklearn/inspection/_permutation_importance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_permutation_importance.py | BSD-3-Clause |
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", "... | Check that `_grid_from_X` always sample from categories and does not
depend from the percentiles.
| test_grid_from_X_with_categorical | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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, fe... | Check that `sample_weight` does not have any effect on reported ICE. | test_partial_dependence_kind_individual_ignores_sample_weight | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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
c... | 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.
| test_partial_dependence_non_null_weight_idx | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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_... | Check that `sample_weight=None` is equivalent to having equal weights. | test_partial_dependence_equivalence_equal_sample_weight | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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 p... | Check that we raise an error when the size of `sample_weight` is not
consistent with `X` and `y`.
| test_partial_dependence_sample_weight_size_error | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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_wei... | Check that we raise an error when `sample_weight` is provided with
`"recursion"` method.
| test_partial_dependence_sample_weight_with_recursion | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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... | Check that we raise a proper error when a column has mixed types and
the sorting of `np.unique` will fail. | test_mixed_type_categorical | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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.... | Check that we raise the proper exception when `categorical_features`
is an empty list | test_partial_dependence_empty_categorical_features | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_partial_dependence.py | BSD-3-Clause |
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_sampl... | Check that a proper error message is raised when `max_samples` is not
set to a valid input value.
| test_permutation_importance_max_samples_error | python | scikit-learn/scikit-learn | sklearn/inspection/tests/test_permutation_importance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/tests/test_permutation_importance.py | BSD-3-Clause |
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', 'p... | 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`,... | _check_boundary_response_method | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/decision_boundary.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/decision_boundary.py | BSD-3-Clause |
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
... | 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 <matplotl... | plot | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/decision_boundary.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/decision_boundary.py | BSD-3-Clause |
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,
**kwa... | Plot decision boundary given an estimator.
Read more in the :ref:`User Guide <visualizations>`.
Parameters
----------
estimator : object
Trained estimator used to plot the decision boundary.
X : {array-like, sparse matrix, dataframe} of shape (n_samples, 2)
... | from_estimator | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/decision_boundary.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/decision_boundary.py | BSD-3-Clause |
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),
... | 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
ar... | from_estimator | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/partial_dependence.py | BSD-3-Clause |
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):... | Compute the number of samples as an integer. | _get_sample_count | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/partial_dependence.py | BSD-3-Clause |
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_... | 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_point... | _plot_ice_lines | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/partial_dependence.py | BSD-3-Clause |
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,... | 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,)
... | _plot_average_dependence | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/partial_dependence.py | BSD-3-Clause |
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
----------
... | 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 ... | _plot_two_way_partial_dependence | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/partial_dependence.py | BSD-3-Clause |
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(V... | Check that we raise an error when `X` does not have exactly 2 features. | test_input_data_dimension | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 classifi... | Check error raised for multi-output multi-class classifiers by
`_check_boundary_response_method`.
| test_check_boundary_response_method_error | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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, clas... | Check the behaviour of `_check_boundary_response_method` for the supported
cases.
| test_check_boundary_response_method | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 = DecisionBo... | Check multiclass `response=predict` gives expected results. | test_multiclass_predict | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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,
res... | Check that decision boundary is correct. | test_decision_boundary_display_classifier | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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_... | Check that decision boundary is correct for outlier detector. | test_decision_boundary_display_outlier_detector | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 = ... | Check that we can display the decision boundary for a regressor. | test_decision_boundary_display_regressor | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 no... | Check that multilabel classifier raises correct error. | test_multilabel_classifier_error | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 an... | Check that multi-output multi-class classifier raises correct error. | test_multi_output_multi_class_classifier_error | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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"):
... | Check that multioutput regressor raises correct error. | test_multioutput_regressor_error | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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_esti... | Check that column names are used for pandas. | test_dataframe_labels_used | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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
DecisionB... | Check that decision boundary works with classifiers trained on string labels. | test_string_target | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 ... | 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
| test_dataframe_support | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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.... | Check the behaviour of passing `class_of_interest` for plotting the output of
`predict_proba` and `decision_function` in the binary case.
| test_class_of_interest_binary | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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... | Check the behaviour of passing `class_of_interest` for plotting the output of
`predict_proba` and `decision_function` in the multiclass case.
| test_class_of_interest_multiclass | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 prod... | Check plot correct when plotting max multiclass class. | test_multiclass_plot_max_class | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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 equiv... | Check correct cmap used for all `multiclass_colors` inputs. | test_multiclass_colors_cmap | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
def test_multiclass_plot_max_class_cmap_kwarg(pyplot):
"""Check `cmap` kwarg ignored when using plotting max multiclass class."""
X, y = load_iris_2d_scaled()
clf = LogisticRegression().fit(X, y)
msg = (
"Plotting max class of multiclass 'decision_function' or 'predict_proba', "
"thus '... | Check `cmap` kwarg ignored when using plotting max multiclass class. | test_multiclass_plot_max_class_cmap_kwarg | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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(Deci... | Check that named constructors return the correct type when subclassed.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/pull/27675
| test_subclass_named_constructors_return_type_is_subclass | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_boundary_decision_display.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_boundary_decision_display.py | BSD-3-Clause |
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],
... | Test that make sure that we can overwrite the label of the PDP plot | test_partial_dependence_overwrite_labels | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_plot_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py | BSD-3-Clause |
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 =... | Check that we raise a ValueError when the grid_resolution is too small
respect to the number of categories in the categorical features targeted.
| test_grid_resolution_with_categorical | python | scikit-learn/scikit-learn | sklearn/inspection/_plot/tests/test_plot_partial_dependence.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/inspection/_plot/tests/test_plot_partial_dependence.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.