Repository navigation
Description
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:
LinearDiscriminantAnalysisreplaces zeros by the smallest normal number, so it returns a constant: -87.3 in float32, -708.4 in float64.LogisticRegressionreturns-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: TrueInterest 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
FIX Ensure finite, numerically stable predict_log_proba for binary mo…
FIX Ensure finite, numerically stable predict_log_proba for binary mo…
Charly21r commentedon Nov 24, 2026
Hi there! I looked into this a bit further. I tried to check which other estimators have the same
1 - pproblem you mentioned, whether multiclass is affected, and whether the proposed fix has any downsides. Everything below is onmain(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-infonce the true log-probability goes below about -745 (float64) or -104 (float32), and LDA hits itssmallest_normalfloor just like in the binary case:In float32, LDA returns -87.3 for all four points. The float32 case also isn't limited to extreme inputs: binary
LogisticRegressionreturns one-infwhen predicting on its ownmake_classification(5000)training data.So
[expit(-d), expit(d)]fixespredict_proba, butpredict_log_probashould work in log space directly:log_expitfor binary,log_softmaxfor multinomial, andlog_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_probaon well-separated data and predicted on far-out points. These are affected, in both the binary and the multiclass case:LogisticRegression,LogisticRegressionCV1 - pin_predict_proba_lr;np.log(softmax(...))SGDClassifier(loss="log_loss")_predict_proba_lr, thennp.logLinearDiscriminantAnalysis(stuck at -708.4 / -87.3)1 - porsoftmax, then thesmallest_normalfloorMLPClassifiervstack([1 - y_pred, y_pred]), thennp.logThe rest look fine. The NB models, QDA and
NearestCentroidalready work in log space, andSVCis bounded by Platt scaling.GradientBoostingClassifierhas the1 - ppattern, but I couldn't get it to trigger.CalibratedClassifierCVhas nopredict_log_probaand clips its inputs to[eps, 1-eps]. Trees andBaggingClassifierdo 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,SGDClassifierand_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 toutils/_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_softmaxexactly in float64 and float32, with no warnings. WithSCIPY_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, plustest_common.pyfor these estimators and their meta-estimators. I only hadarray_api_strictinstalled, not torch or cupy.The fix does change some numbers. Measured on 5000
make_classificationsamples (same for LR, LDA and SGD):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:
-inf, will get different values, so this should get a changelog entry.predict_probaunderflows,predict_log_probawill no longer equallog(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.
ansh-rohilla commentedon Nov 25, 2026
Hi @betatim and scikit-learn team,
I investigated this issue and put together a fix in log-space:
Root Cause: For binary classification,
predict_probacomputesp = expit(decision). For confident predictions where|decision|is large,1 - punderflows to0.0. Takinglog(p)produces-inf(and aRuntimeWarning: divide by zero) inLogisticRegression, or gets clamped to an arbitrary smallest normal constant floor (-87.33in float32,-708.40in float64) inLinearDiscriminantAnalysis.Proposed Solution:
_log_expitinsklearn.utils._array_api: Computes log-sigmoid directly usingscipy.special.log_expitfor NumPy and-xp.logaddexp(xp.asarray(0.0, dtype=x.dtype, device=device), -x)for Array API namespaces (fully compliant witharray_api_strictdevice rules).log_softmaxinsklearn.utils.extmath: Usesscipy.special.log_softmaxfor NumPy andX - xp.reshape(_logsumexp(X, axis=1, xp=xp), (-1, 1))for Array API.LinearClassifierMixin._predict_log_proba_lr: Computes binary log probabilities viaxp.stack([_log_expit(-prob, xp=xp), _log_expit(prob, xp=xp)], axis=1)and multiclass OvR in log-space vialog_prob - _logsumexp(log_prob, axis=1).LogisticRegression,LinearDiscriminantAnalysis, andSGDClassifier(loss="log_loss")to use these log-space calculations.I have this fully implemented and tested locally with all 1,064 tests passing across
linear_model,discriminant_analysis,extmath, andarray_api.Does this approach look good to proceed with reopening the PR?
MilindLate commentedon Nov 26, 2026
Here is a breakdown of the numerical properties and trade-offs of the proposed solution:
Precision asymmetry in the current code:
Currently,
_predict_proba_lrand LDA calculatep = expit(d)and return[1 - p, p]. In floating-point arithmetic, whend > 37in float64 (ord > 17in float32),expit(d)rounds to1.0because1 - expit(d) < eps_machine. Consequently,1 - pcancels to0.0. Taking the logarithm then yields-infinLogisticRegressionand a constant-708.396in LDA (due to thesmallest_normalclamp).Meanwhile, negative decisions retain non-zero probabilities down to
d = -709(expit(-709) ≈ 1e-308), making precision asymmetric between class 0 and class 1.Row sum preservation:
Evaluating
[expit(-d), expit(d)]restores symmetry. Across a sweep ofd in [-1000, 1000], the deviation ofexpit(-d) + expit(d)from1.0is at most2.22e-16(1 ULP) in float64 and1.19e-7in float32, which preserves standard simplex constraints.Exact log probabilities without underflow:
$$\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 < 0$$ $\exp$ is always $\le 0$ , so it cannot overflow, and log probabilities remain exact without underflowing to $|d| \ge 1000$ .
Evaluating
[log_expit(-d), log_expit(d)]directly inpredict_log_probaavoids intermediate underflow. Using:the argument to
-infeven forArray API support:
_log_expitcan be implemented branch-free for Array API without host-device synchronization:All 428 existing tests in
test_discriminant_analysis.pyandtest_logistic.pypass with this change. Happy to open a PR if this direction looks good to you!