Logistic Regression in Python: Fit, Interpret, and Plot

Fit logistic regression in Python with scikit-learn and statsmodels, turn coefficients into odds ratios, and plot the probability curve, odds ratios, and decision threshold.

To fit a logistic regression in Python, call smf.logit("y ~ x", data=df).fit() in statsmodels for coefficients with confidence intervals, or LogisticRegression().fit(X, y) in scikit-learn for predictions. Exponentiate a coefficient with np.exp() to read it as an odds ratio.

Quick Example

This example makes up 600 free-trial accounts and models the chance that each one upgrades to a paid plan, based on how many days it was active during a 14-day trial.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from matplotlib.ticker import PercentFormatter

rng = np.random.default_rng(8)
n = 600
active_days = rng.binomial(14, rng.beta(2, 3, n))
teammates = rng.poisson(1.5, n)
plan = rng.choice(["solo", "team"], n, p=[0.6, 0.4])
log_odds = -3.6 + 0.38 * active_days + 0.30 * teammates + 0.7 * (plan == "team")
upgraded = rng.binomial(1, 1 / (1 + np.exp(-log_odds)))
trials = pd.DataFrame({"upgraded": upgraded, "active_days": active_days,
                       "teammates": teammates, "plan": plan})

simple = smf.logit("upgraded ~ active_days", data=trials).fit()
print(simple.params.round(3))
print("odds ratio per active day:", np.exp(simple.params["active_days"]).round(2))

grid = pd.DataFrame({"active_days": np.linspace(0, 14, 100)})
curve = simple.get_prediction(grid).summary_frame(alpha=0.05)
observed = trials.groupby("active_days")["upgraded"].agg(["mean", "size"])

fig, ax = plt.subplots(figsize=(8, 5), layout="constrained")
ax.fill_between(grid.active_days, curve.ci_lower, curve.ci_upper,
                color="#7c3aed", alpha=0.2, label="95% confidence interval")
ax.plot(grid.active_days, curve.predicted, color="#7c3aed", lw=2.5,
        label="Predicted probability")
ax.scatter(observed.index, observed["mean"], s=observed["size"] * 3,
           color="#f59e0b", edgecolor="#78350f", zorder=3,
           label="Observed share (size = accounts)")
ax.set(title="Chance of upgrading after a free trial",
       xlabel="Days active during the trial", ylabel="Probability of upgrading",
       ylim=(0, 1.03))
ax.yaxis.set_major_formatter(PercentFormatter(1))
ax.legend(loc="upper left")
plt.show()

S-shaped logistic regression curve rising from about 5% at zero active days to 94% at fourteen, with observed upgrade shares scattered close to it

The odds of upgrading multiply by 1.50 for each extra active day. In probability terms, the model predicts about 5% for an account with no active days, 48% at 7 days, and 94% at 14. The curve passes 50% at about 7.2 days.

Plotting the observed share at each value is a quick check on the fit. Points with few accounts, shown as small dots, can sit far from the curve by chance.

Fit a Model with Several Features

Add terms to the formula with +. The text column plan becomes an indicator, with solo as the reference level.

model = smf.logit("upgraded ~ active_days + teammates + plan", data=trials).fit()
print(model.summary())

All three coefficients are positive, and none of the confidence intervals include zero. Pseudo R-squ. is McFadden's pseudo R-squared. It is not a share of variance explained, and it runs much lower than the R-squared of a linear regression, so don't compare the two.

How to Interpret Logistic Regression Coefficients

Each coefficient is the change in log-odds for a one-unit increase, holding the other features fixed. np.exp() turns it into an odds ratio: a value above 1 raises the odds, below 1 lowers them.

odds = np.exp(pd.DataFrame({"odds_ratio": model.params,
                            "low": model.conf_int()[0],
                            "high": model.conf_int()[1]})).drop("Intercept")
odds.index = ["Team plan vs solo", "Each active day", "Each teammate invited"]
print(odds.round(2))

fig, ax = plt.subplots(figsize=(8, 3.5), layout="constrained")
errors = [odds.odds_ratio - odds.low, odds.high - odds.odds_ratio]
ax.errorbar(odds.odds_ratio, odds.index, xerr=errors, fmt="s", color="#0f766e",
            capsize=4, lw=2, markersize=7)
for name, value in odds.odds_ratio.items():
    ax.annotate(f"{value:.2f}", (value, name), xytext=(0, 9),
                textcoords="offset points", ha="center")
ax.axvline(1, color="#334155", ls="--", lw=1)
ax.set_xscale("log")
ax.set_xticks([1, 1.5, 2, 3], labels=["1 (no effect)", "1.5", "2", "3"])
ax.set_xticks([], minor=True)
ax.set(title="Odds ratios with 95% confidence intervals", xlim=(0.9, 3.5),
       xlabel="Odds ratio (log scale)")
ax.margins(y=0.2)
ax.invert_yaxis()
plt.show()

Odds ratio plot with confidence intervals: 2.18 for the team plan, 1.53 per active day and 1.38 per teammate invited, all above 1

With the other features held fixed, the team plan has 2.18 times the odds of a solo plan, and its interval runs from 1.45 to 3.27. Odds ratios multiply: seven more active days multiply the odds by about 1.53 to the seventh power, roughly 20. A log scale gives equal space to equal multiplicative effects.

Odds Ratios Are Not Probability Ratios

The same odds ratio moves the probability by different amounts depending on where an account starts. Predict a grid of cases to show effects in probability terms.

cases = pd.DataFrame(
    [(d, t, p) for p in ["solo", "team"] for t in [0, 4] for d in range(15)],
    columns=["active_days", "teammates", "plan"])
cases["probability"] = model.predict(cases)

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), sharey=True, layout="constrained")
for ax, plan_name in zip(axes, ["solo", "team"]):
    for count, color in [(0, "#94a3b8"), (4, "#be185d")]:
        rows = cases[(cases.plan == plan_name) & (cases.teammates == count)]
        ax.plot(rows.active_days, rows.probability, "o-", color=color,
                label=f"{count} teammates")
    ax.set(title=f"{plan_name.title()} plan", xlabel="Days active")
    ax.yaxis.set_major_formatter(PercentFormatter(1))
    ax.grid(alpha=0.3)
axes[0].set(ylabel="Probability of upgrading", ylim=(0, 1))
axes[0].legend()
plt.show()

print(cases.query("plan == 'solo' and active_days in [0, 7]").round(3))
print("average marginal effects:")
print(model.get_margeff(dummy=True).summary_frame()[["dy/dx"]].round(4))

Predicted upgrade probability by active days for solo and team plans, with the four-teammate curve above the zero-teammate curve in both panels

Four invited teammates multiply the odds by the same amount everywhere. For a solo account with no active days, that raises the probability from 2% to 7%. At 7 active days it raises it from 28% to 59%.

get_margeff() averages the effect over all rows, which gives one number in probability units: each active day adds about 6.9 percentage points on average. dummy=True reports the plan effect as the switch from solo to team instead of a slope.

Logistic Regression in scikit-learn

scikit-learn's LogisticRegression applies an L2 penalty by default (C=1.0), which shrinks coefficients toward zero. Set C=np.inf to turn the penalty off and match statsmodels. Older code uses penalty=None, which is deprecated since scikit-learn 1.8.

from sklearn.linear_model import LogisticRegression

X = trials[["active_days", "teammates"]].assign(team=(trials.plan == "team").astype(int))
y = trials["upgraded"]

unpenalized = LogisticRegression(C=np.inf, max_iter=1000).fit(X, y)
default = LogisticRegression().fit(X, y)
strong = LogisticRegression(C=0.01).fit(X, y)

comparison = pd.DataFrame({
    "statsmodels": model.params[["active_days", "teammates", "plan[T.team]"]].to_numpy(),
    "C=inf": unpenalized.coef_[0], "C=1 (default)": default.coef_[0],
    "C=0.01": strong.coef_[0]}, index=X.columns)
print(comparison.round(3))

With C=np.inf, scikit-learn matches statsmodels to three decimals. The default penalty changes little here, with 600 rows and three features. C=0.01 is a much stronger penalty (smaller C means more shrinkage), and it cuts the team coefficient from 0.78 to 0.15. Don't report odds ratios from a heavily penalized model as if they were unbiased estimates.

Choose a Classification Threshold

predict() labels a row positive when its probability is above 0.5. That cutoff is a choice, and a different one may suit the cost of each kind of error. predict_proba() returns the probabilities, so you can apply any threshold.

from sklearn.metrics import ConfusionMatrixDisplay, precision_score, recall_score
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.4, stratify=y, random_state=8)
clf = LogisticRegression().fit(X_train, y_train)
probability = clf.predict_proba(X_test)[:, 1]

fig, axes = plt.subplots(1, 2, figsize=(10, 4.2), layout="constrained")
for ax, threshold in zip(axes, [0.5, 0.25]):
    label = (probability >= threshold).astype(int)
    ConfusionMatrixDisplay.from_predictions(
        y_test, label, display_labels=["Stayed free", "Upgraded"],
        cmap="Purples", colorbar=False, ax=ax)
    ax.set_title(f"Threshold {threshold}\n"
                 f"precision {precision_score(y_test, label):.0%}, "
                 f"recall {recall_score(y_test, label):.0%}")
plt.show()

Two confusion matrices: lowering the threshold from 0.5 to 0.25 raises correct upgrade predictions from 56 to 76 and false alarms from 29 to 57

Of 89 test accounts that upgraded, the 0.5 threshold finds 56 and flags 29 that stayed free. At 0.25 it finds 76 and flags 57. If a follow-up email is cheap, the lower threshold is the better trade. If each follow-up is a sales call, it may not be.

Pick the threshold using validation data, not the final test set. TunedThresholdClassifierCV (scikit-learn 1.5+) searches for it with cross-validation. A lift and gains chart helps when the question is how many accounts to contact.

scikit-learn vs statsmodels for Logistic Regression

scikit-learn statsmodels
Default penalty L2, C=1.0 None
Standard errors and p-values Not provided summary()
Odds ratio intervals Not provided np.exp(model.conf_int())
Predicted probability predict_proba(X)[:, 1] predict(df)
More than two classes Handled automatically smf.mnlogit
Pipelines and cross-validation Built in Not built in

Practical Tips

  • An odds ratio of 2 does not mean "twice as likely". It means the odds p / (1 - p) double.
  • Scale the features before using a penalized model, since the penalty treats every coefficient the same. A pipeline with StandardScaler does this without leaking test data.
  • If one feature separates the classes perfectly, the unpenalized coefficients grow without limit and statsmodels warns or fails. A penalty keeps them finite.
  • Evaluate the probabilities with a ROC curve and a calibration curve, not accuracy alone.
  • A coefficient describes an association. Accounts that are active more often may differ in other ways, so it doesn't show that pushing someone to log in causes an upgrade.

Similar Topics