Repository navigation
FEAT Ridge: specify individual coefficients for positive constraint - #31031
thedanindanger wants to merge 7 commits into
Conversation
❌ Linting issuesThis PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling You can see the details of the linting issues under the
|
adrinjalali
left a comment
There was a problem hiding this comment.
Overall LGTM, but I defer to @lorentzenchr and @antoinebaker for a more detailed review.
There was a problem hiding this comment.
This example needs to be improved in the sense of having explanation of what's happening before each cell, to give a more notebook visual feeling to the reader, rather than a large block of text and then code.
There was a problem hiding this comment.
@adrinjalali thank you for the review, much appreciated.
Regarding the example, I am happy to update it with more context. Sorry to ask, but this is my first PR to scikit-learn, is it more appropriate to update it as a part of this PR, or keep this PR as-is and add a DOC request issue for subsequent PR?
There was a problem hiding this comment.
@adrinjalali I see other people pushed these types of changes during the PR, so I went ahead and updated the doc as you requested.
Expanded the example to show how the lbfgs solver is impacted by different alpha levels, as well as a recreation of the lbfgs solver to show it is similar to default ridge at higher alpha values.
Sidenote, the results are very different between the solvers at lower alpha. (~0.001 and lower for non & partial constrained, less than 0.01 fully constrained.) It might be worth considering a future enhancement warning the user about a lower alpha level when present in lbfgs solutions.
0a1bb23 to
648c736
Compare
…and add example for visualization
…ts and enhance error messaging
…apabilies DOC: added 31031.feature.rst to changelog
-- note: small formatting fix on test_ridge_loo_cv_asym_scoring not related to changes in this PR, automatically applied due to RUFF linting
- slightly redundant, but help future compatibility if _solve_lbfgs is reused in other _ridge.py objects - add tests for positive list input scenarios
…coefficient stability under positive constraints
648c736 to
678e634
Compare
antoinebaker
left a comment
There was a problem hiding this comment.
Thanks for the PR @thedanindanger, here a couple of first comments.
| information depending on the solver used. | ||
|
|
||
| positive : bool, default=False | ||
| positive : bool or list of bool, default=False |
There was a problem hiding this comment.
Maybe we should allow for array_like instead of just list ?
I don't have a strong opinion here, WDYT @adrinjalali ?
| positive : bool or list of bool, default=False | |
| positive : bool or array_like of shape (n_features,), default=False |
| solver = resolve_solver(solver, positive, return_intercept, X_is_sparse, xp) | ||
| if isinstance(positive, bool): | ||
| _positive = positive | ||
| elif isinstance(positive, list): |
There was a problem hiding this comment.
If we allow for generic array_like, this would need to be relaxed. Maybe using _is_arraylike from sklearn.utils.validation.
| if isinstance(positive, bool): | ||
| if positive: | ||
| config["bounds"] = [(0, np.inf)] * n_features | ||
| elif isinstance(positive, list): | ||
| if len(positive) != n_features: | ||
| raise ValueError( | ||
| "Length of 'positive' list must be equal to the number of features" | ||
| ) | ||
| elif not all(isinstance(p, bool) for p in positive): | ||
| raise ValueError( | ||
| "'positive' must be either a boolean or a list of booleans" | ||
| ) | ||
| config["bounds"] = [(0, np.inf) if p else (None, None) for p in positive] | ||
| else: | ||
| raise ValueError("'positive' must be either a boolean or a list of booleans") |
There was a problem hiding this comment.
I think the validation of positive (bool or list of bool of length n_features) is done twice, here and in _ridge_regression.
There was a problem hiding this comment.
I was unsure if it should be repeated, in case _solve_lbfgs was called elsewhere.
If there was not validation on the positive parameter originally, then it is safe to eliminate the validation in the update as well? Sorry if I was being overly cautious.
| raise ValueError( | ||
| "'positive' must be either a boolean or a list of booleans" | ||
| ) | ||
| _positive = True |
There was a problem hiding this comment.
I think here you would get _positive=True even if positive=[False]*n_features (all False, so no positivity constraint). Maybe:
| _positive = True | |
| _positive = any(positive) |
There was a problem hiding this comment.
@antoinebaker the _positive was intended to replace positive parameter checks.
E.g. if positive and solver != "lbfgs"
becomes if _positive and solver != "lbfgs"
This keeps us from modifying the code when calling the lbfgs solver
elif solver == "lbfgs":
coef = _solve_lbfgs(
X,
y,
alpha,
positive=positive,
tol=tol,
max_iter=max_iter,
X_offset=X_offset,
X_scale=X_scale,
sample_weight_sqrt=sample_weight_sqrt if has_sw else None,
)But you raise a great point. If someone were to pass positive = [False, False, False], there is no reason to force the lbfgs solver.
I think we could remove this check entirely and change the validations to, e.g.:
``if any(positive) and solver != "lbfgs"`
As you suggested.
Would their be any unintended consequences?
We could also remove some tests, but the current tests might need to be updated.
There was a problem hiding this comment.
Actually, really good catch, it would be natural to use [False] when given the option for an list/array-like param.
Assuming they used the default 'auto' solver, resolve_solver would return lbfgs solver.
Regardless of how equivalent the output would have been, it is not the intended behavior.
|
|
||
| coef_lbfgs_single_bool = _solve_lbfgs(X, y, alpha, **config_single_bool) | ||
| coef_lbfgs_list_bool = _solve_lbfgs(X, y, alpha, **config_list_bool) | ||
| assert_allclose(coef_lbfgs_single_bool, coef_lbfgs_list_bool, atol=1e-4, rtol=0) |
There was a problem hiding this comment.
Does it pass with the default atol and rtol ?
| assert_allclose(coef_lbfgs_single_bool, coef_lbfgs_list_bool, atol=1e-4, rtol=0) | |
| assert_allclose(coef_lbfgs_single_bool, coef_lbfgs_list_bool) |
| @pytest.mark.parametrize("positive", [[True, True]]) | ||
| def test_ridge_positive_list_type_test(positive): | ||
| """ | ||
| Test that Ridge raises ValueError when positive is List | ||
| and all values within positive list are boolean. | ||
| """ | ||
| X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) | ||
| coef = np.array([1, -10]) | ||
| y = X.dot(coef) | ||
| model = Ridge(positive=positive, solver="lbfgs") | ||
| model.fit(X, y) |
There was a problem hiding this comment.
It seems that this test is redundant with test_ridge_positive_list_length_test and the docstring misleading.
|
Note, CI check is failing due to what appears to be an unrelated change, referenced in Issue: #31098 |
Co-authored-by: antoinebaker <[email protected]>
|
Hi @thedanindanger, are you planning to continue working on this PR ? Otherwise I'd be interested in taking it over. |
In linear_model.Ridge, enables specifying the coefficients to constrain as positive only.
Reference Issues/PRs
Enhancement of feature implemented in PR: #19772
This is a feature available in other implementations such as GLMNET in R and has been requested in some capacity on stackoverflow, although searching the issues did not surface a particular ticket.
What does this implement/fix? Explain your changes.
Updated 'positive' parameter in BaseRidge class to accept either single boolean or an list of boolean values. List corresponds to X feature input.
Param validation was updated to accept an array like object and exception added if 'positive' is list and is not the same length as as shape[1] of X input matrix.
Highlighted Feature Code Changes:
file:
sklearn/linear_model/_ridge.pyfunction:
_solve_lbfgscurrent versionoriginal, constructs list of 'True' bools if param
positiveis True:updated, retains existing capability, plus allows user to submit list of bools to isolate certain variables for non-negative constraint:
Additional Changes
positiveparameter to accept 'array-like' valuestest_lbfgs_positive_listtest_lbfgs_positive_list_error_lengthtest_lbfgs_positive_list_error_typetest_lbfgs_positive_error_typetest_ridge_positive_list_type_error_testtest_ridge_positive_list_length_error_testtest_ridge_positive_list_length_testFuture Enhancements
Feature could easily be extended to accept list of constraints as well as bools; however, test surface would expand greatly and other algorithms are likely more appropriate for more specific constrained calculations.