Repository navigation
Closed
Labels
Description
Describe the bug
The intercept calculated by LogisticRegressionCV is wrong.
A bit related to #11865.
Steps/Code to Reproduce
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn.model_selection import StratifiedKFold
iris = load_iris()
X, y = iris.data, iris.target
lrcv = LogisticRegressionCV(solver="newton-cholesky").fit(X, y)
# exact same split as default LogisticRegressionCV
cv = StratifiedKFold(5)
folds = list(cv.split(X, y))
# First fold (index 0) and second C (index 1)
train_fold_0 = folds[0][0]
lr = LogisticRegression(
solver="newton-cholesky", C=lrcv.Cs_[1]
).fit(X[train_fold_0], y[train_fold_0])
# Compare coefficients without intercept for class 0
np.testing.assert_allclose(lrcv.coefs_paths_[0][0, 1, :-1], lr.coef_[0], rtol=1e-5)
# Now the intercept of class 0
np.testing.assert_allclose(lrcv.coefs_paths_[0][0, 1, -1], lr.intercept_[0], rtol=1e-5)It is also not related to the freedom to add a constant to coefficients: Probabilities are invariant under shifting all coefficients of a single feature j for all classes by the same amount c:
coef[k, :] -> coef[k, :] + c => proba stays the same
See
# Intercept for all classes
lr.intercept_
# array([ 0.35141429, -0.02662967, -0.32478462])
[lrcv.coefs_paths_[cla][0, 1, -1] for cla in range(3)]
# [0.33603135678054513, -0.04201515149357693, -0.2940162052869682]
# These are not related by a single constant.Expected Results
The LogisticRegression should reproduce the same result as the selected on from LogisticRegressionCV.
Actual Results
AssertionError:
Not equal to tolerance rtol=1e-05, atol=0
Mismatched elements: 1 / 1 (100%)
Max absolute difference among violations: 0.01538293
Max relative difference among violations: 0.04377435
ACTUAL: array(0.336031)
DESIRED: array(0.351414)
Versions
System:
python: 3.12.9 (main, Feb 4 2025, 14:38:38) [Clang 16.0.0 (clang-1600.0.26.6)]
executable: .../bin/python
machine: macOS-15.6.1-x86_64-i386-64bit
Python dependencies:
sklearn: 1.7.1
pip: 25.1.1
setuptools: 77.0.3
numpy: 2.1.3
scipy: 1.15.3
Cython: 3.0.12
pandas: 2.2.3
matplotlib: 3.10.1
joblib: 1.4.2
threadpoolctl: 3.6.0
Built with OpenMP: True
threadpoolctl info:
user_api: openmp
internal_api: openmp
num_threads: 8
prefix: libomp
filepath: .../lib/python3.12/site-packages/sklearn/.dylibs/libomp.dylib
version: None
Activity
TST add test_LogisticRegressionCV_on_folds to prove fixing of scikit-…
lorentzenchr commentedon Sep 2, 2025
This is in fact a duplicate of #31859 which was already fixed on main.