Skip to content

[WIP] first step in fixing minimum 2 required samples for fixing MLPRegressor attribute error #24788

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
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:class:`neural_network.MLPRegressor` now raises an informative error when
`early_stopping` is set and the computed validation set is too small.
By :user:`David Shumway <davidshumway>`.
6 changes: 6 additions & 0 deletions sklearn/neural_network/_multilayer_perceptron.py
Original file line number Diff line number Diff line change
Expand Up @@ -668,6 +668,12 @@ def _fit_stochastic(
test_size=self.validation_fraction,
stratify=stratify,
)
if X_val.shape[0] < 2:
raise ValueError(
"The validation set is too small. Increase 'validation_fraction' "
"or the size of your dataset."
)

if is_classifier(self):
y_val = self._label_binarizer.inverse_transform(y_val)
else:
Expand Down
8 changes: 8 additions & 0 deletions sklearn/neural_network/tests/test_mlp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1084,3 +1084,11 @@ def test_mlp_vs_poisson_glm_equivalent(global_random_seed):
random_state=np.random.RandomState(global_random_seed + 1),
).fit(X, y)
assert not np.allclose(mlp.predict(X), glm.predict(X), rtol=1e-4)


def test_minimum_input_sample_size():
"""Check error message when the validation set is too small."""
X, y = make_regression(n_samples=2, n_features=5, random_state=0)
model = MLPRegressor(early_stopping=True, random_state=0)
with pytest.raises(ValueError, match="The validation set is too small"):
model.fit(X, y)