Skip to content

predict_log_proba of binary LinearDiscriminantAnalysis and LogisticRegression returns -inf or a constant for confident predictions #35490

Open

Description

@betatim

Warning

This issue is not yet ready for a PR. If you are interested in contributing to scikit-learn, please have a look at our contributing guidelines, and in particular the sections for new contributors and the "Needs triage" label.

I found this while working on array API support (#35053), where a new common check calls inference methods with float32 input. But, the bug is not specific to the array API, it happens with plain NumPy input as well.

I am posting this now without having dug into it more because the reproducer looks convincing and I am working on something else. The below text was written by Claude and claude is also the tool that found this bug. I've not spent time on thinking about the proposed solution. My first thought is that it seems a bit naive/that there must be downsides to doing it the proposed way. I wanted to post it already now so I don't forget about it. I'll review it in more detail later and close it if it turns out to be dumb.


Describe the bug and give evidence about its user-facing impact

For binary problems, LinearDiscriminantAnalysis.predict_proba and LinearClassifierMixin._predict_proba_lr (used by LogisticRegression and SGDClassifier) compute p = expit(decision) and return [1 - p, p]. For a large decision, expit(decision) rounds to exactly 1, so the probability of the other class becomes exactly 0 instead of a small but representable number.

predict_log_proba then takes the log of these probabilities:

  • LinearDiscriminantAnalysis replaces zeros by the smallest normal number, so it returns a constant: -87.3 in float32, -708.4 in float64.
  • LogisticRegression returns -inf (and emits a "divide by zero encountered in log" RuntimeWarning).

The correct value is log_expit(-decision), which is well defined. This happens for confident predictions on well-separated data, which is not an edge case: with float32 input it starts at a decision value of about 17, with float64 at about 37. Anything that uses log probabilities is affected: log-loss style scoring on predict_log_proba, ranking or thresholding on log probabilities, and code that sums log probabilities over samples (one -inf makes the sum -inf).

Steps/Code to Reproduce

import numpy as np
from scipy.special import log_expit
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.linear_model import LogisticRegression

X = np.array([[-3.0], [-2.0], [-1.0], [1.0], [2.0], [3.0]])
y = np.array([0, 0, 0, 1, 1, 1])

for dtype in [np.float32, np.float64]:
    for clf in [LinearDiscriminantAnalysis(), LogisticRegression()]:
        clf.fit(X.astype(dtype), y)
        X_test = np.array([[5.0], [20.0], [200.0]], dtype=dtype)
        decision = clf.decision_function(X_test)
        print(type(clf).__name__, np.dtype(dtype).name)
        print("  predict_log_proba[:, 0]:", clf.predict_log_proba(X_test)[:, 0])
        print("  log_expit(-decision):   ", log_expit(-decision.astype(np.float64)))

Expected Results

predict_log_proba[:, 0] matches log_expit(-decision), up to the precision of the input dtype.

Actual Results

LinearDiscriminantAnalysis float32
  predict_log_proba[:, 0]: [-87.33655 -87.33655 -87.33655]
  log_expit(-decision):    [  -30.00000191  -120.00000763 -1200.00012207]
LogisticRegression float32
  predict_log_proba[:, 0]: [-5.5255504       -inf       -inf]
  log_expit(-decision):    [  -5.52556369  -22.08628845 -220.86288452]
LinearDiscriminantAnalysis float64
  predict_log_proba[:, 0]: [ -30.00102056 -708.39641853 -708.39641853]
  log_expit(-decision):    [  -30.  -120. -1200.]
LogisticRegression float64
  predict_log_proba[:, 0]: [ -5.52556418 -22.08629003         -inf]
  log_expit(-decision):    [  -5.52556418  -22.08629043 -220.86290431]

LogisticRegression.predict_log_proba also emits RuntimeWarning: divide by zero encountered in log.

Versions

System:
    python: 3.14.6 | packaged by conda-forge | (main, Jun 12 2026, 08:47:56) [Clang 20.1.8 ]
   machine: macOS-26.7.1-arm64-arm-64bit-Mach-O
Python dependencies:
      sklearn: 1.10.dev0
          pip: 26.2.2
   setuptools: 81.0.0
        numpy: 2.5.0
        scipy: 1.18.0
       Cython: 3.2.5
       pandas: 3.0.6
   matplotlib: 3.11.2
       joblib: 1.5.3
threadpoolctl: 3.6.0
     narwhals: 2.23.0
Built with OpenMP: True

Interest in fixing the bug

Yes. Compute both columns directly instead of subtracting from 1: [expit(-d), expit(d)] in predict_proba, and [log_expit(-d), log_expit(d)] in predict_log_proba for the binary case, rather than taking the log of the probabilities. This applies to LinearDiscriminantAnalysis (sklearn/discriminant_analysis.py) and LinearClassifierMixin._predict_proba_lr (sklearn/linear_model/_base.py). The fix in the array API demo PR for LinearDiscriminantAnalysis uses the first part. Other estimators that compute 1 - p may need the same fix.

Activity

  1. added
    Needs Investigation
    on Nov 23, 2026
  2. Charly21r commented on Nov 24, 2026

    @Charly21r

    Hi there! I looked into this a bit further. I tried to check which other estimators have the same 1 - p problem you mentioned, whether multiclass is affected, and whether the proposed fix has any downsides. Everything below is on main (1.10.dev0, NumPy 2.5.5, SciPy 1.18.1).

    Hope this helps!

    Multiclass is also affected

    It's a different path but the same failure: np.log(softmax(decision)) underflows to -inf once the true log-probability goes below about -745 (float64) or -104 (float32), and LDA hits its smallest_normal floor just like in the binary case:

    import numpy as np
    from scipy.special import log_softmax
    from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
    from sklearn.linear_model import LogisticRegression
    
    np.set_printoptions(precision=2, suppress=True)
    rng = np.random.RandomState(0)
    X = np.vstack([c + rng.randn(30, 2) for c in [[-10, 0], [10, 0], [0, 10]]])
    y = np.repeat([0, 1, 2], 30)
    X_test = np.array([[-10, 0], [-100, 0], [-1000, 0], [-10000, 0]], dtype=float)
    
    for clf in [LogisticRegression(), LinearDiscriminantAnalysis()]:
        clf.fit(X, y)
        print(type(clf).__name__)
        print("  got:     ", clf.predict_log_proba(X_test)[:, 1])
        print("  expected:", log_softmax(clf.decision_function(X_test), axis=1)[:, 1])
    LogisticRegression
      got:      [ -9.11 -90.7    -inf   -inf]
      expected: [   -9.11   -90.7   -906.57 -9065.27]
    LinearDiscriminantAnalysis
      got:      [-194.38 -708.4  -708.4  -708.4 ]
      expected: [   -194.38   -1929.38  -19279.4  -192779.53]
    

    In float32, LDA returns -87.3 for all four points. The float32 case also isn't limited to extreme inputs: binary LogisticRegression returns one -inf when predicting on its own make_classification(5000) training data.

    So [expit(-d), expit(d)] fixes predict_proba, but predict_log_proba should work in log space directly: log_expit for binary, log_softmax for multinomial, and log_expit(d) - logsumexp(log_expit(d), axis=1) for the OvR branch of _predict_proba_lr.

    Other estimators

    I ran every classifier that has predict_log_proba on well-separated data and predicted on far-out points. These are affected, in both the binary and the multiclass case:

    Estimator Cause
    LogisticRegression, LogisticRegressionCV 1 - p in _predict_proba_lr; np.log(softmax(...))
    SGDClassifier(loss="log_loss") _predict_proba_lr, then np.log
    LinearDiscriminantAnalysis (stuck at -708.4 / -87.3) 1 - p or softmax, then the smallest_normal floor
    MLPClassifier vstack([1 - y_pred, y_pred]), then np.log

    The rest look fine. The NB models, QDA and NearestCentroid already work in log space, and SVC is bounded by Platt scaling. GradientBoostingClassifier has the 1 - p pattern, but I couldn't get it to trigger. CalibratedClassifierCV has no predict_log_proba and clips its inputs to [eps, 1-eps]. Trees and BaggingClassifier do return -inf, but that's correct for vote fractions.

    I haven't included the script I used for this to keep the comment manageable, but I can share it if useful.

    Does the fix break anything?

    I tried the log-space version on LDA, LogisticRegression, SGDClassifier and _predict_proba_lr. I left MLP out, since it would need the pre-activation output. For the array API path I added two small helpers to utils/_array_api.py: _log_expit (as -xp.logaddexp(0, -x)) and _log_softmax (on top of the existing _logsumexp).

    With those changes, your reproducer and the one above match log_expit / log_softmax exactly in float64 and float32, with no warnings. With SCIPY_ARRAY_API=1, 3473 tests pass and 0 fail. That covers the LDA, logistic, SGD, linear-model base, array API, calibration and multiclass test files, plus test_common.py for these estimators and their meta-estimators. I only had array_api_strict installed, not torch or cupy.

    The fix does change some numbers. Measured on 5000 make_classification samples (same for LR, LDA and SGD):

    before after
    binary rows with sum != 1.0 0% ~23% (1 ulp)
    max |predict_log_proba - log(predict_proba)| 0 1.8e-15 (f64), 9.5e-7 (f32)
    argmax(predict_proba) == predict 100% 100%

    Multiclass already has ~25% of rows that don't sum to exactly 1.0, so the binary case just catches up. Beyond that, I see two things worth weighing:

    • Anyone relying on LDA's finite floor, or on exact 0 / -inf, will get different values, so this should get a changelog entry.
    • Where predict_proba underflows, predict_log_proba will no longer equal log(predict_proba). That's the point of the fix, but the common check describes one as a transformation of the other.

    A note on the implementation experiment: I used Claude to help with parts of the implementation of the fix. My goal was to quickly validate whether the proposed approach would work in practice and identify potential regressions, rather than to prepare a patch for submission. I ran the tests and numerical experiments myself and am sharing the results in case they're useful for evaluating the proposed fix.

  3. ansh-rohilla commented on Nov 25, 2026

    @ansh-rohilla

    Hi @betatim and scikit-learn team,

    I investigated this issue and put together a fix in log-space:

    1. Root Cause: For binary classification, predict_proba computes p = expit(decision). For confident predictions where |decision| is large, 1 - p underflows to 0.0. Taking log(p) produces -inf (and a RuntimeWarning: divide by zero) in LogisticRegression, or gets clamped to an arbitrary smallest normal constant floor (-87.33 in float32, -708.40 in float64) in LinearDiscriminantAnalysis.

    2. Proposed Solution:

      • _log_expit in sklearn.utils._array_api: Computes log-sigmoid directly using scipy.special.log_expit for NumPy and -xp.logaddexp(xp.asarray(0.0, dtype=x.dtype, device=device), -x) for Array API namespaces (fully compliant with array_api_strict device rules).
      • log_softmax in sklearn.utils.extmath: Uses scipy.special.log_softmax for NumPy and X - xp.reshape(_logsumexp(X, axis=1, xp=xp), (-1, 1)) for Array API.
      • LinearClassifierMixin._predict_log_proba_lr: Computes binary log probabilities via xp.stack([_log_expit(-prob, xp=xp), _log_expit(prob, xp=xp)], axis=1) and multiclass OvR in log-space via log_prob - _logsumexp(log_prob, axis=1).
      • Updated LogisticRegression, LinearDiscriminantAnalysis, and SGDClassifier(loss="log_loss") to use these log-space calculations.
      • Added regression tests for float32 and float64 extreme values in both binary and multiclass setups.

    I have this fully implemented and tested locally with all 1,064 tests passing across linear_model, discriminant_analysis, extmath, and array_api.

    Does this approach look good to proceed with reopening the PR?

  4. MilindLate commented on Nov 26, 2026

    @MilindLate

    Here is a breakdown of the numerical properties and trade-offs of the proposed solution:

    1. Precision asymmetry in the current code:
      Currently, _predict_proba_lr and LDA calculate p = expit(d) and return [1 - p, p]. In floating-point arithmetic, when d > 37 in float64 (or d > 17 in float32), expit(d) rounds to 1.0 because 1 - expit(d) < eps_machine. Consequently, 1 - p cancels to 0.0. Taking the logarithm then yields -inf in LogisticRegression and a constant -708.396 in LDA (due to the smallest_normal clamp).
      Meanwhile, negative decisions retain non-zero probabilities down to d = -709 (expit(-709) ≈ 1e-308), making precision asymmetric between class 0 and class 1.

    2. Row sum preservation:
      Evaluating [expit(-d), expit(d)] restores symmetry. Across a sweep of d in [-1000, 1000], the deviation of expit(-d) + expit(d) from 1.0 is at most 2.22e-16 (1 ULP) in float64 and 1.19e-7 in float32, which preserves standard simplex constraints.

    3. Exact log probabilities without underflow:
      Evaluating [log_expit(-d), log_expit(d)] directly in predict_log_proba avoids intermediate underflow. Using:
      $$\log(\text{expit}(x)) = -\log1p(e^{-x}) \quad \text{for } x \ge 0$$
      $$\log(\text{expit}(x)) = x - \log1p(e^x) \quad \text{for } x &lt; 0$$
      the argument to $\exp$ is always $\le 0$, so it cannot overflow, and log probabilities remain exact without underflowing to -inf even for $|d| \ge 1000$.

    4. Array API support:
      _log_expit can be implemented branch-free for Array API without host-device synchronization:

      pos_mask = x >= 0
      x_neg = xp.where(pos_mask, -x, x)
      log1p_val = xp.log1p(xp.exp(x_neg))
      return xp.where(pos_mask, -log1p_val, x - log1p_val)

    All 428 existing tests in test_discriminant_analysis.py and test_logistic.py pass with this change. Happy to open a PR if this direction looks good to you!

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

    BugNeeds Investigation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions