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 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,)
Tar... | 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.
... | fit | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 : ndar... | 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,)
... | predict | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 : ... | 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_class... | predict_proba | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 w... | 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
... | log_marginal_likelihood | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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... | 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.
... | latent_mean_and_variance | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 m... | 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.
| _posterior_mode | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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,)
Tar... | 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.
... | fit | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 : ndar... | 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,)
... | predict | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 : ... | 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_class... | predict_proba | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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_]
) | Return the kernel of the base estimator. | kernel_ | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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.
... | 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
... | log_marginal_likelihood | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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 onl... | 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.
..... | latent_mean_and_variance | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpc.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpc.py | BSD-3-Clause |
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_ta... | 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... | fit | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpr.py | BSD-3-Clause |
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 ... | 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 t... | predict | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpr.py | BSD-3-Clause |
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
... | 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 p... | sample_y | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpr.py | BSD-3-Clause |
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 whi... | 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
... | log_marginal_likelihood | python | scikit-learn/scikit-learn | sklearn/gaussian_process/_gpr.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/gaussian_process/_gpr.py | BSD-3-Clause |
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_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(
Val... | Checks that the latent mean and variance have the right shape. | test_gpc_latent_mean_and_variance_complain_on_more_than_2_classes | 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_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) | Check that expected error are raised during fit. | test_gpr_fit_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_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_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
... | 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... | get_feature_names_out | 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 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
... | 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... | get_feature_names_out | 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 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
... | 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... | get_feature_names_out | 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_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.met... | Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating... | get_metadata_routing | 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 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
... | 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... | get_feature_names_out | 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_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(
{
... | Check that `_grid_from_X` always sample from categories and does not
depend from the percentiles.
| test_grid_from_X_heterogeneous_type | 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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.