Skip to content

BUG: Fix HC2/HC3 covariance with leverage-one observations - #10699

Open
aniyow07 wants to merge 6 commits into
statsmodels:mainfrom
aniyow07:fix-hc-leverage-one-10659
Open

aniyow07 wants to merge 6 commits into
statsmodels:mainfrom
aniyow07:fix-hc-leverage-one-10659

Conversation

@aniyow07

@aniyow07 aniyow07 commented Nov 7, 2026

Copy link
Copy Markdown

An observation with leverage one (e.g. a single-observation dummy) has a zero residual, so HC2/HC3 computed 0 / 0. The result was arbitrary standard errors, or inf for all parameters.

  • These observations are now dropped from the HC2/HC3 sandwich, with a ValueWarning. Parameters that depend on them get nan variance. All other parameters match the fit without those observations.
  • cov_params(r_matrix=...) uses nan_dot, so t_test on unaffected parameters stays finite. The robust fvalue is nan in this case.
  • Results without leverage-one observations are unchanged.

Tests cover HC2/HC3 with one or two singleton dummies, a scaled dummy, and WLS. The new tests fail on main. The fast test suite passes.

AI Disclosure

Contributions must comply with the statsmodels AI Policy.

Tick exactly one of the following. If AI tools were used, replace the <...>
placeholders in the second option with the tool name(s) and how the tool's output was
used.

  • No AI tools were used to develop this pull request.
  • AI tools were used.
    Tool(s): Claude : Opus 5.5 (High).
    Used for: drafting the fix and tests, and running the test suite.
    I have personally read, understood, and can explain every line of this diff, and
    have verified the statistical/numerical correctness of the change.

Observations with leverage one, e.g. from a dummy that is one for a single
observation, have a zero residual, so HC2/HC3 computed 0 / 0 and returned
arbitrary or inf standard errors. These observations are now dropped from
the sandwich with a ValueWarning, the variance of parameters that depend on
them is nan, and cov_params with r_matrix uses nan_dot so that nan does not
propagate to restrictions that do not use those parameters.

Closes statsmodels#10659
@josef-pkt

Copy link
Copy Markdown
Member

It looks to me a bit like AI is replacing substantive decisions.

In the "old" times, statsmodels refused to automatically fix an ill-posed problem provided by the user, in this case dropping an observation and an explanatory variable.

I'm not sure what the fix should be.
This might be the correct solution for "outlier" dummies, i.e. single observation dummies. (*)
But my guess is that the problem with high leverage points in HC covariances are more general than this.
(HC covariances can have in many cases weak or bad small sample properties. Parameters that depend only a one or a few observations or points with very high leverage can bring us back to small sample behavior even if the "sample size" is large.)

(*)
One question is whether the standard errors for the remaining parameters are affected by this and are correct.
An outlier dummy is equivalent to dropping the observations for the estimated params, but I'm not sure this applies also to inferential statistics if the outlier dummy is not orthogonal to the remaining explanatory variables.

(aside: I don't remember
Is there a sandwich that uses average hii instead of individual hii?
)

@aniyow07

aniyow07 commented Nov 8, 2026 •

Copy link
Copy Markdown
Author

Hey thanks for looking into this, I think what statsmodel should do is your call, I am fine with changes if required.

This PR doesnt change anything from the base model, params and other cov types are not changed and only changes done are for HC2/HC3 term for hii = 1 where ei=0 and the term is 0/0 which on main gives inf or random answers.

-(*) from what I can tell, the other standard errors are still right even when the dummy isn’t orthogonal as the dummy fits its own oberservation exactly so the other params only depends on the other observations and they have the same residuals and leverage in the regression without that row so their HC2/HC3 standard errors remains same.

Quick comparison of main and this PR (HC3, dummy for one observation):

import warnings
import numpy as np
import statsmodels.api as sm

warnings.simplefilter("ignore")
n, i = 50, 7
for seed in range(4):
    rng = np.random.default_rng(seed)
    x = rng.standard_normal(n)
    y = 1 + 2 * x + rng.standard_normal(n) * (1 + np.abs(x))
    d = np.zeros(n)
    d[i] = 1
    X = np.column_stack([np.ones(n), x, d])
    keep = np.arange(n) != i
    full = sm.OLS(y, X).fit(cov_type="HC3").bse
    drop = sm.OLS(y[keep], X[keep, :2]).fit(cov_type="HC3").bse
    print(f"seed {seed}  HC3 [const, x, dummy] = {np.round(full, 4)}   dropped = {np.round(drop, 4)}")

(0.15.0) ,Google Colab:

Statsmodel version :0.15.0, Numpy version 2.4.6
seed 0  HC3 [const, x, dummy] = [0.2936 0.4922 2.4587]   dropped = [0.2936 0.4922]
seed 1  HC3 [const, x, dummy] = [inf inf inf]   dropped = [0.2166 0.3469]
seed 2  HC3 [const, x, dummy] = [0.2523 0.3323 0.6449]   dropped = [0.2523 0.3323]
seed 3  HC3 [const, x, dummy] = [inf inf inf]   dropped = [0.2746 0.287 ]

The dummy SE and the inf cases on main depend on rounding: on another Linux machine(on main) seed 0 gave 1.6868 and only seed 1 was inf, and on Windows none were inf.

this PR:

seed 0  HC3 [const, x, dummy] = [0.2936 0.4922    nan]   dropped = [0.2936 0.4922]
seed 1  HC3 [const, x, dummy] = [0.2166 0.3469    nan]   dropped = [0.2166 0.3469]
seed 2  HC3 [const, x, dummy] = [0.2523 0.3323    nan]   dropped = [0.2523 0.3323]
seed 3  HC3 [const, x, dummy] = [0.2746 0.287     nan]   dropped = [0.2746 0.287 ]

With this PR, const and x always match the regression without that observation, and the dummy’s SE is nan instead of platform-dependent noise or inf.

Aside: Yes. HC1 uses a global correction based on the average leverage rather than individual leverage values.

@bashtage

Copy link
Copy Markdown
Member

Please add the PR role to the release note, after the issue role: :issue:`10659`, :pr:`10699`. The number is known now that the PR is open, so a small commit is fine. Thanks.

@aniyow07

Copy link
Copy Markdown
Author

@bashtage Thanks, added :pr:10699

@bashtage bashtage left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. The example from the issue now gives NaN for the dummy and matches R's estimatr. Three things need fixing: a 1-D r_matrix raises, the tolerance for ill-conditioned designs, and the warning location. sandwich_covariance.cov_hc2 and cov_hc3 are untouched and still give the old numbers for the issue's seeds; could they use the same helper? Also please say in the release note that HC0/HC1 are not changed.

Comment thread statsmodels/base/model.py Outdated
other = np.asarray(other)
if np.isnan(np.asarray(cov_p)).any():
# nan only propagates to restrictions that use the parameter
dot_fun = nan_dot

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nan_dot fails for a 1-D r_matrix (it ends with C[should_be_nan] = np.nan, but np.dot returns a scalar): OLS(y, X).fit(cov_type="HC3").cov_params(r_matrix=[0, 1, 0]) raises TypeError: 'numpy.float64' object does not support item assignment on the issue's data. 1-D input is accepted here, so please handle it (for example np.atleast_2d and reshape the result back).

@aniyow07 aniyow07 Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed. with nan in the cov it now makes both sides 2-D for nan_dot and reshapes back, so the shapes are the same as np.dot. [0, 1, 0] gives the finite variance now and [0, 0, 1] gives nan. Added a test for the same.

Comment thread statsmodels/regression/linear_model.py Outdated
cov_HC1 = self._HCCM(self.het_scale)
return cov_HC1

def _hc_leverage(self, tol=1e-8):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The absolute 1e-8 does not hold for ill-conditioned designs because h comes from normalized_cov_params: with a constant, calendar year, year**2 and a one-observation dummy (n=40) 1 - h of the dummy is up to 1e-7 and only 130 of 200 seeds warn. A QR of wexog gives |1 - h| < 1e-15 there. Please compute h that way and use a tolerance of order sqrt(eps).

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switched to a pivoted QR of wexog with a sqrt(eps) cutoff. On your year/year² example 1 - h for the dummy is ~1e-16 now, and all 200 seeds warn (vs 130 before). Added 10 of those seeds as a test.

Comment thread statsmodels/regression/linear_model.py Outdated
"one. The HC2/HC3 variance of parameters that depend on them is "
"not identified and is set to nan.",
ValueWarning,
stacklevel=3,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With stacklevel=3 the warning points into statsmodels/tools/_decorators.py, not at the user's line. _stacklevel_outside_statsmodels() in statsmodels/base/covtype.py does this.

@aniyow07 aniyow07 Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't know that helper existed, thanks! Using_stacklevel_outside_statsmodels()now, and there's a test that the warning points at the caller.

"n_dummies, scale, weighted",
[(1, 1.0, False), (2, 1.0, False), (1, 1e6, False), (1, 1.0, True)],
)
def test_hc_leverage_one(cov_type, n_dummies, scale, weighted):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These tests use one seed and still pass with h kept instead of the surrogate 0, or with tol=1e-12 or 1e-4. Please parametrize over the issue's seeds 0-5, call OLS(...).fit().get_robustcov_results(cov_type) as in the issue, and add a case with a legitimate high-leverage observation (1 - h around 1e-4) that must stay finite.

@aniyow07 aniyow07 Nov 22, 2026 •

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now parametrized over seeds 0–5 through get_robustcov_results like in the issue, plus the year/year² case and a high-leverage obs (1 - h ~ 1e-6) that has to stay finite. I tried breaking each fix on purpose and at least one test fails every time.

- Compute the leverage from a pivoted QR of wexog and use a sqrt(eps)
  tolerance, so leverage-one observations are found also in
  ill-conditioned designs.
- Issue the warning at the caller with _stacklevel_outside_statsmodels.
- Fix cov_params with a 1-D r_matrix or other when the covariance has nan.
- Use the same rule in sandwich_covariance.cov_hc2 and cov_hc3.
- Parametrize the tests over the seeds of the issue and add tests for an
  ill-conditioned design, a high-leverage observation that stays finite,
  the warning location, cov_params shapes and the sandwich functions.
- Add versionchanged notes and say in the release note that HC0 and HC1
  are not changed.

xref statsmodels#10659
# Conflicts:
#	statsmodels/regression/tests/test_regression.py
@aniyow07

aniyow07 commented Nov 22, 2026 •

Copy link
Copy Markdown
Author

Thanks for the review! cov_hc2/cov_hc3 in sandwich_covariance now use the same helper. One small difference: they take h from wexog now, which is the same for OLS. Release note says HC0/HC1 are unchanged, and I merged main to fix the conflict.

@aniyow07
aniyow07 requested a review from bashtage November 22, 2026 12:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: HC2/HC3 standard errors are arbitrary (or inf) when an observation has leverage 1, e.g. a single-observation dummy

3 participants