Repository navigation
Conversation
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
|
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. (*) (aside: I don't remember |
|
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: 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: 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. |
|
Please add the PR role to the release note, after the issue role: |
|
@bashtage Thanks, added |
bashtage
left a comment
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
| cov_HC1 = self._HCCM(self.het_scale) | ||
| return cov_HC1 | ||
|
|
||
| def _hc_leverage(self, tol=1e-8): |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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.
| "one. The HC2/HC3 variance of parameters that depend on them is " | ||
| "not identified and is set to nan.", | ||
| ValueWarning, | ||
| stacklevel=3, |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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
|
Thanks for the review! |
NumPy's guide.
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, orinffor all parameters.ValueWarning. Parameters that depend on them getnanvariance. All other parameters match the fit without those observations.cov_params(r_matrix=...)usesnan_dot, sot_teston unaffected parameters stays finite. The robustfvalueisnanin this case.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.
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.