Logistic regression in Python is the first classifier worth learning well, because it gives you both a prediction and an explanation: a probability for each case and an odds ratio for each feature. This tutorial fits one to the Pima Indians diabetes data (768 women, 8 measurements, one yes/no outcome), measures it against a baseline, tests three popular “improvements” that turn out not to help, and shows what changing the decision threshold really does. Everything ran on 23 November 2026 with Python 3.13, scikit-learn 1.9.1 and pandas 3.0.5. The data is for teaching only; nothing here is medical advice.
The data and the baseline
The file comes from a public GitHub copy of the data set, originally collected by the US National Institute of Diabetes and Digestive and Kidney Diseases. 34.9% of the 768 patients have diabetes, so a model that always answers “no” is right 65.1% of the time. That is the number to beat. One more thing to know before modelling: several columns use 0 for “not measured”. Blood pressure, skin thickness, insulin and BMI cannot really be 0, yet there are 35, 227, 374 and 11 such rows, plus 5 for glucose.
import numpy as np, pandas as pd
from sklearn.model_selection import RepeatedStratifiedKFold, cross_val_score, cross_val_predict
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import precision_score, recall_score, roc_auc_score, confusion_matrix
URL = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/pima-indians-diabetes.data.csv"
cols = ["pregnancies", "glucose", "blood_pressure", "skin_thickness", "insulin", "bmi", "pedigree", "age", "diabetes"]
df = pd.read_csv(URL, names=cols)
print(df.shape, "diabetes", round(df.diabetes.mean(), 3))
zeros = (df[["glucose", "blood_pressure", "skin_thickness", "insulin", "bmi"]] == 0).sum().to_dict()
print("zeros that cannot be real:", zeros)(768, 9) diabetes 0.349
zeros that cannot be real: {'glucose': 5, 'blood_pressure': 35, 'skin_thickness': 227, 'insulin': 374, 'bmi': 11}Fit logistic regression in Python, and test the usual advice
A single train/test split on 768 rows is too noisy to compare options, so we use five-fold cross-validation repeated five times (25 scores per model). We try three versions: the raw data with no scaling, the data with scaling, and the data with the impossible zeros treated as missing values (filled with the median) and then scaled.
y = df.diabetes
cv = RepeatedStratifiedKFold(n_splits=5, n_repeats=5, random_state=0)
def acc(X, model):
s = cross_val_score(model, X, y, cv=cv); return round(s.mean(), 3), round(s.std(), 3)
print("majority", round(1 - y.mean(), 3))
raw = df.drop(columns="diabetes")
print("raw, no scaling ", acc(raw, LogisticRegression(max_iter=5000)))
clean = raw.copy()
for c in ["glucose", "blood_pressure", "skin_thickness", "insulin", "bmi"]:
clean[c] = clean[c].replace(0, np.nan)
model = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression(max_iter=1000))
print("zeros as missing ", acc(clean, model))
print("zeros kept, scaled", acc(raw, make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))))majority 0.651
raw, no scaling (0.777, 0.026)
zeros as missing (0.768, 0.025)
zeros kept, scaled (0.777, 0.023)All three beat the 65.1% baseline by about 12 points, and the surprise is that the “cleaner” version scores slightly lower (76.8% against 77.7%). With standard deviations of about 2.5 points across folds, none of the three differs reliably. Two lessons: first, do not assume a cleaning step helps because it sounds right, measure it; second, scaling made no difference to accuracy in this test. It still matters for interpretation, which is the next step.
Read the model: odds ratios
Logistic regression models the log-odds of the outcome as a straight-line combination of the features. Taking the exponent of each coefficient gives an odds ratio. Because we scaled every column, each odds ratio is the effect of a one-standard-deviation increase, so the features are directly comparable.
fit = model.fit(clean, y)
coef = pd.Series(fit[-1].coef_[0], index=clean.columns)
print((np.exp(coef)).round(2).sort_values(ascending=False).to_dict()){'glucose': 3.11, 'bmi': 1.89, 'pregnancies': 1.51, 'pedigree': 1.33, 'age': 1.17, 'skin_thickness': 1.04, 'insulin': 0.91, 'blood_pressure': 0.9}
A one-standard-deviation higher glucose multiplies the odds of diabetes by 3.11, the largest effect by far, followed by BMI at 1.89. Blood pressure and insulin come out slightly below 1, which does not mean they protect anyone: the features are correlated, and many insulin values were imputed. An odds ratio describes this data and this model, not a cause. If you need confidence intervals and p-values, statsmodels.Logit provides them, which scikit-learn does not.
Regularization strength (C)
scikit-learn applies L2 regularization by default, controlled by C: smaller C means a stronger penalty. We tried five values on the cleaned, scaled data.
for C in (0.001, 0.01, 0.1, 1, 10):
m = make_pipeline(SimpleImputer(strategy="median"), StandardScaler(), LogisticRegression(C=C, max_iter=1000))
print("C", C, acc(clean, m))C 0.001 (0.654, 0.006)
C 0.01 (0.763, 0.023)
C 0.1 (0.766, 0.028)
C 1 (0.768, 0.025)
C 10 (0.769, 0.025)At C = 0.001 the penalty is so strong that the model collapses to the baseline (65.4%). From C = 0.01 up, accuracy is flat at about 76 to 77%. With 768 rows and 8 features there is little to over-fit, so the default C = 1 is fine, and tuning it would not be worth the time here.
Choose the threshold, not just the model
Accuracy at a 0.5 cut-off is not the only number that matters. In a screening problem, missing a sick patient costs more than a false alarm. predict_proba gives probabilities, and you choose where to cut. We use cross-validated probabilities so the numbers are honest, and report precision (how many flagged cases are real) and recall (how many real cases are flagged).
p = cross_val_predict(model, clean, y, cv=5, method="predict_proba")[:, 1]
print("AUC", round(roc_auc_score(y, p), 3))
for t in (0.5, 0.4, 0.3):
pred = p >= t
print(f"threshold {t}: precision {precision_score(y, pred):.3f} recall {recall_score(y, pred):.3f} accuracy {(pred == y).mean():.3f}")
print(confusion_matrix(y, p >= 0.5).tolist())AUC 0.836
threshold 0.5: precision 0.722 recall 0.563 accuracy 0.772
threshold 0.4: precision 0.651 recall 0.653 accuracy 0.757
threshold 0.3: precision 0.587 recall 0.791 accuracy 0.733
[[442, 58], [117, 151]]The AUC of 0.836 says the model ranks sick patients above healthy ones about 84% of the time. At the default 0.5 cut-off it misses 117 of the 268 patients with diabetes (recall 56.3%). Lowering the threshold to 0.3 finds 79.1% of them, at the price of more false alarms (precision falls from 72.2% to 58.7%) and lower accuracy. Neither is “right”: the choice depends on the cost of each mistake, which is a decision for the people using the model, not for the algorithm.
When logistic regression in Python is the right tool
- You need to explain the result. Odds ratios are easy to communicate, unlike a forest of hundreds of trees.
- The data is small. With a few hundred rows a simple model is hard to beat; see how a forest compares in our random forests tutorial.
- You want calibrated probabilities. Logistic regression outputs probabilities directly, which you can threshold, as above.
- You will validate it properly. The evaluation habits here (baseline, repeated cross-validation, a pipeline that fits the scaler on training folds only) are explained in our scikit-learn model tutorial.
For a complete classification project with a different data set, see Kaggle Titanic with Python, where a logistic regression ends within a point of a random forest. The official scikit-learn documentation lists the solvers and penalties.
FAQ
What is logistic regression used for?
Predicting a yes/no outcome, such as whether a patient has diabetes, a customer will leave or an email is spam, and explaining which features push the probability up or down.
Is logistic regression a regression or a classification algorithm?
It is a classification algorithm that is built like a regression: it fits a straight line to the log-odds of the outcome and then converts that to a probability between 0 and 1.
Do I need to scale features for logistic regression?
Not for accuracy in this test (77.7% scaled and unscaled), but yes if you want to compare coefficients, and it helps the solver converge on larger data sets.
How do I choose the classification threshold?
Compute cross-validated probabilities, then compare precision and recall at several cut-offs and pick the one that matches the cost of a missed case versus a false alarm. The default 0.5 is rarely the best choice for imbalanced problems.
