Repository navigation
Closed
Description
Describe the bug and give evidence about its user-facing impact
When trying to fit a ridge model with the array API on multi target objective, if one want to pass an array for alpha, the checks are not well configured I think, leading to an impossibility.
Here is a small reproducer.
Steps/Code to Reproduce
import os
os.environ["SCIPY_ARRAY_API"] = "1"
import torch
from sklearn import config_context
from sklearn.linear_model import Ridge
from sklearn.datasets import make_regression
X, y = make_regression(1000, n_targets=10)
with config_context(array_api_dispatch=True):
# will consider that alpha is scalar in `_ridge_regression`
# and fail the check_scalar check l.703
reg = Ridge(alpha=np.array([1.]*10))
reg.fit(torch.tensor(X), torch.tensor(y))
# Will fail on `_validate_params` from the base estimator class
reg = Ridge(alpha=torch.tensor([1.]*10))
reg.fit(torch.tensor(X), torch.tensor(y))Expected Results
Working with both cases :)
Actual Results
raise errors:
- for np.array
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 13
11 with config_context(array_api_dispatch=True):
12 reg = Ridge(alpha=np.array([1.]*10))
---> 13 reg.fit(torch.tensor(X), torch.tensor(y))
15 reg = Ridge(alpha=torch.tensor([1.]*10))
16 reg.fit(torch.tensor(X), torch.tensor(y))
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/base.py:1336, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
1329 estimator._validate_params()
1331 with config_context(
1332 skip_parameter_validation=(
1333 prefer_skip_nested_validation or global_skip_validation
1334 )
1335 ):
-> 1336 return fit_method(estimator, *args, **kwargs)
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/linear_model/_ridge.py:1264, in Ridge.fit(self, X, y, sample_weight)
1253 xp, _ = get_namespace(X, y, sample_weight)
1254 X, y = validate_data(
1255 self,
1256 X,
(...) 1262 y_numeric=True,
1263 )
-> 1264 return super().fit(X, y, sample_weight=sample_weight)
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/linear_model/_ridge.py:1006, in _BaseRidge.fit(self, X, y, sample_weight)
1002 else:
1003 # for dense matrices or when intercept is set to 0
1004 params = {}
-> 1006 self.coef_, self.n_iter_, self.solver_ = _ridge_regression(
1007 X,
1008 y,
1009 alpha=self.alpha,
1010 sample_weight=sample_weight,
1011 max_iter=self.max_iter,
1012 tol=self.tol,
1013 solver=solver,
1014 positive=self.positive,
1015 random_state=self.random_state,
1016 return_n_iter=True,
1017 return_intercept=False,
1018 return_solver=True,
1019 check_input=False,
1020 fit_intercept=self.fit_intercept,
1021 **params,
1022 )
1023 self._set_intercept(X_offset, y_offset, X_scale)
1025 return self
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/linear_model/_ridge.py:704, in _ridge_regression(X, y, alpha, sample_weight, solver, max_iter, tol, verbose, positive, random_state, return_n_iter, return_intercept, return_solver, X_scale, X_offset, check_input, fit_intercept)
701 # Some callers of this method might pass alpha as single
702 # element array which already has been validated.
703 if alpha is not None and not isinstance(alpha, type(xp.asarray([0.0]))):
--> 704 alpha = check_scalar(
705 alpha,
706 "alpha",
707 target_type=numbers.Real,
708 min_val=0.0,
709 include_boundaries="left",
710 )
712 # There should be either 1 or n_targets penalties
713 alpha = _ravel(xp.asarray(alpha, device=device_, dtype=X.dtype), xp=xp)
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/utils/validation.py:1861, in check_scalar(x, name, target_type, min_val, max_val, include_boundaries)
1858 else:
1859 target_type_str = type_name(target_type)
-> 1861 raise TypeError(
1862 f"{name} must be an instance of {target_type_str}, not"
1863 f" {type(x).__qualname__}."
1864 )
1866 expected_include_boundaries = ("left", "right", "both", "neither")
1867 if include_boundaries not in expected_include_boundaries:
TypeError: alpha must be an instance of float, not ndarray.- for torch.tensor
---------------------------------------------------------------------------
InvalidParameterError Traceback (most recent call last)
Cell In[2], line 13
11 with config_context(array_api_dispatch=True):
12 reg = Ridge(alpha=torch.tensor([1.]*10))
---> 13 reg.fit(torch.tensor(X), torch.tensor(y))
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/base.py:1329, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs)
1324 partial_fit_and_fitted = (
1325 fit_method.__name__ == "partial_fit" and _is_fitted(estimator)
1326 )
1328 if not global_skip_validation and not partial_fit_and_fitted:
-> 1329 estimator._validate_params()
1331 with config_context(
1332 skip_parameter_validation=(
1333 prefer_skip_nested_validation or global_skip_validation
1334 )
1335 ):
1336 return fit_method(estimator, *args, **kwargs)
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/base.py:492, in BaseEstimator._validate_params(self)
484 def _validate_params(self):
485 """Validate types and values of constructor parameters
486
487 The expected type and values must be defined in the `_parameter_constraints`
(...) 490 accepted constraints.
491 """
--> 492 validate_parameter_constraints(
493 self._parameter_constraints,
494 self.get_params(deep=False),
495 caller_name=self.__class__.__name__,
496 )
File ~/.local/miniconda/lib/python3.12/site-packages/sklearn/utils/_param_validation.py:98, in validate_parameter_constraints(parameter_constraints, params, caller_name)
92 else:
93 constraints_str = (
94 f"{', '.join([str(c) for c in constraints[:-1]])} or"
95 f" {constraints[-1]}"
96 )
---> 98 raise InvalidParameterError(
99 f"The {param_name!r} parameter of {caller_name} must be"
100 f" {constraints_str}. Got {param_val!r} instead."
101 )
InvalidParameterError: The 'alpha' parameter of Ridge must be a float in the range [0.0, inf) or an instance of 'numpy.ndarray'. Got tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]) instead.Versions
1.8.0Interest in fixing the bug
might be if I have time.
Activity
prem-479 commentedon May 23, 2026
Hi, I reproduced both failure paths locally and started tracing the validation flow. It looks like the inconsistency comes from the interaction between
_parameter_constraintsvalidation and the runtime scalar checks inside_ridge_regressionunder Array API dispatch. I’d like to investigate a minimal fix together with regression tests.prem-479 commentedon May 23, 2026
Update: I've finished implementing a minimal, backend-agnostic fix. I aligned _BaseRidge._parameter_constraints with the standalone function by using "array-like", and replaced the coupled isinstance check in _ridge_regression with _is_arraylike_not_scalar.
All existing ridge tests pass, and I've verified the fix against a comprehensive new regression test suite covering multiple Array API backends.
lorentzenchr commentedon May 31, 2026
Fixed by #34004.