Skip to content

DPredict · Guide test 187

Hosmer–Lemeshow test

Compares grouped observed binary outcomes with fitted logistic model probabilities.

Runs in CodeSplashPython (calls R) example not runR example validated

Do it in CodeSplash

In the app, set it up in Analyze with one of these methods:

Do it in CodeSplash Run this test on your own data, in Python or R.

Bench

Change the design, drag the data, move α. The statistic, its reference distribution and the verdict follow.

Bench · Hosmer–Lemeshow test

200
0.50
0.06

0 makes the fitted logistic model correct.

0.050

Your data

Simulated with a known ρ

If H₀ were true

χ² = 22.13
  1. The reference: how χ² varies across samples when H₀ is true (χ² approximation).
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .005).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

C^=∑g=1G(Og−Eg)2Eg(1−Eg/ng)∼χG−22\hat C = \sum_{g=1}^{G}\dfrac{(O_g - E_g)^2}{E_g(1 - E_g/n_g)} \sim \chi^2_{G-2}

With your numbers

C^=22.13,G=10, df=8\hat C = 22.13,\qquad G = 10,\ df = 8
Og,EgO_g, E_g
observed and expected events in risk group g
GG
groups at the deciles of the fitted risk

The verdict

χ²(8) = 22.13, p = .005

p ≤ α = .050: reject H₀

The verdict depends on the number of groups, and with large n trivial misfit rejects. Look at the calibration plot, not just p.

Statistic
22.129
p-value
0.0047
Hosmer–Lemeshow test on 200 (x, y) pairs: χ²(8) = 22.13, p = .005. The p-value is below α = .050, so the data are hard to reconcile with H0.

Hosmer–Lemeshow test on 200 (x, y) pairs: χ²(8) = 22.13, p = .005. The p-value is below α = .050, so the data are hard to reconcile with H₀.

Question and hypotheses

H0: the fitted binary-response model is adequately calibrated in selected risk groups.

Assumptions

Independent binary outcomes; prespecified grouping rule, sufficient expected successes/failures, and a fitted probability model.

Formula

C=∑g=1G(Og−Eg)2Eg(1−Eg/ng)C=\sum_{g=1}^{G}\frac{(O_g-E_g)^2}{E_g(1-E_g/n_g)}

Parameters and notation

Group predicted probabilities; Og observed successes, Eg=Σi∈g p̂i, ng group size.

Structure of the method

Fit a binary probability model, sort observations by predicted risk, form quantile-based groups, and compare observed with expected successes and failures. The grouped discrepancy summarizes calibration within the selected bins; it does not directly measure discrimination or detailed individual-level calibration.

Estimated and nuisance parameters

Logistic coefficients and fitted probabilities are estimated from the training observations. Group boundaries, expected counts, and observed counts are then derived. The actual number of nonempty distinct-risk groups may be smaller than the requested number when predicted probabilities have ties.

Settings and design choices

Prespecify grouping count/rule, handling of ties, evaluation sample, and the appropriate reference or bootstrap. The conventional fitted-logistic chi-square degrees of freedom are not a universal rule for every externally supplied machine-learning probability vector. Do not search for the group count producing the largest p-value.

Fitting and adaptation

Distinguish in-sample model checking from external calibration assessment. A full parametric bootstrap should refit the logistic model and recreate risk groups in every replicate. Recalibrating probabilities through an intercept/slope or flexible calibration model is a separate fitting step and must be evaluated on fresh data or with a valid resampling design.

Sensitivity and robustness

Sparse expected events, rare outcomes, small groups, duplicated risks, and large sample sizes strongly affect the test. A nonsignificant grouped test can miss within-bin miscalibration. Use calibration plots, calibration slope/intercept, proper scoring rules, and out-of-sample evaluation alongside the test; discrimination gains do not imply calibration gains.

How to use and calibrate

Use the conventional χ²G−2 approximation for the standard fitted logistic setting, or bootstrap the full fitting/grouping process.

Example application

Check grouped calibration of a logistic risk model.

Interpretation and pitfalls

Watch out

Results depend on group count and ties. Nonsignificance does not prove calibration; calibration plots and out-of-sample assessment remain useful.

What changed in edition 2

  • New sections: structure of the method, estimated and nuisance parameters, settings and design choices, fitting and adaptation, sensitivity and robustness.

Python and R

Ten groups of predicted risk. This goodness-of-fit test depends on grouping and can fail with too few distinct fitted probabilities; inspect calibration plots as well.

Python · invokes R

Not run — Executed end to end through Rscript · needs Python standard library + Rscript; R packages: ResourceSelection

# Python launcher for the complete R implementation below.
# Requires Rscript on PATH and the listed R packages.
import shutil
import subprocess
rscript = shutil.which("Rscript")
if rscript is None:
    raise RuntimeError("Install R and make Rscript available on PATH.")
r_code = r"""
set.seed(2026)
x<-rnorm(200);y<-rbinom(200,1,plogis(-.3+.8*x));fit<-glm(y~x,family=binomial());print(ResourceSelection::hoslem.test(y,fitted(fit),g=10))
"""
# No shell interpolation. A failed R execution raises an error in Python.
result = subprocess.run([rscript, "--vanilla", "-"], input=r_code,
                        text=True, capture_output=True)
print(result.stdout)
if result.stderr:
    print(result.stderr)
result.check_returncode()
R

Validated — Executed successfully in the validation environment · needs ResourceSelection

set.seed(2026)
x<-rnorm(200);y<-rbinom(200,1,plogis(-.3+.8*x));fit<-glm(y~x,family=binomial());print(ResourceSelection::hoslem.test(y,fitted(fit),g=10))
Output
	Hosmer and Lemeshow goodness of fit (GOF) test

data:  y, fitted(fit)
X-squared = 5.9472, df = 8, p-value = 0.6531

Sources

Statistics guide v4 (historical):
Python: Executed end to end through Rscript · R: Executed successfully in the validation environment
Reference's record:
Edition 2 review: Python: skip · R: not executed (Rscript unavailable); why not run: Python: Python-to-R bridge; Rscript is unavailable. R code was not executed. Python: Not run in the reference's review: Python-to-R bridge; Rscript is unavailable. R code was not executed. R: Reviewed but not run: R wasn't available to the reference's authors.

From the CodeSplash statistics guide (v4), entry 187, updated from the reference's edition 2 (reviewed 14 November 2026) as STAT187.