Skip to content
Merged
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
``sklearn.utils._check_sample_weight`` now raises a clearer error message when the
provided weights are neither a scalar nor a 1-D array-like of the same size as the
input data.
:issue:`31712` by :user:`Kapil Parekh <kapslock123>`.
2 changes: 1 addition & 1 deletion sklearn/utils/tests/test_validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1608,7 +1608,7 @@ def _check_sample_weight_common(xp):
assert_allclose(_convert_to_numpy(sample_weight, xp), 2 * np.ones(5))

# check wrong number of dimensions
with pytest.raises(ValueError, match="Sample weights must be 1D array or scalar"):
with pytest.raises(ValueError, match=r"Sample weights must be 1D array or scalar"):
_check_sample_weight(xp.ones((2, 4)), X=xp.ones((2, 2)))

# check incorrect n_samples
Expand Down
6 changes: 5 additions & 1 deletion sklearn/utils/validation.py
Original file line number Diff line number Diff line change
Expand Up @@ -2222,7 +2222,11 @@ def _check_sample_weight(
input_name="sample_weight",
)
if sample_weight.ndim != 1:
raise ValueError("Sample weights must be 1D array or scalar")
raise ValueError(
f"Sample weights must be 1D array or scalar, got "
f"{sample_weight.ndim}D array. Expected either a scalar value "
f"or a 1D array of length {n_samples}."
)

if sample_weight.shape != (n_samples,):
raise ValueError(
Expand Down
Loading