Repository navigation
BUG: Use exog centroid as center in rainbow test use_distance (#9103) - #9903
Merged
Merged
Conversation
linear_rainbow(res, use_distance=True) ordered the observations by their Mahalanobis distance to an arbitrary middle-indexed observation (exog[nobs // 2]) and built the covariance from the deviations around that single point. Both depend on the raw row order of the data, so the same data supplied in a different order produced a different F-statistic and p-value. In addition, the covariance was singular whenever exog contained a constant column, which raised a LinAlgError for the typical regression model. Measure the Mahalanobis distances from the exog centroid (the multivariate mean) instead, following Utts (1982) and matching R's lmtest::raintest. The centroid is order invariant, so the statistic no longer depends on the row order, and using the pseudo-inverse of the covariance handles a constant (or otherwise rank-deficient) column gracefully. Order the observations with a deterministic lexsort keyed on the distance (primary) and the exog values (tie-break) rather than the non-stable argsort, so that exact distance ties from discrete or duplicated regressors do not reintroduce order dependence; endog is never used as a tie-break key. The center keyword no longer has any effect; it is deprecated and now emits a FutureWarning. Add regression tests that assert order invariance for continuous data (with and without a constant column) and for a discrete integer-lattice design (which ties distances and exercises the tie-break), equivalence to ordering manually by the centroid distance, and the center deprecation warning. The previous test_rainbow_smoke_centered test was smoke-only and is superseded. closes #9103 This change was drafted with the assistance of Claude (Anthropic). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Contributor
There was a problem hiding this comment.
Pull request overview
Fixes linear_rainbow(..., use_distance=True) so that observation ordering is based on Mahalanobis distance to the exog centroid, making the rainbow test invariant to row order and robust to singular covariance structures (e.g., intercept/constant columns).
Changes:
- Update
linear_rainbowto center Mahalanobis distances on theexogcentroid, usepinv, and apply deterministic tie-breaking vialexsort. - Deprecate and ignore the
centerkeyword whenuse_distance=True, emitting aFutureWarning. - Replace the prior smoke test with regression tests that assert order invariance (continuous + discrete/ties), manual ordering equivalence, and deprecation behavior.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| statsmodels/stats/diagnostic.py | Reworks use_distance=True ordering to use centroid + pinv and deterministic tie-breaking; adds documentation and center deprecation warning. |
| statsmodels/stats/tests/test_diagnostic.py | Adds targeted regression tests for order invariance, tie handling, manual ordering equivalence, and center deprecation warning. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Comment on lines
1184
to
+1187
| center : {float, int}, default None | ||
| If a float, the value must be in [0, 1] and the center is center * | ||
| nobs of the ordered data. If an integer, must be in [0, nobs) and | ||
| is interpreted as the observation of the ordered data to use. | ||
| Deprecated and ignored. The center used to order the observations | ||
| when ``use_distance`` is True is always the exog centroid (the | ||
| multivariate mean). Passing a value emits a ``FutureWarning``. |
Comment on lines
+1252
to
+1262
| if center is not None: | ||
| warnings.warn( | ||
| "The center keyword is deprecated and no longer has any " | ||
| "effect. The Mahalanobis distances used to order the " | ||
| "observations are now measured from the exog centroid (the " | ||
| "multivariate mean) rather than from an individual " | ||
| "observation, so that the rainbow test no longer depends on " | ||
| "the order of the observations (Utts, 1982).", | ||
| FutureWarning, | ||
| stacklevel=2, | ||
| ) |
Member
|
@copilot please fix the merge conflicts in this pull request. |
Member
|
Thanks. LGTM. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
closes #9103
Why
linear_rainbow(res, use_distance=True)is supposed to order the observations bytheir multivariate distance from the center of the design, so the "central
subset" used by the rainbow test is chosen automatically and the result does
not depend on the order in which the rows happen to be stored.
The current implementation instead uses an arbitrary, order-dependent point as the
center (
statsmodels/stats/diagnostic.py):Two problems follow:
exog[nobs // 2]is whateverobservation sits in the middle row, and the covariance
VIis the secondmoment about that single point. Permuting the rows changes the center, hence
the distances, hence the central subset, hence the statistic.
column of
exog - center_obsis exactly zero, soerr.T @ erris singular andnp.linalg.invraisesLinAlgError. Theexceptbranch subtractsexog.mean(0), also zero on the constant column, so it raises again. Souse_distance=Truefails outright for the most common case (a model with aconstant).
The multivariate analogue of "central observations" is distance from the data
centroid (the multivariate mean), per Utts (1982), The rainbow test for lack
of fit in regression.
R'slmtest::raintestalso centers on the mean. This wasconfirmed in the issue thread by @josef-pkt ("I agree that there is a problem with
the current code ... R uses the mean") and the reporter @SvenSerneels ("use the
mean for both univariate and multivariate cases").
Reproduction (before)
Same data, 5 random row permutations,
use_distance=True:The conclusion flips from clearly non-significant (p=0.28) to significant (p=0.002)
purely from the row order. With a constant column the same call raises
LinAlgError: Singular matrix.What
Measure the Mahalanobis distances from the
exogcentroid, with a deterministictie-break:
statistic) no longer depends on row order. This follows Utts (1982) and R's
lmtest::raintest. (The subset itself remains the middle band of the distanceranks — the same
[lowidx:uppidx]slice shared with theorder_bypath — notUtts' "closest
frac" subset; that pre-existing slicing is unchanged.)argsort→lexsort). With the centroid fix alone,the default
np.argsort(non-stable quicksort) still left the result orderdependent whenever Mahalanobis distances tie and the tied rows straddle the
subset boundary — common with discrete or duplicated regressors.
np.lexsortkeys on distance (primary) and the exog columns (secondary), so ties are broken
by regressor values, a property of the observation rather than its position.
endogis deliberately not a tie-break key: breaking ties by the responsewould make subset membership depend on
y, a statistical defect. Among exactlyequidistant points any deterministic choice is valid.
inv→pinv. The covariance is the sample covariance aboutthe mean (what the old
exceptbranch already computed). Thetry/except—whose purpose @josef-pkt noted he could not recall — is removed. On a constant
column the pseudo-inverse contributes 0 to the distance (the constant equals its
own mean), so the typical intercept model runs instead of raising.
pinvequalsinvfor a full-rank covariance, so relative to the centroid approach theordering for models without a constant is unchanged (it of course differs from
the old middle-row center, which was the bug).
centerkeyword no longer has a meaning under the corrected definition, so itis deprecated: passing it emits a
FutureWarningand is otherwise ignored.After
Tests
test_rainbow_smoke_centeredwas smoke-only and is replaced by real regressiontests in
statsmodels/stats/tests/test_diagnostic.py:test_rainbow_use_distance_order_invariant[False|True]— continuous data,statistic identical across permutations, with/without a constant (the constant
case also exercises the former
LinAlgError). Targets the centroid fix.test_rainbow_use_distance_order_invariant_discrete— discrete integer-latticedesign (every exog row distinct but many exact distance ties), invariant across
permutations. Targets the
lexsorttie-break; fails withargsorteven afterthe centroid fix.
test_rainbow_use_distance_matches_manual_ordering— equals ordering byMahalanobis distance to the centroid (recomputed independently) via the standard
order_bypath.test_rainbow_center_deprecated— passingcenterwarns and doesn't change theresult.
All fail on
main;pytest statsmodels/stats/tests/test_diagnostic.py -q→138 passed. The value-assertingtest_rainbowusesuse_distance=False(untouched),so no reference values change.
Notes for the maintainer (scope / decisions to confirm)
centerdisposition. Deprecated (non-breaking) rather than removed — it hasno coherent meaning once the center is the centroid. You may prefer to remove it
(no test coverage / documented users) or repurpose it — see (2). Left in
place so that door stays open.
of central observations." I implemented the mean, matching Utts (1982), R's
raintest, and @SvenSerneels.centercould become acenter={"mean","median"}selector in a follow-up (another reason I deprecated rather than deleted it).
pinv. Fixing the order-dependence alone (mean +inv) would leave theLinAlgErrorin place.pinvresolves both. Happy tosplit if you'd rather scope this strictly to order-dependence — but they share
the same lines.
lexsorttie-break is order-invariant for tieddistances from discrete/duplicated regressors, with one honest exception: two
rows with identical exog but different
endogstraddling the subset boundarycan't be disambiguated without ordering by the response (which we must not),
so they keep input order. Rare, documented in
Notes. A different key order is aone-line change.
centroid ordering, not R (unavailable here). A hard
lmtest::raintestcross-checkvalue could be added if you want one.
Conventions
this
BUG:-prefixed PR under the 0.15 milestone is picked up automatically.