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 predict(self, X, **predict_params): """Predict using the base regressor, applying inverse. The regressor is used to predict and the `inverse_func` or `inverse_transform` is applied before returning the prediction. Parameters ---------- X : {array-like, sparse matrix...
Predict using the base regressor, applying inverse. The regressor is used to predict and the `inverse_func` or `inverse_transform` is applied before returning the prediction. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Samp...
predict
python
scikit-learn/scikit-learn
sklearn/compose/_target.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_target.py
BSD-3-Clause
def n_features_in_(self): """Number of features seen during :term:`fit`.""" # For consistency with other estimators we raise a AttributeError so # that hasattr() returns False the estimator isn't fitted. try: check_is_fitted(self) except NotFittedError as nfe: ...
Number of features seen during :term:`fit`.
n_features_in_
python
scikit-learn/scikit-learn
sklearn/compose/_target.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_target.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.6 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.6 Returns ------- routing : MetadataRouter A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating...
get_metadata_routing
python
scikit-learn/scikit-learn
sklearn/compose/_target.py
https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/compose/_target.py
BSD-3-Clause
def test_column_transformer_remainder_dtypes(cols1, cols2, expected_remainder_cols): """Check that the remainder columns format matches the format of the other columns when they're all strings or masks. """ X = np.ones((1, 3)) if isinstance(cols1, list) and isinstance(cols1[0], str): pd = p...
Check that the remainder columns format matches the format of the other columns when they're all strings or masks.
test_column_transformer_remainder_dtypes
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_force_int_remainder_cols_deprecation(force_int_remainder_cols): """Check that ColumnTransformer raises a FutureWarning when force_int_remainder_cols is set. """ X = np.ones((1, 3)) ct = ColumnTransformer( [("T1", Trans(), [0]), ("T2", Trans(), [1])], remainder="passthrough",...
Check that ColumnTransformer raises a FutureWarning when force_int_remainder_cols is set.
test_force_int_remainder_cols_deprecation
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_feature_names_out_pandas(selector): """Checks name when selecting only the second column""" pd = pytest.importorskip("pandas") df = pd.DataFrame({"col1": ["a", "a", "b"], "col2": ["z", "z", "z"]}) ct = ColumnTransformer([("ohe", OneHotEncoder(), selector)]) ct.fit(df) assert_array_equa...
Checks name when selecting only the second column
test_feature_names_out_pandas
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_feature_names_out_non_pandas(selector): """Checks name when selecting the second column with numpy array""" X = [["a", "z"], ["a", "z"], ["b", "z"]] ct = ColumnTransformer([("ohe", OneHotEncoder(), selector)]) ct.fit(X) assert_array_equal(ct.get_feature_names_out(), ["ohe__x1_z"])
Checks name when selecting the second column with numpy array
test_feature_names_out_non_pandas
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_column_transformer_reordered_column_names_remainder( explicit_colname, remainder ): """Test the interaction between remainder and column transformer""" pd = pytest.importorskip("pandas") X_fit_array = np.array([[0, 1, 2], [2, 4, 6]]).T X_fit_df = pd.DataFrame(X_fit_array, columns=["first",...
Test the interaction between remainder and column transformer
test_column_transformer_reordered_column_names_remainder
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_feature_name_validation_missing_columns_drop_passthough(): """Test the interaction between {'drop', 'passthrough'} and missing column names.""" pd = pytest.importorskip("pandas") X = np.ones(shape=(3, 4)) df = pd.DataFrame(X, columns=["a", "b", "c", "d"]) df_dropped = df.drop("c", axi...
Test the interaction between {'drop', 'passthrough'} and missing column names.
test_feature_name_validation_missing_columns_drop_passthough
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_feature_names_in_(): """Feature names are stored in column transformer. Column transformer deliberately does not check for column name consistency. It only checks that the non-dropped names seen in `fit` are seen in `transform`. This behavior is already tested in `test_feature_name_validat...
Feature names are stored in column transformer. Column transformer deliberately does not check for column name consistency. It only checks that the non-dropped names seen in `fit` are seen in `transform`. This behavior is already tested in `test_feature_name_validation_missing_columns_drop_passthough`
test_feature_names_in_
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_column_transform_set_output_mixed(remainder, fit_transform): """Check ColumnTransformer outputs mixed types correctly.""" pd = pytest.importorskip("pandas") df = pd.DataFrame( { "pet": pd.Series(["dog", "cat", "snake"], dtype="category"), "color": pd.Series(["green",...
Check ColumnTransformer outputs mixed types correctly.
test_column_transform_set_output_mixed
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_transformers_with_pandas_out_but_not_feature_names_out( trans_1, expected_verbose_names, expected_non_verbose_names ): """Check that set_config(transform="pandas") is compatible with more transformers. Specifically, if transformers returns a DataFrame, but does not define `get_feature_names_ou...
Check that set_config(transform="pandas") is compatible with more transformers. Specifically, if transformers returns a DataFrame, but does not define `get_feature_names_out`.
test_transformers_with_pandas_out_but_not_feature_names_out
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_empty_selection_pandas_output(empty_selection): """Check that pandas output works when there is an empty selection. Non-regression test for gh-25487 """ pd = pytest.importorskip("pandas") X = pd.DataFrame([[1.0, 2.2], [3.0, 1.0]], columns=["a", "b"]) ct = ColumnTransformer( [ ...
Check that pandas output works when there is an empty selection. Non-regression test for gh-25487
test_empty_selection_pandas_output
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_raise_error_if_index_not_aligned(): """Check column transformer raises error if indices are not aligned. Non-regression test for gh-26210. """ pd = pytest.importorskip("pandas") X = pd.DataFrame([[1.0, 2.2], [3.0, 1.0]], columns=["a", "b"], index=[8, 3]) reset_index_transformer = Func...
Check column transformer raises error if indices are not aligned. Non-regression test for gh-26210.
test_raise_error_if_index_not_aligned
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_remainder_set_output(): """Check that the output is set for the remainder. Non-regression test for #26306. """ pd = pytest.importorskip("pandas") df = pd.DataFrame({"a": [True, False, True], "b": [1, 2, 3]}) ct = make_column_transformer( (VarianceThreshold(), make_column_sele...
Check that the output is set for the remainder. Non-regression test for #26306.
test_remainder_set_output
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_pd_na(): """Check behavior when a tranformer's output contains pandas.NA It should raise an error unless the output config is set to 'pandas'. """ pd = pytest.importorskip("pandas") if not hasattr(pd, "Float64Dtype"): pytest.skip( "The issue with pd.NA tested ...
Check behavior when a tranformer's output contains pandas.NA It should raise an error unless the output config is set to 'pandas'.
test_transform_pd_na
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_dataframe_different_dataframe_libraries(): """Check fitting and transforming on pandas and polars dataframes.""" pd = pytest.importorskip("pandas") pl = pytest.importorskip("polars") X_train_np = np.array([[0, 1], [2, 4], [4, 5]]) X_test_np = np.array([[1, 2], [1, 3], [2, 3]]) # Fit on...
Check fitting and transforming on pandas and polars dataframes.
test_dataframe_different_dataframe_libraries
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_column_transformer_remainder_passthrough_naming_consistency(transform_output): """Check that when `remainder="passthrough"`, inconsistent naming is handled correctly by the underlying `FunctionTransformer`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28232 ...
Check that when `remainder="passthrough"`, inconsistent naming is handled correctly by the underlying `FunctionTransformer`. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28232
test_column_transformer_remainder_passthrough_naming_consistency
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_column_transformer_column_renaming(dataframe_lib): """Check that we properly rename columns when using `ColumnTransformer` and selected columns are redundant between transformers. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28260 """ lib = pytest.import...
Check that we properly rename columns when using `ColumnTransformer` and selected columns are redundant between transformers. Non-regression test for: https://github.com/scikit-learn/scikit-learn/issues/28260
test_column_transformer_column_renaming
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_column_transformer_error_with_duplicated_columns(dataframe_lib): """Check that we raise an error when using `ColumnTransformer` and the columns names are duplicated between transformers.""" lib = pytest.importorskip(dataframe_lib) df = lib.DataFrame({"x1": [1, 2, 3], "x2": [10, 20, 30], "x3": ...
Check that we raise an error when using `ColumnTransformer` and the columns names are duplicated between transformers.
test_column_transformer_error_with_duplicated_columns
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_column_transformer_auto_memmap(): """Check that ColumnTransformer works in parallel with joblib's auto-memmapping. non-regression test for issue #28781 """ X = np.random.RandomState(0).uniform(size=(3, 4)) scaler = StandardScaler(copy=False) transformer = ColumnTransformer( t...
Check that ColumnTransformer works in parallel with joblib's auto-memmapping. non-regression test for issue #28781
test_column_transformer_auto_memmap
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_routing_passed_metadata_not_supported(method): """Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.""" X = np.array([[0, 1, 2], [2, 4, 6]]).T y = [1, 2, 3] trs = ColumnTransformer([("trans", Trans(), [0])]).fit(X, ...
Test that the right error message is raised when metadata is passed while not supported when `enable_metadata_routing=False`.
test_routing_passed_metadata_not_supported
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_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 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 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