Skip to content

Alternative solvers for QuantileRegressor #20132

Open

Description

@glemaitre

QuantileRegressor has been implemented in #9978
However, it was reported to have an issue with large array of data where linear programming solvers require to form huge matrices for the optimization problem.

A potential solution is to have an online solver using partial_fit. However, it is not clear which solvers would be best to solve this issue.

Has proposed by @agramfort #9978 (comment), we should benchmark the different available solvers before making an implementation choice.

Pinging @RPyElec @avidale @agramfort @lorentzenchr @GaelVaroquaux that were involved in the discussion in the former pull-request.

Tasks:

Activity

  1. lorentzenchr commented on May 25, 2021

    @lorentzenchr
    Member

    Another route would be to allow for sparse input as several linprog methods can deal with that.

  2. glemaitre commented on May 25, 2021

    @glemaitre
    MemberAuthor

    Another route would be to allow for sparse input as several linprog methods can deal with that.

    This could be quite straightforward, I think.

  3. glemaitre commented on May 26, 2021

    @glemaitre
    MemberAuthor

    Regarding the sparse support I think that the following patch might be a good start (it passes some naive tests):

    Details
    --- a/sklearn/linear_model/_quantile.py
    +++ b/sklearn/linear_model/_quantile.py
    @@ -4,11 +4,13 @@
     import warnings
     
     import numpy as np
    +from scipy import sparse
     from scipy.optimize import linprog
     
     from ..base import BaseEstimator, RegressorMixin
     from ._base import LinearModel
     from ..exceptions import ConvergenceWarning
    +from ..utils import _safe_indexing
     from ..utils.validation import _check_sample_weight
     from ..utils.fixes import sp_version, parse_version
     
    @@ -116,7 +118,11 @@ class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator):
                 Returns self.
             """
             X, y = self._validate_data(
    -            X, y, accept_sparse=False, y_numeric=True, multi_output=False
    +            X,
    +            y,
    +            accept_sparse=["csr", "csc", "coo"],
    +            y_numeric=True,
    +            multi_output=False,
             )
             sample_weight = _check_sample_weight(sample_weight, X)
     
    @@ -210,13 +216,13 @@ class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator):
             #
             # Filtering out zero samples weights from the beginning makes life
             # easier for the linprog solver.
    -        mask = sample_weight != 0
    -        n_mask = int(np.sum(mask))  # use n_mask instead of n_samples
    +        indices = np.flatnonzero(sample_weight != 0)
    +        n_indices = len(indices)  # use n_mask instead of n_samples
             c = np.concatenate(
                 [
                     np.full(2 * n_params, fill_value=alpha),
    -                sample_weight[mask] * self.quantile,
    -                sample_weight[mask] * (1 - self.quantile),
    +                _safe_indexing(sample_weight, indices) * self.quantile,
    +                _safe_indexing(sample_weight, indices) * (1 - self.quantile),
                 ]
             )
             if self.fit_intercept:
    @@ -224,23 +230,31 @@ class QuantileRegressor(LinearModel, RegressorMixin, BaseEstimator):
                 c[0] = 0
                 c[n_params] = 0
     
    -            A_eq = np.concatenate(
    -                [
    -                    np.ones((n_mask, 1)),
    -                    X[mask],
    -                    -np.ones((n_mask, 1)),
    -                    -X[mask],
    -                    np.eye(n_mask),
    -                    -np.eye(n_mask),
    -                ],
    -                axis=1,
    -            )
    -        else:
    -            A_eq = np.concatenate(
    -                [X[mask], -X[mask], np.eye(n_mask), -np.eye(n_mask)], axis=1
    -            )
    +        X = _safe_indexing(X, indices)
     
    -        b_eq = y[mask]
    +        if sparse.issparse(X):
    +            sparse_constructor = {
    +                "csr": sparse.csr_matrix,
    +                "csc": sparse.csc_matrix,
    +                "coo": sparse.coo_matrix,
    +            }
    +            eye = sparse.eye(n_indices, dtype=X.dtype, format=X.format)
    +            if self.fit_intercept:
    +                ones = sparse_constructor[X.format](
    +                    np.ones(shape=(n_indices, 1), dtype=X.dtype)
    +                )
    +                A_eq = sparse.hstack([ones, X, -ones, -X, eye, -eye])
    +            else:
    +                A_eq = sparse.hstack([X, -X, eye, -eye])
    +        else:
    +            eye = np.eye(n_indices)
    +            if self.fit_intercept:
    +                ones = np.ones((n_indices, 1))
    +                A_eq = np.concatenate([ones, X, -ones, -X, eye, -eye], axis=1)
    +            else:
    +                A_eq = np.concatenate([X, -X, eye, -eye], axis=1)
    +
    +        b_eq = _safe_indexing(y, indices)
     
             result = linprog(
                 c=c,

    I personally do not want to open a PR right away because I already have plenty to finish up. Apart of the patch, the tests should be adapted to use some sparse input and make sure that sparse == dense.

  4. added
    Moderate
    on May 26, 2021
  5. glemaitre commented on Jun 14, 2021

    @glemaitre
    MemberAuthor

    I just got across the following paper: https://www.jmlr.org/papers/volume7/takeuchi06a/takeuchi06a.pdf

    The formulation is non-parametric, uses kernel and can be solved as a quadratic programming problem. It might possible to implement it via libsvm maybe.

  6. agramfort commented on Jun 15, 2021

    @agramfort
    Member

    @RPyElec @avidale thinking about it I think it makes more sense to add your stochastic solver to SGGRegressor as it also has the right API for stochastic solvers and it has all the machinery. It's "just" a matter of adding one more loss in the gradient computations.

  7. BatMrE commented on Aug 25, 2021

    @BatMrE

    Hi, if something specific need to be done on the implementation, can I work on it by creating a new PR??

  8. glemaitre commented on Aug 30, 2021

    @glemaitre
    MemberAuthor

    yes you can create a PR. The implementation for sparse input as I shown in the "details" section here: #20132 (comment)

    One would need to use this patch and implement additional tests to check the behaviour is the right one.

  9. venkyyuvy commented on Sep 18, 2021

    @venkyyuvy
    Contributor

    @BatMrE
    can I take this up ?

  10. BatMrE commented on Sep 19, 2021

    @BatMrE

    @BatMrE
    can I take this up ?

    Hi @venkyyuvy
    Yes you can, I am bit packed

  11. venkyyuvy commented on Dec 15, 2021

    @venkyyuvy
    Contributor

    @RPyElec @avidale thinking about it I think it makes more sense to add your stochastic solver to SGGRegressor as it also has the right API for stochastic solvers and it has all the machinery. It's "just" a matter of adding one more loss in the gradient computations.

    Is there any consensus for this?
    If so I would be interested in working on it.

  12. glemaitre commented on Dec 15, 2021

    @glemaitre
    MemberAuthor

    Is there any consensus for this?

    I agree with @agramfort to delegate the partial_fit to SGDRegressor.

  13. venkyyuvy commented on Dec 16, 2021

    @venkyyuvy
    Contributor

    Add a pin-ball loss function into SGDRegressor

    This is what I'm supposed to start with?

  14. lorentzenchr commented on Dec 16, 2021

    @lorentzenchr
    Member

    I have two questions:

    1. Does stochastic gradient descent work for non-smooth objective functions?
      I see that it seems to work for the Hinge loss.
    2. Do we want to use the common loss function module also for the SGDRegressor?
      The faster way is certainly to add the pinball loss to _sgd_fast.pyx.
  15. glemaitre commented on Dec 16, 2021

    @glemaitre
    MemberAuthor

    Do we want to use the common loss function module also for the SGDRegressor?
    The faster way is certainly to add the pinball loss to _sgd_fast.pyx.

    It is probably better to go for modifying directly _sgd_fast.pyx and in a later PR, refactor together all the losses using the common losses?

  16. lorentzenchr commented on Dec 16, 2021

    @lorentzenchr
    Member

    Do we want to use the common loss function module also for the SGDRegressor?
    The faster way is certainly to add the pinball loss to _sgd_fast.pyx.

    It is probably better to go for modifying directly _sgd_fast.pyx and in a later PR, refactor together all the losses using the common losses?

    As long as we use the exact same definition/version as in the common loss functions, it's fine.

  17. ogrisel commented on Mar 18, 2024

    @ogrisel
    Member

    For the record, Julien also mentioned the following NeurIPS 2023 paper in a discussion on discord:

    The performance results for look impressive although they do not compare against our solver.

    There is a benchmark script that could be updated to compare against our own HIGHS-based solver:

    It's based on the https://benchopt.github.io/ tool.

    Note: I am not 100% sure that it's possible our HIGHS-based l1-regularized QR solver vs the ReHLine-based l1+l2-regularized QR solver since, our l1 solver does not support l1+l2 penalization and the equations of the ReHLine paper solver seem to become singular when progressively setting the l2-regularization term to 0.

  18. changed the title [-]Follow-up of QuantileRegressor implementation[/-] [+]Alternative solvers for QuantileRegressor[/+] on Mar 18, 2024
  19. lorentzenchr commented on Apr 10, 2024

    @lorentzenchr
    Member

    The pinball loss will be easily available in SGD with #28049.

  20. moved this to Discussion in Losses and solverson May 17, 2024
  21. ogrisel commented on Jan 24, 2025

    @ogrisel
    Member

    It would be interesting to see if we can reuse the saga optimizer of Ridge to make it work for the pinball loss in QuantileRegressor with smooth (l2) penalty.

  22. benjareyesp-svg commented on Nov 25, 2026

    @benjareyesp-svg

    Hi! I'm Benjamin. My background is in data science and AI engineering, and most of my recent work has been in optimization and operations research. I'd like to help with this issue.

    With the default HiGHS solver, fit time grows much faster than the data (base M5 MacBook Pro, 20 features, quantile=0.9, alpha=0):

     n_samples   time (s)   peak MB
          1000       0.10       2.7
          5000       0.94      13.2
         20000      11.54      52.9
    

    The pinball loss has no Lipschitz gradient, so I replaced it with its Moreau envelope (a Huberized pinball with width delta) and minimized that with proximal SAGA, following @ogrisel's suggestion to try SAGA here.

    SAGA prototype, n_samples=1000
       delta   epochs to 1e-3 gap   best gap
         1.0                > 500    2.5e-02
         0.3                > 500    3.9e-03
         0.1                  100    7.5e-04
        0.03                  270    2.9e-04
    

    Large delta is fast but stalls at the smoothing bias. Small delta has no floor but needs more epochs.

    I also tried continuation, starting at delta=1.0 and dividing by 3 every k epochs with a warm start, down to 0.03:

    epochs/stage   epochs to 1e-3 gap   best gap
               3                  181    2.0e-04
               5                  103    2.3e-04
              10                   76    2.2e-04
              20                   65    2.2e-04
    

    With 10 to 20 epochs per stage, continuation reaches the target in 65 to 76 epochs versus 100 for the best fixed delta, and ends at a lower gap. This is one seed, one dataset size and alpha=0, so I'd treat it as a first signal. The prototype loops in pure Python, so I'm comparing epochs rather than wall time for now.

    Before going further, I'd like to check a few things:

    1. Is a SAGA solver still wanted? The discussion seemed to lean toward adding the pinball loss to SGDRegressor (Plan for SGD and SAGA loss function migration #28049), which doesn't appear to be on main yet, so I'd like to know whether this fits alongside that.
    2. Should delta be exposed to users, or handled internally through continuation?
    3. Should the smoothed loss go in sklearn/_loss so _sag_fast.pyx.tp can reuse it?

    Prototype with tests and benchmark.py: https://github.com/benjareyesp-svg/quantile-saga

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    ModerateNew Featurehelp wantedmodule:linear_model

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions