Skip to content

FEAT Ridge: specify individual coefficients for positive constraint - #31031

Open
thedanindanger wants to merge 7 commits into
scikit-learn:mainfrom
thedanindanger:feature/specify-positive-coefficients-ridge
Open

thedanindanger wants to merge 7 commits into
scikit-learn:mainfrom
thedanindanger:feature/specify-positive-coefficients-ridge

Conversation

@thedanindanger

@thedanindanger thedanindanger commented Mar 19, 2025 •

Copy link
Copy Markdown

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.py

function: _solve_lbfgs current version

original, constructs list of 'True' bools if param positive is True:

    if positive:
        config["bounds"] = [(0, np.inf)] * n_features

updated, retains existing capability, plus allows user to submit list of bools to isolate certain variables for non-negative constraint:

    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")

Additional Changes

  1. ridge.py data validation positive parameter to accept 'array-like' values
  2. Updated docstrings in Ridge class and _ridge_regression function
  3. test_ridge.py tests
  • test_lbfgs_positive_list
  • test_lbfgs_positive_list_error_length
  • test_lbfgs_positive_list_error_type
  • test_lbfgs_positive_error_type
  • test_ridge_positive_list_type_error_test
  • test_ridge_positive_list_length_error_test
  • test_ridge_positive_list_length_test
  1. Added 31031.feature.rst to upcoming changes
  2. Added examples/linear_model/plot_ridge_path_specify_non_negative.py

Future 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.

@github-actions

github-actions Bot commented Mar 19, 2025 •

Copy link
Copy Markdown

❌ Linting issues

This PR is introducing linting issues. Here's a summary of the issues. Note that you can avoid having linting issues by enabling pre-commit hooks. Instructions to enable them can be found here.

You can see the details of the linting issues under the lint job here


ruff

ruff detected issues. Please run ruff check --fix --output-format=full locally, fix the remaining issues, and push the changes. Here you can see the detected issues. Note that the installed ruff version is ruff=0.11.0.

Details

sklearn/linear_model/_ridge.py:528:51: W291 Trailing whitespace
    |
526 |     positive : bool or list of bool, default=False
527 |         When set to ``True``, forces the coefficients to be positive.
528 |         Positivity constraint on the coefficients. 
    |                                                   ^ W291
529 |         If True, forces all coefficients to be positive.
530 |         If False, no constraint is enforced.
    |
    = help: Remove trailing whitespace

sklearn/linear_model/_ridge.py:531:79: W291 Trailing whitespace
    |
529 |         If True, forces all coefficients to be positive.
530 |         If False, no constraint is enforced.
531 |         If list of length `n_features`, the positivity constraint is specified 
    |                                                                               ^ W291
532 |         for each feature, forcing the corresponding coefficient to be positive.
533 |         Only 'lbfgs' solver is supported in this case.
    |
    = help: Remove trailing whitespace

Found 2 errors.
No fixes available (2 hidden fixes can be enabled with the `--unsafe-fixes` option).

Generated for commit: cf7b14c. Link to the linter CI: here

@thedanindanger thedanindanger changed the title Feature/specify positive coefficients ridge FEAT Ridge: specify individual coefficients for positive constraint Mar 20, 2025

@adrinjalali adrinjalali left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM, but I defer to @lorentzenchr and @antoinebaker for a more detailed review.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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?

@thedanindanger thedanindanger Mar 25, 2025 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ogrisel might be interested in this.

@thedanindanger
thedanindanger force-pushed the feature/specify-positive-coefficients-ridge branch from 0a1bb23 to 648c736 Compare March 25, 2025 23:22
TheoryLaneAdmin and others added 6 commits March 27, 2025 10:51
…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
@thedanindanger
thedanindanger force-pushed the feature/specify-positive-coefficients-ridge branch from 648c736 to 678e634 Compare March 27, 2025 15:51

@antoinebaker antoinebaker left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe we should allow for array_like instead of just list ?
I don't have a strong opinion here, WDYT @adrinjalali ?

Suggested change
positive : bool or list of bool, default=False
positive : bool or array_like of shape (n_features,), default=False

Comment thread sklearn/linear_model/_ridge.py Resolved
solver = resolve_solver(solver, positive, return_intercept, X_is_sparse, xp)
if isinstance(positive, bool):
_positive = positive
elif isinstance(positive, list):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we allow for generic array_like, this would need to be relaxed. Maybe using _is_arraylike from sklearn.utils.validation.

Comment on lines +328 to +342
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")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the validation of positive (bool or list of bool of length n_features) is done twice, here and in _ridge_regression.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here you would get _positive=True even if positive=[False]*n_features (all False, so no positivity constraint). Maybe:

Suggested change
_positive = True
_positive = any(positive)

@thedanindanger thedanindanger Mar 28, 2025 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it pass with the default atol and rtol ?

Suggested change
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)

Comment on lines +2033 to +2043
@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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems that this test is redundant with test_ridge_positive_list_length_test and the docstring misleading.

@thedanindanger

Copy link
Copy Markdown
Author

Note, CI check is failing due to what appears to be an unrelated change, referenced in Issue: #31098

@FrancoisPgm

Copy link
Copy Markdown
Member

Hi @thedanindanger, are you planning to continue working on this PR ? Otherwise I'd be interested in taking it over.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants