Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

Statsmodels Logistic Regression with Logit and Probit

  • NinadNinad
  • October 27, 2026
  • Statsmodel
Statsmodels Logistic Regression with Logit and Probit

For a yes-or-no outcome, you need a model that relates the result to its predictors. Statsmodels provides Logit and Probit, two estimators for modeling binary responses.

In this piece, I’ll fit both models and show how to inspect their estimates and predicted probabilities.

TL;DR

Use Statsmodels Logit for a logistic link or Probit for a normal-CDF link, and pass a binary outcome with a deliberately prepared predictor matrix.

  • For the array API, add an intercept with sm.add_constant().
  • Call fit() to estimate parameters and inspect the results object.
  • Use predict() for probabilities, not class labels.

What is Statsmodels logistic regression?

Statsmodels provides Logit and Probit estimators for binary responses. Their fitted result objects include coefficient estimates and inference statistics.

Logit converts a linear score with the logistic cumulative distribution function, whereas Probit uses the standard normal cumulative distribution function. Their probability estimates share the outcome scale even though the coefficients do not.

The array API names the response endog and the predictor matrix exog.

Choose the formula interface when readable column names and categorical encoding help. Choose arrays when you want explicit control over the design matrix. The related Statsmodels endog and exog guide explains these input roles, while the formula API guide covers formula syntax.

How to fit Logit and Probit step by step

The example loads Spector’s teaching dataset and applies both estimators to the same design matrix.

Step 1: Prepare the response and predictors

The Statsmodels example below uses its built-in Spector teaching data. It loads an outcome and predictor table, then adds the intercept column. For your data, choose a missing-row policy before estimation and align the outcome with each predictor row.

import statsmodels.api as sm

sample = sm.datasets.spector.load_pandas()
y = sample.endog
X = sm.add_constant(sample.exog)

The response supplies one value per observation, while X supplies the predictor columns and added intercept.

Step 2: Fit both models and read the result

Call fit() on either model to estimate its coefficients by maximum likelihood. This complete run uses the current installed Statsmodels 0.15.0 and prints convergence, iteration count, one coefficient, and a fitted probability.

import statsmodels.api as sm

sample = sm.datasets.spector.load_pandas()
y = sample.endog
X = sm.add_constant(sample.exog)

for name, model in (("Logit", sm.Logit(y, X)), ("Probit", sm.Probit(y, X))):
    result = model.fit(disp=False)
    print(f"{name}: converged={result.mle_retvals['converged']}, iterations={result.mle_retvals['iterations']}")
    print(f"  GPA coefficient={result.params['GPA']:.3f}; predicted probability={result.predict(X.iloc[[0]])[0]:.3f}")

Here is the exact output from that command.

Logit: converged=True, iterations=7
  GPA coefficient=2.826; predicted probability=0.027
Probit: converged=True, iterations=6
  GPA coefficient=1.626; predicted probability=0.018
Terminal output comparing fitted Statsmodels Logit and Probit probabilities

Both estimators converged on this dataset.

Step 3: Inspect estimates and predict probabilities

The fitted results object exposes estimates, standard errors, confidence intervals, p-values and a summary table. Its predict() method returns probabilities for binary Logit and Probit models.

result = sm.Logit(y, X).fit()
print(result.summary())
probabilities = result.predict(X)
class_labels = (probabilities >= 0.5).astype(int)

The cutoff turns predicted probabilities into class labels. Choose it to reflect the costs of false positives and false negatives, and preserve the training matrix columns and order for new predictions.

What should you check when results look wrong?

Start with the design matrix, missing values and convergence status before interpreting coefficient tests.

CheckSymptomNext action
InterceptBaseline probability is constrained unexpectedlyAdd sm.add_constant(X) for array input
Missing or non-finite valuesNaN output or fitting errorInspect outcome and predictors, then choose an explicit missing-data policy
SeparationVery large estimates or standard errorsCheck whether a predictor nearly determines the outcome. Reconsider the specification or data
ConvergenceWarning or false convergence flagInspect scale, redundant columns, sample information and model specification

The Logit and Probit API accepts missing-value policies named none, drop and raise. Inspect the data and select a missing-value policy deliberately. Duplicate or perfectly dependent predictor columns can also destabilize estimation.

A Logit coefficient gives the change in log-odds for a one-unit predictor change, holding other terms fixed. Exponentiating it gives an odds ratio.

Probit coefficients shift a latent normal score. Use marginal effects to express a predictor change on the probability scale.

Read the optimizer message and mle_retvals rather than choosing a fixed iteration count from a search snippet. More iterations cannot fix separation, missing values or a misspecified design matrix.

Conclusion

Choose Logit or Probit according to the link that fits the analysis, and inspect the fitted results before interpreting them.

For practical interpretation, report marginal effects when a probability-scale change is more useful than a coefficient.

For estimator arguments, see the official Logit API and Probit API.

FAQ

These answers cover common fit and output questions that the sections above do not resolve by themselves.

How many iterations are good for Statsmodels logistic regression?

There is no fixed ideal count. Check whether the optimizer converged and inspect warnings and model diagnostics; iteration needs depend on the data and starting values.

How do I save Statsmodels logistic regression results?

Save the fitted result object with its supported save method, and keep the model specification and data-preparation steps alongside it so the analysis can be reproduced.

Why can Statsmodels logistic regression return NaN?

Missing or non-finite inputs, separation, redundant predictors or optimization problems can produce invalid estimates. Inspect the data, design matrix and convergence output before interpreting results.

Ninad
Ninad

A Python and PHP developer turned writer out of passion. Over the last 6+ years, he has written for brands including DigitalOcean, DreamHost, Hostinger, and many others. When not working, you'll find him tinkering with open-source projects, vibe coding, or on a mountain trail, completely disconnected from tech.

Articles: 136
How To Configure Logging In Python
Previous Post How To Configure Logging In Python
Next Post Fix ModuleNotFoundError No Module Named TensorFlow
Fix ModuleNotFoundError No Module Named TensorFlow

Related Posts

Statsmodels Library Structure and Imports

Statsmodels Library Structure and Imports

  • November 11, 2026
Python Statsmodels Linear Mixed Effects Models

Python Statsmodels Linear Mixed Effects Models

  • November 29, 2025
Statsmodels Robust Linear Models

Statsmodels Robust Linear Models

  • November 29, 2025

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.