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_metadata_routing_for_column_transformer(method):
"""Test that metadata is routed correctly for column transformer."""
X = np.array([[0, 1, 2], [2, 4, 6]]).T
y = [1, 2, 3]
registry = _Registry()
sample_weight, metadata = [1], "a"
trs = ColumnTransformer(
[
(
... | Test that metadata is routed correctly for column transformer. | test_metadata_routing_for_column_transformer | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_metadata_routing_no_fit_transform():
"""Test metadata routing when the sub-estimator doesn't implement
``fit_transform``."""
class NoFitTransform(BaseEstimator):
def fit(self, X, y=None, sample_weight=None, metadata=None):
assert sample_weight
assert metadata
... | Test metadata routing when the sub-estimator doesn't implement
``fit_transform``. | test_metadata_routing_no_fit_transform | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_metadata_routing_error_for_column_transformer(method):
"""Test that the right error is raised when metadata is not requested."""
X = np.array([[0, 1, 2], [2, 4, 6]]).T
y = [1, 2, 3]
sample_weight, metadata = [1], "a"
trs = ColumnTransformer([("trans", ConsumingTransformer(), [0])])
err... | Test that the right error is raised when metadata is not requested. | test_metadata_routing_error_for_column_transformer | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_column_transformer.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_column_transformer.py | BSD-3-Clause |
def test_transform_target_regressor_not_warns_with_global_output_set(output_format):
"""Test that TransformedTargetRegressor will not raise warnings if
set_config(transform_output="pandas"/"polars") is set globally; regression test for
issue #29361."""
X, y = datasets.make_regression()
y = np.abs(y)... | Test that TransformedTargetRegressor will not raise warnings if
set_config(transform_output="pandas"/"polars") is set globally; regression test for
issue #29361. | test_transform_target_regressor_not_warns_with_global_output_set | python | scikit-learn/scikit-learn | sklearn/compose/tests/test_target.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/tests/test_target.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the EllipticEnvelope model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
se... | Fit the EllipticEnvelope model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
self : object
Returns the i... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_elliptic_envelope.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_elliptic_envelope.py | BSD-3-Clause |
def decision_function(self, X):
"""Compute the decision function of the given observations.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
decision : ndarray of shape (n_samples,)
De... | Compute the decision function of the given observations.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
decision : ndarray of shape (n_samples,)
Decision function of the samples.
... | decision_function | python | scikit-learn/scikit-learn | sklearn/covariance/_elliptic_envelope.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_elliptic_envelope.py | BSD-3-Clause |
def predict(self, X):
"""
Predict labels (1 inlier, -1 outlier) of X according to fitted model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
is_inlier : ndarray of shape (n_samples,)
... |
Predict labels (1 inlier, -1 outlier) of X according to fitted model.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix.
Returns
-------
is_inlier : ndarray of shape (n_samples,)
Returns -1 for anomali... | predict | python | scikit-learn/scikit-learn | sklearn/covariance/_elliptic_envelope.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_elliptic_envelope.py | BSD-3-Clause |
def log_likelihood(emp_cov, precision):
"""Compute the sample mean of the log_likelihood under a covariance model.
Computes the empirical expected log-likelihood, allowing for universal
comparison (beyond this software package), and accounts for normalization
terms and scaling.
Parameters
----... | Compute the sample mean of the log_likelihood under a covariance model.
Computes the empirical expected log-likelihood, allowing for universal
comparison (beyond this software package), and accounts for normalization
terms and scaling.
Parameters
----------
emp_cov : ndarray of shape (n_featur... | log_likelihood | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def empirical_covariance(X, *, assume_centered=False):
"""Compute the Maximum likelihood covariance estimator.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
assume_centered : bool, default=False
If `True`, dat... | Compute the Maximum likelihood covariance estimator.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
assume_centered : bool, default=False
If `True`, data will not be centered before computation.
Useful when... | empirical_covariance | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def _set_covariance(self, covariance):
"""Saves the covariance and precision estimates
Storage is done accordingly to `self.store_precision`.
Precision stored only if invertible.
Parameters
----------
covariance : array-like of shape (n_features, n_features)
... | Saves the covariance and precision estimates
Storage is done accordingly to `self.store_precision`.
Precision stored only if invertible.
Parameters
----------
covariance : array-like of shape (n_features, n_features)
Estimated covariance matrix to be stored, and fro... | _set_covariance | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def get_precision(self):
"""Getter for the precision matrix.
Returns
-------
precision_ : array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object.
"""
if self.store_precision:
precision = self.... | Getter for the precision matrix.
Returns
-------
precision_ : array-like of shape (n_features, n_features)
The precision matrix associated to the current covariance object.
| get_precision | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the maximum likelihood covariance estimator to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples and
`n_features` is the number of features.
y :... | Fit the maximum likelihood covariance estimator to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples and
`n_features` is the number of features.
y : Ignored
Not used, presen... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def score(self, X_test, y=None):
"""Compute the log-likelihood of `X_test` under the estimated Gaussian model.
The Gaussian model is defined by its mean and covariance matrix which are
represented respectively by `self.location_` and `self.covariance_`.
Parameters
----------
... | Compute the log-likelihood of `X_test` under the estimated Gaussian model.
The Gaussian model is defined by its mean and covariance matrix which are
represented respectively by `self.location_` and `self.covariance_`.
Parameters
----------
X_test : array-like of shape (n_sample... | score | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def error_norm(self, comp_cov, norm="frobenius", scaling=True, squared=True):
"""Compute the Mean Squared Error between two covariance estimators.
Parameters
----------
comp_cov : array-like of shape (n_features, n_features)
The covariance to compare with.
norm : {"... | Compute the Mean Squared Error between two covariance estimators.
Parameters
----------
comp_cov : array-like of shape (n_features, n_features)
The covariance to compare with.
norm : {"frobenius", "spectral"}, default="frobenius"
The type of norm used to compute... | error_norm | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def mahalanobis(self, X):
"""Compute the squared Mahalanobis distances of given observations.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The observations, the Mahalanobis distances of the which we
compute. Observations are assumed to be... | Compute the squared Mahalanobis distances of given observations.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The observations, the Mahalanobis distances of the which we
compute. Observations are assumed to be drawn from the same
dist... | mahalanobis | python | scikit-learn/scikit-learn | sklearn/covariance/_empirical_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_empirical_covariance.py | BSD-3-Clause |
def _objective(mle, precision_, alpha):
"""Evaluation of the graphical-lasso objective function
the objective function is made of a shifted scaled version of the
normalized log-likelihood (i.e. its empirical mean over the samples) and a
penalisation term to promote sparsity
"""
p = precision_.s... | Evaluation of the graphical-lasso objective function
the objective function is made of a shifted scaled version of the
normalized log-likelihood (i.e. its empirical mean over the samples) and a
penalisation term to promote sparsity
| _objective | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def _dual_gap(emp_cov, precision_, alpha):
"""Expression of the dual gap convergence criterion
The specific definition is given in Duchi "Projected Subgradient Methods
for Learning Sparse Gaussians".
"""
gap = np.sum(emp_cov * precision_)
gap -= precision_.shape[0]
gap += alpha * (np.abs(pr... | Expression of the dual gap convergence criterion
The specific definition is given in Duchi "Projected Subgradient Methods
for Learning Sparse Gaussians".
| _dual_gap | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def alpha_max(emp_cov):
"""Find the maximum alpha for which there are some non-zeros off-diagonal.
Parameters
----------
emp_cov : ndarray of shape (n_features, n_features)
The sample covariance matrix.
Notes
-----
This results from the bound for the all the Lasso that are solved
... | Find the maximum alpha for which there are some non-zeros off-diagonal.
Parameters
----------
emp_cov : ndarray of shape (n_features, n_features)
The sample covariance matrix.
Notes
-----
This results from the bound for the all the Lasso that are solved
in GraphicalLasso: each time... | alpha_max | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def graphical_lasso(
emp_cov,
alpha,
*,
mode="cd",
tol=1e-4,
enet_tol=1e-4,
max_iter=100,
verbose=False,
return_costs=False,
eps=np.finfo(np.float64).eps,
return_n_iter=False,
):
"""L1-penalized covariance estimator.
Read more in the :ref:`User Guide <sparse_inverse_... | L1-penalized covariance estimator.
Read more in the :ref:`User Guide <sparse_inverse_covariance>`.
.. versionchanged:: v0.20
graph_lasso has been renamed to graphical_lasso
Parameters
----------
emp_cov : array-like of shape (n_features, n_features)
Empirical covariance from which... | graphical_lasso | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the GraphicalLasso model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
y : Ignored
Not used, present for API consistency by convention.
... | Fit the GraphicalLasso model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
y : Ignored
Not used, present for API consistency by convention.
Returns
-------
... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def graphical_lasso_path(
X,
alphas,
cov_init=None,
X_test=None,
mode="cd",
tol=1e-4,
enet_tol=1e-4,
max_iter=100,
verbose=False,
eps=np.finfo(np.float64).eps,
):
"""l1-penalized covariance estimator along a path of decreasing alphas
Read more in the :ref:`User Guide <sp... | l1-penalized covariance estimator along a path of decreasing alphas
Read more in the :ref:`User Guide <sparse_inverse_covariance>`.
Parameters
----------
X : ndarray of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
alphas : array-like of shape (n_alphas... | graphical_lasso_path | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def fit(self, X, y=None, **params):
"""Fit the GraphicalLasso covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
y : Ignored
Not used, present for API consisten... | Fit the GraphicalLasso covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
y : Ignored
Not used, present for API consistency by convention.
**params : dict, def... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.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/covariance/_graph_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_graph_lasso.py | BSD-3-Clause |
def c_step(
X,
n_support,
remaining_iterations=30,
initial_estimates=None,
verbose=False,
cov_computation_method=empirical_covariance,
random_state=None,
):
"""C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD.
Parameters
----------
X : array-like of shap... | C_step procedure described in [Rouseeuw1984]_ aiming at computing MCD.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data set in which we look for the n_support observations whose
scatter matrix has minimum determinant.
n_support : int
Number of observat... | c_step | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def select_candidates(
X,
n_support,
n_trials,
select=1,
n_iter=30,
verbose=False,
cov_computation_method=empirical_covariance,
random_state=None,
):
"""Finds the best pure subset of observations to compute MCD from it.
The purpose of this function is to find the best sets of n_... | Finds the best pure subset of observations to compute MCD from it.
The purpose of this function is to find the best sets of n_support
observations with respect to a minimization of their covariance
matrix determinant. Equivalently, it removes n_samples-n_support
observations to construct what we call a... | select_candidates | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def fast_mcd(
X,
support_fraction=None,
cov_computation_method=empirical_covariance,
random_state=None,
):
"""Estimate the Minimum Covariance Determinant matrix.
Read more in the :ref:`User Guide <robust_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_feat... | Estimate the Minimum Covariance Determinant matrix.
Read more in the :ref:`User Guide <robust_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data matrix, with p features and n samples.
support_fraction : float, default=None
The proportion o... | fast_mcd | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit a Minimum Covariance Determinant with the FastMCD algorithm.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of feature... | Fit a Minimum Covariance Determinant with the FastMCD algorithm.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
N... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def correct_covariance(self, data):
"""Apply a correction to raw Minimum Covariance Determinant estimates.
Correction using the empirical correction factor suggested
by Rousseeuw and Van Driessen in [RVD]_.
Parameters
----------
data : array-like of shape (n_samples, n_... | Apply a correction to raw Minimum Covariance Determinant estimates.
Correction using the empirical correction factor suggested
by Rousseeuw and Van Driessen in [RVD]_.
Parameters
----------
data : array-like of shape (n_samples, n_features)
The data matrix, with p f... | correct_covariance | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def reweight_covariance(self, data):
"""Re-weight raw Minimum Covariance Determinant estimates.
Re-weight observations using Rousseeuw's method (equivalent to
deleting outlying observations from the data set before
computing location and covariance estimates) described
in [RVDri... | Re-weight raw Minimum Covariance Determinant estimates.
Re-weight observations using Rousseeuw's method (equivalent to
deleting outlying observations from the data set before
computing location and covariance estimates) described
in [RVDriessen]_.
Parameters
----------
... | reweight_covariance | python | scikit-learn/scikit-learn | sklearn/covariance/_robust_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_robust_covariance.py | BSD-3-Clause |
def _ledoit_wolf(X, *, assume_centered, block_size):
"""Estimate the shrunk Ledoit-Wolf covariance matrix."""
# for only one feature, the result is the same whatever the shrinkage
if len(X.shape) == 2 and X.shape[1] == 1:
if not assume_centered:
X = X - X.mean()
return np.atleast... | Estimate the shrunk Ledoit-Wolf covariance matrix. | _ledoit_wolf | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def _oas(X, *, assume_centered=False):
"""Estimate covariance with the Oracle Approximating Shrinkage algorithm.
The formulation is based on [1]_.
[1] "Shrinkage algorithms for MMSE covariance estimation.",
Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O.
IEEE Transactions on Signal Proces... | Estimate covariance with the Oracle Approximating Shrinkage algorithm.
The formulation is based on [1]_.
[1] "Shrinkage algorithms for MMSE covariance estimation.",
Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O.
IEEE Transactions on Signal Processing, 58(10), 5016-5029, 2010.
https:/... | _oas | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def shrunk_covariance(emp_cov, shrinkage=0.1):
"""Calculate covariance matrices shrunk on the diagonal.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
emp_cov : array-like of shape (..., n_features, n_features)
Covariance matrices to be shrunk, at least 2D nd... | Calculate covariance matrices shrunk on the diagonal.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
emp_cov : array-like of shape (..., n_features, n_features)
Covariance matrices to be shrunk, at least 2D ndarray.
shrinkage : float, default=0.1
Coe... | shrunk_covariance | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
... | Fit the shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present for API co... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def ledoit_wolf_shrinkage(X, assume_centered=False, block_size=1000):
"""Estimate the shrunk Ledoit-Wolf covariance matrix.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the Ledoit-Wo... | Estimate the shrunk Ledoit-Wolf covariance matrix.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the Ledoit-Wolf shrunk covariance shrinkage.
assume_centered : bool, default=False
... | ledoit_wolf_shrinkage | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def ledoit_wolf(X, *, assume_centered=False, block_size=1000):
"""Estimate the shrunk Ledoit-Wolf covariance matrix.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estim... | Estimate the shrunk Ledoit-Wolf covariance matrix.
Read more in the :ref:`User Guide <shrunk_covariance>`.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Data from which to compute the covariance estimate.
assume_centered : bool, default=False
If True, data ... | ledoit_wolf | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the Ledoit-Wolf shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : ... | Fit the Ledoit-Wolf shrunk covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not used, present... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def fit(self, X, y=None):
"""Fit the Oracle Approximating Shrinkage covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
... | Fit the Oracle Approximating Shrinkage covariance model to X.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training data, where `n_samples` is the number of samples
and `n_features` is the number of features.
y : Ignored
Not u... | fit | python | scikit-learn/scikit-learn | sklearn/covariance/_shrunk_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/_shrunk_covariance.py | BSD-3-Clause |
def test_ledoit_wolf_empty_array(ledoit_wolf_fitting_function):
"""Check that we validate X and raise proper error with 0-sample array."""
X_empty = np.zeros((0, 2))
with pytest.raises(ValueError, match="Found array with 0 sample"):
ledoit_wolf_fitting_function(X_empty) | Check that we validate X and raise proper error with 0-sample array. | test_ledoit_wolf_empty_array | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_covariance.py | BSD-3-Clause |
def test_EmpiricalCovariance_validates_mahalanobis():
"""Checks that EmpiricalCovariance validates data with mahalanobis."""
cov = EmpiricalCovariance().fit(X)
msg = f"X has 2 features, but \\w+ is expecting {X.shape[1]} features as input"
with pytest.raises(ValueError, match=msg):
cov.mahalano... | Checks that EmpiricalCovariance validates data with mahalanobis. | test_EmpiricalCovariance_validates_mahalanobis | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_covariance.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_covariance.py | BSD-3-Clause |
def test_graphical_lassos(random_state=1):
"""Test the graphical lasso solvers.
This checks is unstable for some random seeds where the covariance found with "cd"
and "lars" solvers are different (4 cases / 100 tries).
"""
# Sample data from a sparse multivariate normal
dim = 20
n_samples =... | Test the graphical lasso solvers.
This checks is unstable for some random seeds where the covariance found with "cd"
and "lars" solvers are different (4 cases / 100 tries).
| test_graphical_lassos | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_graphical_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_graphical_lasso.py | BSD-3-Clause |
def test_graphical_lasso_when_alpha_equals_0():
"""Test graphical_lasso's early return condition when alpha=0."""
X = np.random.randn(100, 10)
emp_cov = empirical_covariance(X, assume_centered=True)
model = GraphicalLasso(alpha=0, covariance="precomputed").fit(emp_cov)
assert_allclose(model.precisi... | Test graphical_lasso's early return condition when alpha=0. | test_graphical_lasso_when_alpha_equals_0 | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_graphical_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_graphical_lasso.py | BSD-3-Clause |
def test_graphical_lasso_cv_alphas_iterable(alphas_container_type):
"""Check that we can pass an array-like to `alphas`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/22489
"""
true_cov = np.array(
[
[0.8, 0.0, 0.2, 0.0],
[0.0, 0.4, 0.0... | Check that we can pass an array-like to `alphas`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/22489
| test_graphical_lasso_cv_alphas_iterable | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_graphical_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_graphical_lasso.py | BSD-3-Clause |
def test_graphical_lasso_cv_alphas_invalid_array(alphas, err_type, err_msg):
"""Check that if an array-like containing a value
outside of (0, inf] is passed to `alphas`, a ValueError is raised.
Check if a string is passed, a TypeError is raised.
"""
true_cov = np.array(
[
[0.8, 0... | Check that if an array-like containing a value
outside of (0, inf] is passed to `alphas`, a ValueError is raised.
Check if a string is passed, a TypeError is raised.
| test_graphical_lasso_cv_alphas_invalid_array | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_graphical_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_graphical_lasso.py | BSD-3-Clause |
def test_graphical_lasso_cv_scores_with_routing(global_random_seed):
"""Check that `GraphicalLassoCV` internally dispatches metadata to
the splitter.
"""
splits = 5
n_alphas = 5
n_refinements = 3
true_cov = np.array(
[
[0.8, 0.0, 0.2, 0.0],
[0.0, 0.4, 0.0, 0.0... | Check that `GraphicalLassoCV` internally dispatches metadata to
the splitter.
| test_graphical_lasso_cv_scores_with_routing | python | scikit-learn/scikit-learn | sklearn/covariance/tests/test_graphical_lasso.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/covariance/tests/test_graphical_lasso.py | BSD-3-Clause |
def _get_first_singular_vectors_power_method(
X, y, mode="A", max_iter=500, tol=1e-06, norm_y_weights=False
):
"""Return the first left and right singular vectors of X'y.
Provides an alternative to the svd(X'y) and uses the power method instead.
With norm_y_weights to True and in mode A, this correspon... | Return the first left and right singular vectors of X'y.
Provides an alternative to the svd(X'y) and uses the power method instead.
With norm_y_weights to True and in mode A, this corresponds to the
algorithm section 11.3 of the Wegelin's review, except this starts at the
"update saliences" part.
| _get_first_singular_vectors_power_method | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def _get_first_singular_vectors_svd(X, y):
"""Return the first left and right singular vectors of X'y.
Here the whole SVD is computed.
"""
C = np.dot(X.T, y)
U, _, Vt = svd(C, full_matrices=False)
return U[:, 0], Vt[0, :] | Return the first left and right singular vectors of X'y.
Here the whole SVD is computed.
| _get_first_singular_vectors_svd | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def _center_scale_xy(X, y, scale=True):
"""Center X, y and scale if the scale parameter==True
Returns
-------
X, y, x_mean, y_mean, x_std, y_std
"""
# center
x_mean = X.mean(axis=0)
X -= x_mean
y_mean = y.mean(axis=0)
y -= y_mean
# scale
if scale:
x_std = X.s... | Center X, y and scale if the scale parameter==True
Returns
-------
X, y, x_mean, y_mean, x_std, y_std
| _center_scale_xy | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def _svd_flip_1d(u, v):
"""Same as svd_flip but works on 1d arrays, and is inplace"""
# svd_flip would force us to convert to 2d array and would also return 2d
# arrays. We don't want that.
biggest_abs_val_idx = np.argmax(np.abs(u))
sign = np.sign(u[biggest_abs_val_idx])
u *= sign
v *= sign | Same as svd_flip but works on 1d arrays, and is inplace | _svd_flip_1d | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of predictors.
y : array-like of shape (n_samples... | Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of predictors.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
... | fit | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def transform(self, X, y=None, copy=True):
"""Apply the dimension reduction.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to transform.
y : array-like of shape (n_samples, n_targets), default=None
Target vectors.
... | Apply the dimension reduction.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to transform.
y : array-like of shape (n_samples, n_targets), default=None
Target vectors.
copy : bool, default=True
Whether to copy... | transform | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def inverse_transform(self, X, y=None):
"""Transform data back to its original space.
Parameters
----------
X : array-like of shape (n_samples, n_components)
New data, where `n_samples` is the number of samples
and `n_components` is the number of pls components.
... | Transform data back to its original space.
Parameters
----------
X : array-like of shape (n_samples, n_components)
New data, where `n_samples` is the number of samples
and `n_components` is the number of pls components.
y : array-like of shape (n_samples,) or (n... | inverse_transform | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def predict(self, X, copy=True):
"""Predict targets of given samples.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples.
copy : bool, default=True
Whether to copy `X` or perform in-place normalization.
Returns
... | Predict targets of given samples.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples.
copy : bool, default=True
Whether to copy `X` or perform in-place normalization.
Returns
-------
y_pred : ndarray of shape (... | predict | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of predictors.
y : array-like of shape (n_samples... | Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training vectors, where `n_samples` is the number of samples and
`n_features` is the number of predictors.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
... | fit | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def fit(self, X, y):
"""Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training samples.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Targets.
Returns
-------
self : obj... | Fit model to data.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Training samples.
y : array-like of shape (n_samples,) or (n_samples, n_targets)
Targets.
Returns
-------
self : object
Fitted estimator... | fit | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def transform(self, X, y=None):
"""
Apply the dimensionality reduction.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to be transformed.
y : array-like of shape (n_samples,) or (n_samples, n_targets), \
default... |
Apply the dimensionality reduction.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Samples to be transformed.
y : array-like of shape (n_samples,) or (n_samples, n_targets), default=None
Targets.
Returns
... | transform | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/_pls.py | BSD-3-Clause |
def test_scale_and_stability(Est, X, y):
"""scale=True is equivalent to scale=False on centered/scaled data
This allows to check numerical stability over platforms as well"""
X_s, y_s, *_ = _center_scale_xy(X, y)
X_score, y_score = Est(scale=True).fit_transform(X, y)
X_s_score, y_s_score = Est(sca... | scale=True is equivalent to scale=False on centered/scaled data
This allows to check numerical stability over platforms as well | test_scale_and_stability | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_n_components_upper_bounds(Estimator):
"""Check the validation of `n_components` upper bounds for `PLS` regressors."""
rng = np.random.RandomState(0)
X = rng.randn(10, 5)
y = rng.randn(10, 3)
est = Estimator(n_components=10)
err_msg = "`n_components` upper bound is .*. Got 10 instead. Re... | Check the validation of `n_components` upper bounds for `PLS` regressors. | test_n_components_upper_bounds | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_n_components_upper_PLSRegression():
"""Check the validation of `n_components` upper bounds for PLSRegression."""
rng = np.random.RandomState(0)
X = rng.randn(20, 64)
y = rng.randn(20, 3)
est = PLSRegression(n_components=30)
err_msg = "`n_components` upper bound is 20. Got 30 instead. Re... | Check the validation of `n_components` upper bounds for PLSRegression. | test_n_components_upper_PLSRegression | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_loadings_converges(global_random_seed):
"""Test that CCA converges. Non-regression test for #19549."""
X, y = make_regression(
n_samples=200, n_features=20, n_targets=20, random_state=global_random_seed
)
cca = CCA(n_components=10, max_iter=500)
with warnings.catch_warnings():
... | Test that CCA converges. Non-regression test for #19549. | test_loadings_converges | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_pls_constant_y():
"""Checks warning when y is constant. Non-regression test for #19831"""
rng = np.random.RandomState(42)
x = rng.rand(100, 3)
y = np.zeros(100)
pls = PLSRegression()
msg = "y residual is constant at iteration"
with pytest.warns(UserWarning, match=msg):
pls... | Checks warning when y is constant. Non-regression test for #19831 | test_pls_constant_y | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_pls_coef_shape(PLSEstimator):
"""Check the shape of `coef_` attribute.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12410
"""
d = load_linnerud()
X = d.data
y = d.target
pls = PLSEstimator(copy=True).fit(X, y)
n_targets, n_features = y.shap... | Check the shape of `coef_` attribute.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/12410
| test_pls_coef_shape | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_pls_prediction(PLSEstimator, scale):
"""Check the behaviour of the prediction function."""
d = load_linnerud()
X = d.data
y = d.target
pls = PLSEstimator(copy=True, scale=scale).fit(X, y)
y_pred = pls.predict(X, copy=True)
y_mean = y.mean(axis=0)
X_trans = X - X.mean(axis=0)
... | Check the behaviour of the prediction function. | test_pls_prediction | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_pls_regression_fit_1d_y():
"""Check that when fitting with 1d `y`, prediction should also be 1d.
Non-regression test for Issue #26549.
"""
X = np.array([[1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36]])
y = np.array([2, 6, 12, 20, 30, 42])
expected = y.copy()
plsr = PLSRegressio... | Check that when fitting with 1d `y`, prediction should also be 1d.
Non-regression test for Issue #26549.
| test_pls_regression_fit_1d_y | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def test_pls_regression_scaling_coef():
"""Check that when using `scale=True`, the coefficients are using the std. dev. from
both `X` and `y`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27964
"""
# handcrafted data where we can predict y from X with an addition... | Check that when using `scale=True`, the coefficients are using the std. dev. from
both `X` and `y`.
Non-regression test for:
https://github.com/scikit-learn/scikit-learn/issues/27964
| test_pls_regression_scaling_coef | python | scikit-learn/scikit-learn | sklearn/cross_decomposition/tests/test_pls.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cross_decomposition/tests/test_pls.py | BSD-3-Clause |
def _split_sparse_columns(
arff_data: ArffSparseDataType, include_columns: List
) -> ArffSparseDataType:
"""Obtains several columns from sparse ARFF representation. Additionally,
the column indices are re-labelled, given the columns that are not
included. (e.g., when including [1, 2, 3], the columns wil... | Obtains several columns from sparse ARFF representation. Additionally,
the column indices are re-labelled, given the columns that are not
included. (e.g., when including [1, 2, 3], the columns will be relabelled
to [0, 1, 2]).
Parameters
----------
arff_data : tuple
A tuple of three lis... | _split_sparse_columns | python | scikit-learn/scikit-learn | sklearn/datasets/_arff_parser.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_arff_parser.py | BSD-3-Clause |
def _post_process_frame(frame, feature_names, target_names):
"""Post process a dataframe to select the desired columns in `X` and `y`.
Parameters
----------
frame : dataframe
The dataframe to split into `X` and `y`.
feature_names : list of str
The list of feature names to populate ... | Post process a dataframe to select the desired columns in `X` and `y`.
Parameters
----------
frame : dataframe
The dataframe to split into `X` and `y`.
feature_names : list of str
The list of feature names to populate `X`.
target_names : list of str
The list of target name... | _post_process_frame | python | scikit-learn/scikit-learn | sklearn/datasets/_arff_parser.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_arff_parser.py | BSD-3-Clause |
def _liac_arff_parser(
gzip_file,
output_arrays_type,
openml_columns_info,
feature_names_to_select,
target_names_to_select,
shape=None,
):
"""ARFF parser using the LIAC-ARFF library coded purely in Python.
This parser is quite slow but consumes a generator. Currently it is needed
to... | ARFF parser using the LIAC-ARFF library coded purely in Python.
This parser is quite slow but consumes a generator. Currently it is needed
to parse sparse datasets. For dense datasets, it is recommended to instead
use the pandas-based parser, although it does not always handles the
dtypes exactly the s... | _liac_arff_parser | python | scikit-learn/scikit-learn | sklearn/datasets/_arff_parser.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_arff_parser.py | BSD-3-Clause |
def _pandas_arff_parser(
gzip_file,
output_arrays_type,
openml_columns_info,
feature_names_to_select,
target_names_to_select,
read_csv_kwargs=None,
):
"""ARFF parser using `pandas.read_csv`.
This parser uses the metadata fetched directly from OpenML and skips the metadata
headers of... | ARFF parser using `pandas.read_csv`.
This parser uses the metadata fetched directly from OpenML and skips the metadata
headers of ARFF file itself. The data is loaded as a CSV file.
Parameters
----------
gzip_file : GzipFile instance
The GZip compressed file with the ARFF formatted payload... | _pandas_arff_parser | python | scikit-learn/scikit-learn | sklearn/datasets/_arff_parser.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_arff_parser.py | BSD-3-Clause |
def load_arff_from_gzip_file(
gzip_file,
parser,
output_type,
openml_columns_info,
feature_names_to_select,
target_names_to_select,
shape=None,
read_csv_kwargs=None,
):
"""Load a compressed ARFF file using a given parser.
Parameters
----------
gzip_file : GzipFile instan... | Load a compressed ARFF file using a given parser.
Parameters
----------
gzip_file : GzipFile instance
The file compressed to be read.
parser : {"pandas", "liac-arff"}
The parser used to parse the ARFF file. "pandas" is recommended
but only supports loading dense datasets.
... | load_arff_from_gzip_file | python | scikit-learn/scikit-learn | sklearn/datasets/_arff_parser.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_arff_parser.py | BSD-3-Clause |
def get_data_home(data_home=None) -> str:
"""Return the path of the scikit-learn data directory.
This folder is used by some large dataset loaders to avoid downloading the
data several times.
By default the data directory is set to a folder named 'scikit_learn_data' in the
user home folder.
A... | Return the path of the scikit-learn data directory.
This folder is used by some large dataset loaders to avoid downloading the
data several times.
By default the data directory is set to a folder named 'scikit_learn_data' in the
user home folder.
Alternatively, it can be set by the 'SCIKIT_LEARN_... | get_data_home | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_files(
container_path,
*,
description=None,
categories=None,
load_content=True,
shuffle=True,
encoding=None,
decode_error="strict",
random_state=0,
allowed_extensions=None,
):
"""Load text files with categories as subfolder names.
Individual samples are assumed ... | Load text files with categories as subfolder names.
Individual samples are assumed to be files stored a two levels folder
structure such as the following:
.. code-block:: text
container_folder/
category_1_folder/
file_1.txt
file_2.txt
..... | load_files | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_csv_data(
data_file_name,
*,
data_module=DATA_MODULE,
descr_file_name=None,
descr_module=DESCR_MODULE,
encoding="utf-8",
):
"""Loads `data_file_name` from `data_module with `importlib.resources`.
Parameters
----------
data_file_name : str
Name of csv file to be ... | Loads `data_file_name` from `data_module with `importlib.resources`.
Parameters
----------
data_file_name : str
Name of csv file to be loaded from `data_module/data_file_name`.
For example `'wine_data.csv'`.
data_module : str or module, default='sklearn.datasets.data'
Module wh... | load_csv_data | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_wine(*, return_X_y=False, as_frame=False):
"""Load and return the wine dataset (classification).
.. versionadded:: 0.18
The wine dataset is a classic and very easy multi-class classification
dataset.
================= ==============
Classes 3
Samples pe... | Load and return the wine dataset (classification).
.. versionadded:: 0.18
The wine dataset is a classic and very easy multi-class classification
dataset.
================= ==============
Classes 3
Samples per class [59,71,48]
Samples total ... | load_wine | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_iris(*, return_X_y=False, as_frame=False):
"""Load and return the iris dataset (classification).
The iris dataset is a classic and very easy multi-class classification
dataset.
================= ==============
Classes 3
Samples per class 50
... | Load and return the iris dataset (classification).
The iris dataset is a classic and very easy multi-class classification
dataset.
================= ==============
Classes 3
Samples per class 50
Samples total 150
Dimensionality ... | load_iris | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_breast_cancer(*, return_X_y=False, as_frame=False):
"""Load and return the breast cancer Wisconsin dataset (classification).
The breast cancer dataset is a classic and very easy binary classification
dataset.
================= ==============
Classes 2
Sample... | Load and return the breast cancer Wisconsin dataset (classification).
The breast cancer dataset is a classic and very easy binary classification
dataset.
================= ==============
Classes 2
Samples per class 212(M),357(B)
Samples total 569
... | load_breast_cancer | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_digits(*, n_class=10, return_X_y=False, as_frame=False):
"""Load and return the digits dataset (classification).
Each datapoint is a 8x8 image of a digit.
================= ==============
Classes 10
Samples per class ~180
Samples total ... | Load and return the digits dataset (classification).
Each datapoint is a 8x8 image of a digit.
================= ==============
Classes 10
Samples per class ~180
Samples total 1797
Dimensionality 64
Features ... | load_digits | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_diabetes(*, return_X_y=False, as_frame=False, scaled=True):
"""Load and return the diabetes dataset (regression).
============== ==================
Samples total 442
Dimensionality 10
Features real, -.2 < x < .2
Targets integer 25 - 346
============== ====... | Load and return the diabetes dataset (regression).
============== ==================
Samples total 442
Dimensionality 10
Features real, -.2 < x < .2
Targets integer 25 - 346
============== ==================
.. note::
The meaning of each feature (i.e. `feat... | load_diabetes | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_linnerud(*, return_X_y=False, as_frame=False):
"""Load and return the physical exercise Linnerud dataset.
This dataset is suitable for multi-output regression tasks.
============== ============================
Samples total 20
Dimensionality 3 (for both data and target)
Feature... | Load and return the physical exercise Linnerud dataset.
This dataset is suitable for multi-output regression tasks.
============== ============================
Samples total 20
Dimensionality 3 (for both data and target)
Features integer
Targets integer
============... | load_linnerud | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_sample_images():
"""Load sample images for image manipulation.
Loads both, ``china`` and ``flower``.
Read more in the :ref:`User Guide <sample_images>`.
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
images... | Load sample images for image manipulation.
Loads both, ``china`` and ``flower``.
Read more in the :ref:`User Guide <sample_images>`.
Returns
-------
data : :class:`~sklearn.utils.Bunch`
Dictionary-like object, with the following attributes.
images : list of ndarray of shape (427,... | load_sample_images | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def load_sample_image(image_name):
"""Load the numpy array of a single sample image.
Read more in the :ref:`User Guide <sample_images>`.
Parameters
----------
image_name : {`china.jpg`, `flower.jpg`}
The name of the sample image loaded.
Returns
-------
img : 3D array
T... | Load the numpy array of a single sample image.
Read more in the :ref:`User Guide <sample_images>`.
Parameters
----------
image_name : {`china.jpg`, `flower.jpg`}
The name of the sample image loaded.
Returns
-------
img : 3D array
The image as a numpy array: height x width ... | load_sample_image | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def _pkl_filepath(*args, **kwargs):
"""Return filename for Python 3 pickles
args[-1] is expected to be the ".pkl" filename. For compatibility with
older scikit-learn versions, a suffix is inserted before the extension.
_pkl_filepath('/path/to/folder', 'filename.pkl') returns
'/path/to/folder/filen... | Return filename for Python 3 pickles
args[-1] is expected to be the ".pkl" filename. For compatibility with
older scikit-learn versions, a suffix is inserted before the extension.
_pkl_filepath('/path/to/folder', 'filename.pkl') returns
'/path/to/folder/filename_py3.pkl'
| _pkl_filepath | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def _sha256(path):
"""Calculate the sha256 hash of the file at path."""
sha256hash = hashlib.sha256()
chunk_size = 8192
with open(path, "rb") as f:
while True:
buffer = f.read(chunk_size)
if not buffer:
break
sha256hash.update(buffer)
retur... | Calculate the sha256 hash of the file at path. | _sha256 | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def _fetch_remote(remote, dirname=None, n_retries=3, delay=1):
"""Helper function to download a remote dataset.
Fetch a dataset pointed by remote's url, save into path using remote's
filename and ensure its integrity based on the SHA256 checksum of the
downloaded file.
.. versionchanged:: 1.6
... | Helper function to download a remote dataset.
Fetch a dataset pointed by remote's url, save into path using remote's
filename and ensure its integrity based on the SHA256 checksum of the
downloaded file.
.. versionchanged:: 1.6
If the file already exists locally and the SHA256 checksums match... | _fetch_remote | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def _filter_filename(value, filter_dots=True):
"""Derive a name that is safe to use as filename from the given string.
Adapted from the `slugify` function of django:
https://github.com/django/django/blob/master/django/utils/text.py
Convert spaces or repeated dashes to single dashes. Replace characters... | Derive a name that is safe to use as filename from the given string.
Adapted from the `slugify` function of django:
https://github.com/django/django/blob/master/django/utils/text.py
Convert spaces or repeated dashes to single dashes. Replace characters that
aren't alphanumerics, underscores, hyphens o... | _filter_filename | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def fetch_file(
url, folder=None, local_filename=None, sha256=None, n_retries=3, delay=1
):
"""Fetch a file from the web if not already present in the local folder.
If the file already exists locally (and the SHA256 checksums match when
provided), the path to the local file is returned without re-downl... | Fetch a file from the web if not already present in the local folder.
If the file already exists locally (and the SHA256 checksums match when
provided), the path to the local file is returned without re-downloading.
.. versionadded:: 1.6
Parameters
----------
url : str
URL of the file... | fetch_file | python | scikit-learn/scikit-learn | sklearn/datasets/_base.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_base.py | BSD-3-Clause |
def fetch_california_housing(
*,
data_home=None,
download_if_missing=True,
return_X_y=False,
as_frame=False,
n_retries=3,
delay=1.0,
):
"""Load the California housing dataset (regression).
============== ==============
Samples total 20640
Dimensionality ... | Load the California housing dataset (regression).
============== ==============
Samples total 20640
Dimensionality 8
Features real
Target real 0.15 - 5.
============== ==============
Read more in the :ref:`User Guide <california_ho... | fetch_california_housing | python | scikit-learn/scikit-learn | sklearn/datasets/_california_housing.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_california_housing.py | BSD-3-Clause |
def fetch_covtype(
*,
data_home=None,
download_if_missing=True,
random_state=None,
shuffle=False,
return_X_y=False,
as_frame=False,
n_retries=3,
delay=1.0,
):
"""Load the covertype dataset (classification).
Download it if necessary.
================= ============
... | Load the covertype dataset (classification).
Download it if necessary.
================= ============
Classes 7
Samples total 581012
Dimensionality 54
Features int
================= ============
Read more in the... | fetch_covtype | python | scikit-learn/scikit-learn | sklearn/datasets/_covtype.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_covtype.py | BSD-3-Clause |
def fetch_kddcup99(
*,
subset=None,
data_home=None,
shuffle=False,
random_state=None,
percent10=True,
download_if_missing=True,
return_X_y=False,
as_frame=False,
n_retries=3,
delay=1.0,
):
"""Load the kddcup99 dataset (classification).
Download it if necessary.
... | Load the kddcup99 dataset (classification).
Download it if necessary.
================= ====================================
Classes 23
Samples total 4898431
Dimensionality 41
... | fetch_kddcup99 | python | scikit-learn/scikit-learn | sklearn/datasets/_kddcup99.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_kddcup99.py | BSD-3-Clause |
def _fetch_brute_kddcup99(
data_home=None, download_if_missing=True, percent10=True, n_retries=3, delay=1.0
):
"""Load the kddcup99 dataset, downloading it if necessary.
Parameters
----------
data_home : str, default=None
Specify another download and cache folder for the datasets. By defaul... | Load the kddcup99 dataset, downloading it if necessary.
Parameters
----------
data_home : str, default=None
Specify another download and cache folder for the datasets. By default
all scikit-learn data is stored in '~/scikit_learn_data' subfolders.
download_if_missing : bool, default=Tr... | _fetch_brute_kddcup99 | python | scikit-learn/scikit-learn | sklearn/datasets/_kddcup99.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_kddcup99.py | BSD-3-Clause |
def _mkdirp(d):
"""Ensure directory d exists (like mkdir -p on Unix)
No guarantee that the directory is writable.
"""
try:
os.makedirs(d)
except OSError as e:
if e.errno != errno.EEXIST:
raise | Ensure directory d exists (like mkdir -p on Unix)
No guarantee that the directory is writable.
| _mkdirp | python | scikit-learn/scikit-learn | sklearn/datasets/_kddcup99.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_kddcup99.py | BSD-3-Clause |
def _check_fetch_lfw(
data_home=None, funneled=True, download_if_missing=True, n_retries=3, delay=1.0
):
"""Helper function to download any missing LFW data"""
data_home = get_data_home(data_home=data_home)
lfw_home = join(data_home, "lfw_home")
if not exists(lfw_home):
makedirs(lfw_home)
... | Helper function to download any missing LFW data | _check_fetch_lfw | python | scikit-learn/scikit-learn | sklearn/datasets/_lfw.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_lfw.py | BSD-3-Clause |
def _fetch_lfw_people(
data_folder_path, slice_=None, color=False, resize=None, min_faces_per_person=0
):
"""Perform the actual data loading for the lfw people dataset
This operation is meant to be cached by a joblib wrapper.
"""
# scan the data folder content to retain people with more that
# ... | Perform the actual data loading for the lfw people dataset
This operation is meant to be cached by a joblib wrapper.
| _fetch_lfw_people | python | scikit-learn/scikit-learn | sklearn/datasets/_lfw.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_lfw.py | BSD-3-Clause |
def fetch_lfw_people(
*,
data_home=None,
funneled=True,
resize=0.5,
min_faces_per_person=0,
color=False,
slice_=(slice(70, 195), slice(78, 172)),
download_if_missing=True,
return_X_y=False,
n_retries=3,
delay=1.0,
):
"""Load the Labeled Faces in the Wild (LFW) people data... | Load the Labeled Faces in the Wild (LFW) people dataset (classification).
Download it if necessary.
================= =======================
Classes 5749
Samples total 13233
Dimensionality 5828
Features ... | fetch_lfw_people | python | scikit-learn/scikit-learn | sklearn/datasets/_lfw.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_lfw.py | BSD-3-Clause |
def _fetch_lfw_pairs(
index_file_path, data_folder_path, slice_=None, color=False, resize=None
):
"""Perform the actual data loading for the LFW pairs dataset
This operation is meant to be cached by a joblib wrapper.
"""
# parse the index file to find the number of pairs to be able to allocate
... | Perform the actual data loading for the LFW pairs dataset
This operation is meant to be cached by a joblib wrapper.
| _fetch_lfw_pairs | python | scikit-learn/scikit-learn | sklearn/datasets/_lfw.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_lfw.py | BSD-3-Clause |
def fetch_lfw_pairs(
*,
subset="train",
data_home=None,
funneled=True,
resize=0.5,
color=False,
slice_=(slice(70, 195), slice(78, 172)),
download_if_missing=True,
n_retries=3,
delay=1.0,
):
"""Load the Labeled Faces in the Wild (LFW) pairs dataset (classification).
Downl... | Load the Labeled Faces in the Wild (LFW) pairs dataset (classification).
Download it if necessary.
================= =======================
Classes 2
Samples total 13233
Dimensionality 5828
Features ... | fetch_lfw_pairs | python | scikit-learn/scikit-learn | sklearn/datasets/_lfw.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_lfw.py | BSD-3-Clause |
def fetch_olivetti_faces(
*,
data_home=None,
shuffle=False,
random_state=0,
download_if_missing=True,
return_X_y=False,
n_retries=3,
delay=1.0,
):
"""Load the Olivetti faces data-set from AT&T (classification).
Download it if necessary.
================= =================... | Load the Olivetti faces data-set from AT&T (classification).
Download it if necessary.
================= =====================
Classes 40
Samples total 400
Dimensionality 4096
Features real, between 0 and... | fetch_olivetti_faces | python | scikit-learn/scikit-learn | sklearn/datasets/_olivetti_faces.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_olivetti_faces.py | BSD-3-Clause |
def _retry_with_clean_cache(
openml_path: str,
data_home: Optional[str],
no_retry_exception: Optional[Exception] = None,
) -> Callable:
"""If the first call to the decorated function fails, the local cached
file is removed, and the function is called again. If ``data_home`` is
``None``, then the... | If the first call to the decorated function fails, the local cached
file is removed, and the function is called again. If ``data_home`` is
``None``, then the function is called once. We can provide a specific
exception to not retry on using `no_retry_exception` parameter.
| _retry_with_clean_cache | python | scikit-learn/scikit-learn | sklearn/datasets/_openml.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_openml.py | BSD-3-Clause |
def _retry_on_network_error(
n_retries: int = 3, delay: float = 1.0, url: str = ""
) -> Callable:
"""If the function call results in a network error, call the function again
up to ``n_retries`` times with a ``delay`` between each call. If the error
has a 412 status code, don't call the function again as... | If the function call results in a network error, call the function again
up to ``n_retries`` times with a ``delay`` between each call. If the error
has a 412 status code, don't call the function again as this is a specific
OpenML error.
The url parameter is used to give more information to the user abou... | _retry_on_network_error | python | scikit-learn/scikit-learn | sklearn/datasets/_openml.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_openml.py | BSD-3-Clause |
def _open_openml_url(
url: str, data_home: Optional[str], n_retries: int = 3, delay: float = 1.0
):
"""
Returns a resource from OpenML.org. Caches it to data_home if required.
Parameters
----------
url : str
OpenML URL that will be downloaded and cached locally. The path component
... |
Returns a resource from OpenML.org. Caches it to data_home if required.
Parameters
----------
url : str
OpenML URL that will be downloaded and cached locally. The path component
of the URL is used to replicate the tree structure as sub-folders of the local
cache folder.
da... | _open_openml_url | python | scikit-learn/scikit-learn | sklearn/datasets/_openml.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_openml.py | BSD-3-Clause |
def _get_json_content_from_openml_api(
url: str,
error_message: Optional[str],
data_home: Optional[str],
n_retries: int = 3,
delay: float = 1.0,
) -> Dict:
"""
Loads json data from the openml api.
Parameters
----------
url : str
The URL to load from. Should be an officia... |
Loads json data from the openml api.
Parameters
----------
url : str
The URL to load from. Should be an official OpenML endpoint.
error_message : str or None
The error message to raise if an acceptable OpenML error is thrown
(acceptable error is, e.g., data id not found. O... | _get_json_content_from_openml_api | python | scikit-learn/scikit-learn | sklearn/datasets/_openml.py | https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/_openml.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.