Thanks to visit codestin.com
Credit goes to github.com

Skip to content

FIX Raises error in PLSRegression for invalid n_components #29710

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions doc/whats_new/v1.6.rst
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,12 @@ Changelog
now accepts string format or callable to generate feature names. :pr:`28934` by
:user:`Marc Bresson <MarcBresson>`.

:mod:`sklearn.cross_decomposition`
..................................

- |Fix| :class:`cross_decomposition.PLSRegression` properly raises an error when
`n_components` is larger than `n_samples`. :pr:`29710` by `Thomas Fan`_.

:mod:`sklearn.datasets`
.......................

Expand Down
4 changes: 3 additions & 1 deletion sklearn/cross_decomposition/_pls.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,9 @@ def fit(self, X, y=None, Y=None):
# With PLSRegression n_components is bounded by the rank of (X.T X) see
# Wegelin page 25. With CCA and PLSCanonical, n_components is bounded
# by the rank of X and the rank of Y: see Wegelin page 12
rank_upper_bound = p if self.deflation_mode == "regression" else min(n, p, q)
rank_upper_bound = (
min(n, p) if self.deflation_mode == "regression" else min(n, p, q)
)
if n_components > rank_upper_bound:
raise ValueError(
f"`n_components` upper bound is {rank_upper_bound}. "
Expand Down
11 changes: 11 additions & 0 deletions sklearn/cross_decomposition/tests/test_pls.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,17 @@ def test_n_components_upper_bounds(Estimator):
est.fit(X, Y)


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. Reduce `n_components`."
with pytest.raises(ValueError, match=err_msg):
est.fit(X, Y)


@pytest.mark.parametrize("n_samples, n_features", [(100, 10), (100, 200)])
def test_singular_value_helpers(n_samples, n_features, global_random_seed):
# Make sure SVD and power method give approximately the same results
Expand Down