Skip to content

BUG loss of precision in LogisticRegression as of version 1.4 #28700

Closed

Description

@user799595

Describe the bug

Between version 1.3.2 and 1.4.0, LogisticRegression became less accurate.

Steps/Code to Reproduce

import numpy as np
import pandas as pd

import sklearn.pipeline
import sklearn.preprocessing
import sklearn.linear_model

df = pd.DataFrame({
    'age': [0, 1, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    'exiting':  [False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, True, False, False, False, False, False, False, False, False, False, False, False, True, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
})

data_timeline = np.arange(df['age'].max() + 1)

estimator = sklearn.pipeline.Pipeline(
    [
        (
            "onehot",
            sklearn.preprocessing.OneHotEncoder(
                categories=[data_timeline], sparse_output=False
            )
        ),
        (
            "logistic",
            sklearn.linear_model.LogisticRegression(
                fit_intercept=False, C=1e6, max_iter=1000, tol=1e-7, solver="newton-cg"
            ),
        ),
    ]
)

estimator.fit(df[['age']], df["exiting"])
def logistic_regression_gradient(X, y, y_hat, coef, C):
    return coef + C * (y_hat - y) @ X

gradient = logistic_regression_gradient(
    X=estimator.named_steps['onehot'].transform(df[['age']]),
    y=df["exiting"].astype(float).to_numpy(),
    y_hat=estimator.predict_proba(df[['age']])[:, 1],
    coef=estimator.named_steps["logistic"].coef_,
    C=estimator.named_steps['logistic'].C
)
print(sklearn.__version__)
print(gradient)

Expected Results

1.3.2
[[ 6.38057971e-06 -1.47032373e-02  3.23092176e-06 -1.86882858e-02
  -1.85588401e-02 -7.10504243e-05  8.47822321e-05 -1.58804369e-02
  -1.58804369e-02 -1.58804369e-02 -1.58804369e-02 -1.18021221e-02
  -2.76625890e-03 -2.76625890e-03 -2.76625890e-03 -2.76625890e-03
  -2.76625890e-03 -2.76625890e-03 -2.76625890e-03  0.00000000e+00
   2.22974349e-02  2.22974349e-02  2.22974349e-02  2.22974349e-02
   2.22974349e-02  2.22974349e-02  2.22974349e-02  2.22974349e-02
   2.22974349e-02  2.22974349e-02  2.22974349e-02  2.22974349e-02
   2.22974349e-02]]

Actual Results

1.4.0
[[ 2.68892818e-03  3.64025037e+00  6.76589138e-04  3.77020823e+00
   3.80372303e+00 -1.41805879e-04  1.51207953e-02  3.89408378e+00
   3.89408378e+00  3.89408378e+00  3.89408378e+00  3.96014198e+00
   4.05600402e+00  4.05600402e+00  4.05600402e+00  4.05600402e+00
   4.05600402e+00  4.05600402e+00  4.05600402e+00  0.00000000e+00
   4.22741992e+00  4.22741992e+00  4.22741992e+00  4.22741992e+00
   4.22741992e+00  4.22741992e+00  4.22741992e+00  4.22741992e+00
   4.22741992e+00  4.22741992e+00  4.22741992e+00  4.22741992e+00
   4.22741992e+00]]

Versions

System:
    python: 3.12.2 | packaged by conda-forge | (main, Feb 16 2024, 20:50:58) [GCC 12.3.0]
executable: ~/miniforge3/envs/sklearn-env/bin/python
   machine: Linux-6.8.1-arch1-1-x86_64-with-glibc2.39

Python dependencies:
      sklearn: 1.4.0
          pip: 24.0
   setuptools: 69.2.0
        numpy: 1.26.4
        scipy: 1.12.0
       Cython: 3.0.9
       pandas: 2.2.1
   matplotlib: None
       joblib: 1.3.2
threadpoolctl: 3.4.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libopenblas
       filepath: ~/miniforge3/envs/sklearn-env/lib/libopenblasp-r0.3.26.so
        version: 0.3.26
threading_layer: pthreads
   architecture: Zen

       user_api: openmp
   internal_api: openmp
    num_threads: 8
         prefix: libgomp
       filepath: ~/miniforge3/envs/sklearn-env/lib/libgomp.so.1.0.0
        version: None

Activity

  1. added
    Needs Triage
    on Mar 26, 2024
  2. jeremiedbb commented on Mar 26, 2024

    @jeremiedbb
    Member

    Hi @user799595, The change of behavior comes from this PR #26721 and has been documented in this changelog https://scikit-learn.org/stable/whats_new/v1.4.html#changed-models.

    The goal was to have a better convergence, in particular with the "newton-cg" solver, but you might have to adapt the parameters (e.g. tol). ping @lorentzenchr who will probably have better insights.

  3. lorentzenchr commented on Mar 26, 2024

    @lorentzenchr
    Member

    @jeremiedbb I'd have answered the same, so thanks.

    I tested it, and setting a smaller tol reduces the gradient significantly.

    Also note that the gradient from the code snippet has a different scaling/factor than the one implemented in LogisticRegression. Important for the given case is the huge C=1e6, which enters as inverse in LogisticRegression as sum loss + 1/C * penalty which, from a point of view of optimization, makes much more sense.

  4. ogrisel commented on Mar 26, 2024

    @ogrisel
    Member

    I tried with tol=1e-12 on the current main and I get:

    1.5.dev0
    [[ 7.07649050e-10  3.72818333e-07 -1.29261490e-10  4.96373966e-07
       5.70140248e-07  2.73745471e-11 -9.57811608e-12  8.01605017e-07
       8.01605017e-07  8.01605017e-07  8.01605017e-07  9.85129512e-07
       1.28843198e-06  1.28843198e-06  1.28843198e-06  1.28843198e-06
       1.28843198e-06  1.28843198e-06  1.28843198e-06  0.00000000e+00
       2.36813173e-06  2.36813173e-06  2.36813173e-06  2.36813173e-06
       2.36813173e-06  2.36813173e-06  2.36813173e-06  2.36813173e-06
       2.36813173e-06  2.36813173e-06  2.36813173e-06  2.36813173e-06
       2.36813173e-06]]
    

    but I can reproduce the very large gradient norm for tol=1e-7:

    1.5.dev0
    [[ 2.16078502e-03  3.64025049e+00 -4.96437499e-02  3.77020824e+00
       3.80372303e+00 -2.41174741e-04  3.06366990e-02  3.89408374e+00
       3.89408374e+00  3.89408374e+00  3.89408374e+00  3.96014194e+00
       4.05600398e+00  4.05600398e+00  4.05600398e+00  4.05600398e+00
       4.05600398e+00  4.05600398e+00  4.05600398e+00  0.00000000e+00
       4.22741995e+00  4.22741995e+00  4.22741995e+00  4.22741995e+00
       4.22741995e+00  4.22741995e+00  4.22741995e+00  4.22741995e+00
       4.22741995e+00  4.22741995e+00  4.22741995e+00  4.22741995e+00
       4.22741995e+00]]
    

    this is even larger than what @user799595 reports for 1.4.0.

  5. ogrisel commented on Mar 26, 2024

    @ogrisel
    Member

    I think the scaling between the loss terms should not have changed w.r.t. the meaning of C: the gradient should still be defined in the same way.

    However indeed the tolerance might need to be rescaled as the convergence criterion have changed. If you decrease tol by 2 orders of magnitude you should be able to get approximately the same gradient norm as previously.

  6. lorentzenchr commented on Mar 26, 2024

    @lorentzenchr
    Member

    I think the scaling between the loss terms should not have changed w.r.t. the meaning of C: the gradient should still be defined in the same way.

    I politely disagree as multiplying the loss by the penalty C instead of putting it inversely to the penalty is - hmm, forgive my language - just stupid for optimization, and an implementation detail.

  7. changed the title [-]Regression in LogisticRegression[/-] [+]BUG loss of precision in LogisticRegression as of version 1.4[/+] on Mar 26, 2024
  8. lorentzenchr commented on Mar 26, 2024

    @lorentzenchr
    Member

    BTW, what really matters are the coefficients. From tol=1e-7 to tol=1e-12, the max abs relative difference of coefficients is 0.026755317918426336, so roughly 3%. That seems ok.

  9. user799595 commented on Mar 26, 2024

    @user799595
    Author

    Thank you guys for looking into this!

    I've decreased the tolerance and that solved the issue.

    Sorry for not looking at the release notes first.

    Would it make sense to add this to the documentation? I'm happy to contribute if you think it's worthwhile.

  10. lorentzenchr commented on Mar 26, 2024

    @lorentzenchr
    Member

    What exactly do you suggest to add to the documentation?

  11. ogrisel commented on Mar 27, 2024

    @ogrisel
    Member

    I think the scaling between the loss terms should not have changed w.r.t. the meaning of C: the gradient should still be defined in the same way.

    I politely disagree as multiplying the loss by the penalty C instead of putting it inversely to the penalty is - hmm, forgive my language - just stupid for optimization, and an implementation detail.

    I only meant to say that changes made in #26721 should not impact the fact that coef + C * (y_hat - y) @ X is still the valid expression to compute the gradient from the public API parametrization of LogisticRegression both before and after #26721 as explained in the following inline comment https://github.com/scikit-learn/scikit-learn/pull/26721/files#diff-66422c7ed307653c80e5d68ed353d44d8fbb02319c428e140daff082eaf9d6cbR361.

  12. lorentzenchr commented on Mar 27, 2024

    @lorentzenchr
    Member

    We do not expose the gradient publicly. Maybe, we should change the use guide in https://scikit-learn.org/stable/modules/linear_model.html#binary-case. Liblinear is the only solver with that exact objective, all others are more consistent with the GLM formulation, Ridge and Lasso included.

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions