Repository navigation
FIX ridge validation of alphas with array api - #34004
Conversation
|
Looks like the failure on macOS is with pytorch MPS because one element of the array is too different. Maybe a precision problem. Running the CUDA tests to see what they say while I think about the macOS failure and the PR. |
|
Thanks for making the PR. I think the only thing we need to discuss is if we want to allow However, for argument to estimators (like So at the moment I am thinking we should be quite flexible with what we accept for hyper-parameters. For example, we could say that any "array-like" would be fine and take care of the conversion. In some sense that would be consistent with the "everything follows Conclusion: I'd accept this change. Homework for this PR: make it so that The homework for a new PR: make sure we have a common check that enforces this. What do the other array API people think? @ogrisel @lucyleeow @virchan |
| assert_allclose(move_to(pred_xp, xp=np, device="cpu"), pred_np) | ||
|
|
||
| # check that passing the same array type for alpha also works as expected | ||
| estimator = Ridge(alpha=xp.asarray(alphas), solver="svd") |
There was a problem hiding this comment.
I would have expected the following:
| estimator = Ridge(alpha=xp.asarray(alphas), solver="svd") | |
| estimator = Ridge(alpha=xp.asarray(alphas, device=device), solver="svd") |
Using the implicit default device should work on most libraries, but I am not sure if it will continue working in the future for libraries such as array-api-strict.
There was a problem hiding this comment.
If we allow "all the array-likes" then it shouldn't matter if you specify a device here or not/what device this is on. Using torch + a device that doesn't match the device of X should work just as well as using a ndarray here.
|
General question if we are happy for array-like hyperparameters to be converted by the estimator, should we add a common test that checks all 'array-like' inputs are converted...? |
That might be a good idea but in practice it might be challenging to find suitable array values in an estimator agnostic manner. Maybe we could inspect the range of valid value expressed in parameters validation constraints, but they might not be specific enough and require setting extra non default hparams. Alternatively we could specify explicit array hparams values in |
|
That's a good point. Do you think we could make some heuristics using the default value? E.g., default value of alpha in |
| # There should be either 1 or n_targets penalties | ||
| alpha = _ravel(xp.asarray(alpha, device=device_, dtype=X.dtype), xp=xp) |
There was a problem hiding this comment.
Here's what happens to alpha in _ridge_regression
There was a problem hiding this comment.
For example, we could say that any "array-like" would be fine and take care of the conversion.
@betatim, I agree and it looks like this what's already implemented
|
Not sure how to handle the mps failure and also note that putting _________________________________________ test_ridge_per_target_alpha_array_api[torch-cpu-float32] _________________________________________
array_namespace = 'torch', device_name = 'cpu', dtype_name = 'float32'
@pytest.mark.parametrize(
"array_namespace, device_name, dtype_name",
yield_namespace_device_dtype_combinations(),
)
def test_ridge_per_target_alpha_array_api(array_namespace, device_name, dtype_name):
# non-regression test for #34003, where passing a array-like for alpha was
# not working with array API dispatch
xp, device = _array_api_for_tests(array_namespace, device_name, dtype_name)
X, y = make_regression(n_targets=3, n_features=100, random_state=0)
X_np = X.astype(dtype_name)
y_np = y.astype(dtype_name)
alphas = np.asarray([1e-2, 0.1, 1.0], dtype=dtype_name)
estimator = Ridge(alpha=alphas, solver="svd")
ridge_np = estimator.fit(X_np, y_np)
pred_np = ridge_np.predict(X_np)
with config_context(array_api_dispatch=True):
X_xp, y_xp = xp.asarray(X_np, device=device), xp.asarray(y_np, device=device)
# check that passing a numpy array for alpha works as expected
estimator = Ridge(alpha=alphas, solver="svd")
ridge_xp = estimator.fit(X_xp, y_xp)
pred_xp = ridge_xp.predict(X_xp)
assert pred_xp.shape == pred_np.shape == y.shape
> assert_allclose(move_to(pred_xp, xp=np, device="cpu"), pred_np)
sklearn/linear_model/tests/test_ridge.py:1530:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
actual = array([[ 8.97728577e+01, 8.07121582e+01, -6.99864044e+01],
[-2.06915024e+02, -3.41886566e+02, -2.91464203e+02]...876e+01, -7.56005325e+01, -1.04415405e+02],
[ 2.14425491e+02, 9.88522263e+01, 2.31183105e+02]], dtype=float32)
desired = array([[ 8.97727127e+01, 8.07121582e+01, -6.99864273e+01],
[-2.06914932e+02, -3.41886475e+02, -2.91464264e+02]...549e+01, -7.56003265e+01, -1.04415276e+02],
[ 2.14425369e+02, 9.88519516e+01, 2.31182877e+02]], dtype=float32)
rtol = 0.0001, atol = 0.0, equal_nan = True, err_msg = '', verbose = True
def assert_allclose(
actual, desired, rtol=None, atol=0.0, equal_nan=True, err_msg="", verbose=True
):
"""dtype-aware variant of numpy.testing.assert_allclose
This variant introspects the least precise floating point dtype
in the input argument and automatically sets the relative tolerance
parameter to 1e-4 float32 and use 1e-7 otherwise (typically float64
in scikit-learn).
`atol` is always left to 0. by default. It should be adjusted manually
to an assertion-specific value in case there are null values expected
in `desired`.
The aggregate tolerance is `atol + rtol * abs(desired)`.
Parameters
----------
actual : array_like
Array obtained.
desired : array_like
Array desired.
rtol : float, optional, default=None
Relative tolerance.
If None, it is set based on the provided arrays' dtypes.
atol : float, optional, default=0.
Absolute tolerance.
equal_nan : bool, optional, default=True
If True, NaNs will compare equal.
err_msg : str, optional, default=''
The error message to be printed in case of failure.
verbose : bool, optional, default=True
If True, the conflicting values are appended to the error message.
Raises
------
AssertionError
If actual and desired are not equal up to specified precision.
See Also
--------
numpy.testing.assert_allclose
Examples
--------
>>> import numpy as np
>>> from sklearn.utils._testing import assert_allclose
>>> x = [1e-5, 1e-3, 1e-1]
>>> y = np.arccos(np.cos(x))
>>> assert_allclose(x, y, rtol=1e-5, atol=0)
>>> a = np.full(shape=10, fill_value=1e-5, dtype=np.float32)
>>> assert_allclose(a, 1e-5)
"""
dtypes = []
actual, desired = np.asanyarray(actual), np.asanyarray(desired)
dtypes = [actual.dtype, desired.dtype]
if rtol is None:
rtols = [1e-4 if dtype == np.float32 else 1e-7 for dtype in dtypes]
rtol = max(rtols)
> np_assert_allclose(
actual,
desired,
rtol=rtol,
atol=atol,
equal_nan=equal_nan,
err_msg=err_msg,
verbose=verbose,
)
E AssertionError:
E Not equal to tolerance rtol=0.0001, atol=0
E
E Mismatched elements: 3 / 300 (1%)
E Max absolute difference among violations: 0.00036526
E Max relative difference among violations: 0.00071551
E ACTUAL: array([[ 8.977286e+01, 8.071216e+01, -6.998640e+01],
E [-2.069150e+02, -3.418866e+02, -2.914642e+02],
E [ 1.699422e+02, 1.885383e+02, 8.361436e+01],...
E DESIRED: array([[ 8.977271e+01, 8.071216e+01, -6.998643e+01],
E [-2.069149e+02, -3.418865e+02, -2.914643e+02],
E [ 1.699422e+02, 1.885384e+02, 8.361426e+01],...
sklearn/utils/_testing.py:236: AssertionError
========================================================= short test summary info ==========================================================
FAILED sklearn/linear_model/tests/test_ridge.py::test_ridge_per_target_alpha_array_api[torch-cpu-float32] - AssertionError: As I am not clear on what's the expected violation/policy, happy to invesigate with a few rules in mind. |
|
I think the |
jeremiedbb
left a comment
There was a problem hiding this comment.
All green now. LGTM, thanks.
|
Thanks a lot for fixing the tests ! |
Co-authored-by: Jérémie du Boisberranger <[email protected]>
Co-authored-by: Jérémie du Boisberranger <[email protected]>
Fix for #34003
Allows to pass both
np.arrayand an array of the same type as fit data asalphas.Add non regression tests.
Need to add non-regression tests