Written and maintained by CASRAI Editorial Board
Published
On this page
Logistic regression in statsmodels fits a binary outcome with sm.Logit(y, X) or smf.logit(formula, data). Add an intercept explicitly with the array interface, fit the model, then extract coefficients, confidence intervals and predicted probabilities. The example below connects both interfaces to an odds-ratio report and checks that they produce the same fit.
What it is used for in research
Use a binary logit model when the response has two coded outcomes and the analysis concerns the probability of the outcome coded 1. Statsmodels places Logit in its discrete-model family, alongside separate classes for probit, multinomial and count outcomes. An unordered response with three categories therefore needs a different model specification; changing its labels to numbers does not make it binary.
The practical distinction is between the model and its interface. statsmodels.api accepts a response vector and a predictor matrix. statsmodels.formula.api accepts a formula and a DataFrame. Both can express the same logistic regression. The statsmodels API guide explains the wider import structure; this walkthrough follows one binary model through estimation and reporting.
Write the model as log[p/(1 − p)] = η = β₀ + β₁x₁ + … + βₖxₖ, where p is the conditional probability of outcome 1, η is the linear predictor, β₀ is the intercept, and each βⱼ multiplies predictor xⱼ. Solving for probability gives p = 1/(1 + exp(−η)). A one-unit increase in a predictor adds its coefficient to the log-odds, holding the remaining predictors fixed. Exponentiation converts that change to an odds ratio.
This specification makes the log-odds linear in the included predictor terms; it does not make probability itself a straight line. The broader logistic-regression model guide covers the methodological context. Here the central task is preserving the intended specification from the input data through the final report.
Install or access
The project’s official installation page provides the following pip command. Run it in the Python environment that will execute the analysis:
python -m pip install statsmodels
Its documented conda route is conda install -c conda-forge statsmodels. Choose the route appropriate to the environment you maintain, then import the package in that environment. Installation in one Python interpreter does not establish that a different notebook interpreter can import it.
import statsmodels
print(statsmodels.__version__)
Record the installed version with the analysis script. The worked calculations here use statsmodels 0.15.0. This example loads the dataset distributed with the package, so there is no separate CSV download, account or file-path substitution before fitting. For your own data, replace the response and predictor selection deliberately rather than modifying only the displayed title of a model.
Step-by-step task: fit a binary logistic regression
The official discrete-model documentation demonstrates the Spector dataset. It has 32 observations, response GRADE, and predictors GPA, TUCE and PSI. The package’s dataset description defines GRADE=1 as grade improvement and PSI as participation in the program. These are demonstration data, not evidence that a model will perform similarly in another study.
- Load the response and predictors. Keep their rows aligned. For your own dataset, state explicitly which observed outcome is coded 1; all subsequent probabilities refer to that event.
- Add the intercept column. The array-based
Logitconstructor does not add one automatically. The official example callssm.add_constantbefore creating the model. - Create and fit the model.
fit()estimates the parameters by maximum likelihood. The example usesmissing="raise"to stop if missing values reach the constructor. - Inspect the result. Print the summary and review convergence, sample size, coefficients and uncertainty before preparing a report.
import numpy as np
import pandas as pd
import statsmodels.api as sm
import statsmodels.formula.api as smf
data = sm.datasets.spector.load_pandas()
y = data.endog
X = sm.add_constant(data.exog)
result = sm.Logit(y, X, missing="raise").fit(disp=False)
print(result.summary())
disp=False suppresses the optimizer’s progress output; it is not a diagnostic test. Preserve warnings and inspect the fitted results. In this example, the summary identifies the method as MLE and reports 32 observations. Those details provide an immediate check that the intended data reached the model.
Fit the same model with the formula interface
The formula interface uses column names, and its default specification includes an intercept. Here the response is added to the predictor DataFrame before fitting. The equality check compares coefficients in their matching order:
df = data.exog.copy()
df["GRADE"] = y
formula_result = smf.logit(
"GRADE ~ GPA + TUCE + PSI", data=df, missing="raise"
).fit(disp=False)
print(np.allclose(
result.params.to_numpy(), formula_result.params.to_numpy()
))
The check returns True for this example. The intercept is called const in the array result and Intercept in the formula result. A disagreement in your own translation is a reason to compare the design matrices and retained observations before interpreting coefficients.
The official formula tutorial documents C(variable) for categorical treatment, -1 for removing an intercept, : for an interaction term and * for an interaction together with its component terms. These choices change the fitted design. An integer identifier should not become a continuous predictor merely because it can be stored as a number. Specify the intended treatment explicitly.
Output and how to read it
The official example’s coefficient rows show GPA=2.8261, TUCE=0.0952 and PSI=2.3787, with an intercept of −13.0213. These are log-odds coefficients. The summary also displays standard errors, test statistics, p-values and confidence limits. For the general column meanings, see how to read a regression table.
Convert coefficients and confidence limits to odds ratios
For a coefficient β, the odds ratio is exp(β). Apply the same transformation to both coefficient confidence limits. Do not exponentiate the standard error and present it as an odds-ratio standard error: the following code transforms the interval endpoints themselves.
interval = result.conf_int(alpha=0.05)
table = pd.DataFrame({
"beta": result.params,
"odds_ratio": np.exp(result.params),
"ci_low": np.exp(interval[0]),
"ci_high": np.exp(interval[1]),
"p_value": result.pvalues,
})
print(table.round(4))
The computed PSI odds ratio is 10.7907, with a 95% interval from 1.3393 to 86.9380. The GPA odds ratio is 16.8797, with an interval from 1.4202 to 200.6238. These broad intervals belong beside the point estimates; rounding them away would hide substantial uncertainty. TUCE has an odds ratio of 1.0998 and an interval from 0.8334 to 1.4515.
Each estimate is conditional on the other included predictors. The odds ratio describes a ratio of odds, p/(1 − p). A PSI odds ratio near 10.79 does not mean that the fitted probability is multiplied by 10.79. The next calculation makes that distinction visible.
Predict probabilities for explicit covariate profiles
These two illustrative profiles hold GPA at 3.0 and TUCE at 20.0, changing only PSI from 0 to 1. They are constructed inputs for explaining the fitted equation, not a pair of observed participants or a causal comparison.
new = pd.DataFrame({
"GPA": [3.0, 3.0],
"TUCE": [20.0, 20.0],
"PSI": [0.0, 1.0],
})
new_X = sm.add_constant(new, has_constant="add")
new_X = new_X.loc[:, X.columns]
print(result.predict(new_X))
print(formula_result.predict(new))
Both interfaces return approximately 0.066617 and 0.435077. Using the rounded coefficients, the first linear predictor is −13.0213 + 2.8261 × 3 + 0.0952 × 20 = −2.6390, giving p ≈ 0.0666. Adding 2.3787 for PSI=1 gives η ≈ −0.2603 and p ≈ 0.4353. The slight difference from the code comes from rounding the coefficients before doing the arithmetic.
Here the probability difference is about 0.3685, or 36.85 percentage points. The probability ratio is about 6.53, whereas the odds ratio remains about 10.79. All three calculations describe these same fitted profiles on different scales.
The explicit has_constant="add" matters for these profiles because GPA and TUCE are constant across the two rows. The final column selection preserves the original predictor order. For formula predictions, pass the named raw predictors; the formula machinery constructs their design. Also distinguish result.predict() from result.fittedvalues: the LogitResults reference defines the latter as the linear predictor XB, rather than the fitted probability.
Prepare a report from the fitted model
A report for this demonstration could state: “A binary logistic regression modeled GRADE using GPA, TUCE and PSI in 32 observations. The PSI coefficient was 2.379, corresponding to an adjusted odds ratio of 10.79, 95% CI [1.34, 86.94], p=.025, with the model’s nonrobust covariance estimate.” Include the outcome coding and predictor units in the accompanying methods description.
The example summary reports McFadden’s pseudo-R² as 0.3740 and the likelihood-ratio p-value as approximately .001502. The results reference defines the likelihood-ratio statistic as −2 × (LL-null − LL-fitted). These summarize likelihood comparisons; pseudo-R² is not an ordinary least-squares percentage of outcome variance explained. Neither summary establishes predictive performance on new observations.
Troubleshooting
Missing values or different sample sizes: the Logit constructor documents missing='none', 'drop' and 'raise'. The default 'none' performs no NaN check. An explicit choice makes the handling visible. If observations are dropped, report the analyzed sample and ensure that a model comparison uses the intended rows.
No intercept or unexpected coefficients: inspect the predictor columns. The array constructor needs an intercept added by the user; the formula interface includes one unless removed. Do not compare a no-intercept model with an intercept model as if only the calling syntax changed. The downloadable data table below records the separate input and output contracts.
Nonconvergence, extreme estimates or singularity: the project’s Pitfalls page warns that maximum-likelihood estimates may be infinite or nonunique under separation, and that convergence indicators can be misleading. Examine sparse outcome/predictor combinations and redundant columns. Increasing an iteration limit cannot by itself establish that a finite, identifiable estimate exists. Do not present a warning-laden coefficient table as a settled result.
A successful fit with unresolved diagnostics: numerical termination is only one check. The documentation warns that quasi-perfect prediction is not automatically checked comprehensively. Preserve the warnings and evaluate the design and data rather than treating silence as proof. For alternative fitting settings, create separate model instances when retaining both results, as the Pitfalls guidance recommends.
Unexpected disagreement with another package: first align event coding, observations, intercepts, categorical reference levels and penalties. Statsmodels offers fit_regularized() separately from ordinary fit(). Scikit-learn’s logistic regression applies regularization by default, so its default coefficients are not a direct replication target for this unpenalized example.
Free alternatives
These alternatives support related research tasks, with different interfaces and defaults. The table describes their documented functions rather than assuming interchangeable output:
| Alternative | Documented interface | Difference to preserve | Official source |
|---|---|---|---|
| R stats | glm(formula, family=binomial(), data=df) |
Formula-based generalized linear model; the documented default fitting method uses iteratively reweighted least squares. | R glm reference |
| scikit-learn | LogisticRegression |
Regularization and intercept fitting are on by default; predict gives labels and predict_proba gives probabilities. |
LogisticRegression reference |
The logistic-regression workflow in R provides the corresponding R steps. For Python classification workflows, use the scikit-learn logistic-regression guide. Whichever interface you choose, retain the specification and distinguish probability estimation from assigning a class label. A table of coefficient estimates and a table of predicted probabilities answer different questions.
Sources
- statsmodels: Logit API reference and add_constant reference. Checked 2026-11-14.
- statsmodels: Regression with Discrete Dependent Variable, Spector example. Checked 2026-11-14.
- statsmodels: Installing. Checked 2026-11-14.
- statsmodels: Fitting models using R-style formulas. Checked 2026-11-14.
- statsmodels: LogitResults API reference. Checked 2026-11-14.
- statsmodels: Pitfalls. Checked 2026-11-14.
- scikit-learn: LogisticRegression API reference. Checked 2026-11-14.
- R stats: Fitting Generalized Linear Models and Family Objects for Models. Checked 2026-11-14.
Data: statsmodels binary-logit input, prediction and reporting contracts
Original crosswalk compiled from the official statsmodels Logit, formula, LogitResults and Pitfalls references. It separates required inputs, intercept handling, missing-value behavior and output scales so the same research model can be preserved from fitting through reporting.
| Workflow component | Documented contract | Check or implication | Source |
|---|---|---|---|
| Array interface | Logit takes endog and exog; no intercept is added automatically. | Add an intercept explicitly when the intended model includes one. | Logit API reference |
| Formula interface | Formula models accept a formula and data; the formula default includes an intercept. | Remove the intercept only when that is the intended specification. | Fitting models using R-style formulas |
| Missing observations | Logit missing options: none, drop, raise. Default none performs no NaN check. | Choose and record missing-value handling explicitly. | Logit API reference |
| Coefficient intervals | conf_int constructs confidence intervals for fitted parameters. | Transform coefficient interval endpoints when reporting odds ratios. | LogitResults API reference |
| Stored fittedvalues | LogitResults.fittedvalues is the linear predictor XB. | Do not label this attribute as fitted probabilities. | LogitResults API reference |
| Convergence | Convergence criteria can misleadingly indicate success; separation can yield infinite or nonunique parameters. | Review warnings and the design; a convergence flag alone is insufficient. | Pitfalls |
| Retained alternative fits | Result instances may depend on attributes of their model instance. | Use separate model instances when keeping different fits. | Pitfalls |
Sources
- Logit API reference (accessed 2026-11-14)
- Fitting models using R-style formulas (accessed 2026-11-14)
- LogitResults API reference (accessed 2026-11-14)
- Pitfalls (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







