Skip to content

REF/ENH Penalized linear TheilGLS, ridge - #1665

Merged
josef-pkt merged 18 commits into
statsmodels:masterfrom
josef-pkt:penalized_linear
Oct 16, 2017
Merged

josef-pkt merged 18 commits into
statsmodels:masterfrom
josef-pkt:penalized_linear

Conversation

@josef-pkt

@josef-pkt josef-pkt commented May 10, 2014 •

Copy link
Copy Markdown
Member

some enhancements cleanup and unit test for TheilGLS

Still WIP but ready for TravisCI

TODOs

more unit tests

  • inherited results, llf, inherited aic, bic seems correct in close to OLS cases
  • check fit_minic, no reference implementation ? scikit-learn ?
    (R MASS lm.ridge uses a different parameterization, Longley looks weird also in R)
  • test case with non-diagonal prior
  • GLS, non-iid errors have no example nor tests

other

  • register extra keywords for recreating model
  • code cleanup
  • check robust cov
  • HCxx_se raise exception, maybe support later
  • summary - adjustments to inherited version ?

most likely not in this PR:

  • computational efficient implementation for special case of Ridge, SVD based.
  • iterative estimation, improve support for patterned priors, patsy/formula integration ?
  • estimating prior parameters ?

unclear

perfect multicollinearity affects the inference for the base parameters, cov_params, bse, and similar.
Can I separate the effect? eg. precise fixed effects and imprecise random effects.
Note: even a small prior resolves perfect multicollinearity in the expected way for the params

bias: cov_params is pretty standard, but should we do something about the bias. Confidence interval will be centered around a biased estimate if prior information is biased as in Ridge.

extra references

reference for HC robust cov not yet available as pdf (in print)
http://www.tandfonline.com/doi/abs/10.1080/03610918.2012.750354#.U3LRKleFUy4
Muhammad Aslam "Using Heteroscedasticity Consistent Standard Errors for the Linear Regression Model with Correlated Regressors" Communications in Statistics - Simulation and Computation
(I didn't read it yet, but derivation of robust sandwiches is pretty generic, only Theil cov_type='data-prior' has and extra additive term that doesn't fit the current pattern.)
edit no available as pdf, in Monte Carlo comparison (looking at graphs) HC3 has best coverage, using effective degrees of freedom.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling 09103a4 on josef-pkt:penalized_linear into b472807 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

forgot about py3 compatibility,
range is not from statsmodels.compat

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage remained the same when pulling a3b242b on josef-pkt:penalized_linear into b472807 on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

nice paper http://www.jstor.org/stable/1241927
write code then look for which paper provides the theoretical justification.

R beta + v = q
Theil Goldberger use cov_type='data_prior' under the assumption that q is a random variable.
Mittelhammer, Conway get the cov_type='sandwich' under the assumption that q is non-random given by the prior beliefs, "best guess".

'sandwich' is also used in Ridge literature, and I think it just follows immediately from properties of M-estimators.

extra Mittelhammer, Conway mention a test for risk superiority of the TG estimator.

@josef-pkt josef-pkt added this to the 0.7 milestone Aug 17, 2014
@josef-pkt josef-pkt modified the milestones: 0.8, 0.7 Feb 4, 2015
@josef-pkt josef-pkt mentioned this pull request Jun 8, 2015
7 tasks
@josef-pkt josef-pkt mentioned this pull request Jul 4, 2015
2 of 15 tasks
@josef-pkt

Copy link
Copy Markdown
Member Author

bump, check and merge with warnings if there are still results missing.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased (no merge conflicts)

note: this is still in the sandbox in a generically named penalized.py. Where should it go?

AFAIR:
low test coverage, no equivalent function in other packages ?
otherwise should be ready to merge. generic PenalizedMixin #3677 would work as cross-check, GAM uses the same structure of normal prior penalization, but for GLM instead of linear/OLS

@josef-pkt

Copy link
Copy Markdown
Member Author

travis: precision failure in some python, rtol=1e-11 in test_theil.TestTheilTextile.test_no_penalization

@coveralls

coveralls commented May 20, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.03%) to 90.401% when pulling b44223d on josef-pkt:penalized_linear into 90e2af8 on statsmodels:master.

@josef-pkt josef-pkt modified the milestones: 0.9, 0.8 Jul 26, 2017
@josef-pkt

Copy link
Copy Markdown
Member Author

After trying out the examples (copied from __main__ a bit

  • parameter estimation and penalization looks good in examples

  • fit_minic also looks good aicc and gcv penalization weights are close to each other (same neighborhood)

  • model.normalized_cov_params becomes wrong after repeated fit

  • however, results.bse corresponds to or changes with the cov_type. I haven't figured out how that happens

  • possibly too much inheritance, fit_minic(method='bic') works but uses inherited bic which is not overwritten in TheilGLS results

  • bse/cov_params need unit tests or checking. I think testing the equivalence to OLS might not be enough. check whether extreme penalization (setting a params to zero) has correct cov_type.

  • df_resid : construction in results.__init__ looks fine

  • hatmatrix_diag uses model.normalized_cov_params, that could become stale except it is computed and cached before it can get stale because of the df_resid call.

  • fit_minic name is a bit misleading because it doesn't return a results instance, it returns minic penalization parameter

@josef-pkt

Copy link
Copy Markdown
Member Author

Bug
Note, df_resid is computed differently depending on cov_type and model.normalized_cov_params
as a consequence, scale df correction varies by cov_type

and, the only difference in cov_params between the two cov_types comes from the scale df

>>> np.max(np.abs(res_aicc_s.bse / res_aicc_p.bse - np.sqrt(res_aicc_s.scale / res_aicc_p.scale)))
Out[84]:
1.1102230246251565e-16

@josef-pkt

Copy link
Copy Markdown
Member Author

naming: don't use lambd for penalization weight in fit.
most fit_regularized use alpha, but I want something like pen_weight

@josef-pkt

Copy link
Copy Markdown
Member Author

I'm a bit stuck (as a programming exercise)

What is df_resid supposed to be? Should it really depend on cov_type?

I'm trying to fix model.normalized_cov_params to be independent of cov_type

If I use xpxi, self.normalized_cov_params = xpxi, then equivalence to OLS unit tests fail
If I use self.normalized_cov_params = xpxi_sandwich, then unit test for textile comparing to Stata fails. However, that already has correction factors because I didn't/don't like the choices in tgmixed. Based on code comments in unit tests, their scale and df_resid are from OLS.

Even when I fix the corrfact for textile bse test case, then pvalues and conf_int still fail.
The easiest "fix" might be to add a scale option, so we can try with the OLS scale, and test if only the scale estimator differs to tgmixed.

@josef-pkt

Copy link
Copy Markdown
Member Author

another possible problem:
setting/overriding df_resid in TheilResults.__init__ after super call is fragile, if some cached results are computed in super with the inherited default df_resid. For example this will be the case, I think, when we go through generic cov_type handling.

@josef-pkt

Copy link
Copy Markdown
Member Author

commit "try refactor normalized_cov_params, cheat in test against tgmixed"
is a bit dirty to see whether it works, with partial reverse engineering of tgmixed results in unit tests.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.737% when pulling a2fcfe4 on josef-pkt:penalized_linear into 326ae0c on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.737% when pulling a2fcfe4 on josef-pkt:penalized_linear into 326ae0c on statsmodels:master.

@josef-pkt

josef-pkt commented Oct 15, 2017 •

Copy link
Copy Markdown
Member Author

another use case and possible test case based on equivalence

using theil-goldberger for data combination

splitting sample and using the first part as prior for the second part.
params agree well
The only thing that I don't understand is why I need the ratio of residual scales as extra penalization or prior weight res_ols1.scale / res_ols0.scale. I thought this should already be built into the penalization weight normalization.

edit Most likely this comes from the use of the GLS scale sigma2_e in the weight between data and prior. We don't update this because it is irrelevant when we choose the weight with minic for example.

In [167]:
n05 = nobs // 2
np.random.seed(987125)
shuffle_idx = np.random.permutation(np.arange(nobs))
ys = y[shuffle_idx]
Xs = X[shuffle_idx]
res_ols0 = sm.OLS(ys[:n05], Xs[:n05, :5]).fit()
res_ols1 = sm.OLS(ys[n05:], Xs[n05:, :5]).fit()

w = res_ols1.scale / res_ols0.scale   #1.01
mod_1 = TheilGLS(ys[n05:], Xs[n05:, :5], r_matrix=np.eye(5), q_matrix=res_ols0.params, sigma_prior=w * res_ols0.cov_params())
res_1 = mod_1.fit()
res_olsf = sm.OLS(ys, Xs[:, :5]).fit()
print('ols  ', res_olsf.params)
print('theil', res_1.params)
ols   [ 5.81954943 -0.75691643  0.09666926  1.1554354   0.90451147]
theil [ 5.81954943 -0.75691643  0.09666926  1.1554354   0.90451147]

@josef-pkt

josef-pkt commented Oct 15, 2017 •

Copy link
Copy Markdown
Member Author

however, bse doesn't fully match up, and sandwich matches better than "data-prior"

In [173]:
print('ols    ', res_olsf.bse)
print('theil-p', res_1.bse)     # cov_type='data-prior'
print('theil-s', res_1s.bse)   # cov_type='sandwich'

ols     [ 0.26636831  0.1547747   0.86339653  0.86339653  0.86339653]
theil-p [ 0.26711852  0.15521061  0.86582824  0.86582824  0.86582824]
theil-s [ 0.26660948  0.15491483  0.86417826  0.86417826  0.86417826]

One possibility, we are pooling information for the params, but we are not pooling information for the scale.
Either we need another scale correction, or it is because the conjugate normal case is derived under normality with known variance assumption.

Even though we don't match very closely, the results are still close, e.g. the bse for the two subset OLS are, so we are still pooling cov_params with Theil almost the same as the pooled OLS.

print(res_ols0.bse)
print(res_ols1.bse)

[ 0.38140552  0.21949276  1.92393876  1.36673492  1.36167682]
[ 0.3738958   0.2198737   0.97009927  1.11823741  1.11816121]

@josef-pkt

Copy link
Copy Markdown
Member Author

cov_type="data-prior" is off by a constant factor, so it's a small scale pooling or correction issue, I guess.

1 / (res_olsf.bse / res_1.bse)
array([ 1.01414357,  1.01414357,  1.01414357,  1.01414357 ....

in another run, with a different generated random sample, the factor is 0.91310453, so it's data dependent.

a bit tricky (not completely clear without going through the math):

in the weighted mean for params we use sigma2_e * lambd to compute xpx. however lambd is set to w the subsample scale ration.
In the covariance we multiply xpxi by the new, final scale, which multiplies both the component from data and from prior.
I guess it's not really worth worrying about this for the penalization case, but we might want to have cleaner structure for data combination.
(It would have been useful for unit test to be able to use exact equivalence.)

@josef-pkt

Copy link
Copy Markdown
Member Author

relationship to fit_regularized elastic net
reverse engineering alpha, trial and error only, I didn't try to figure out the normalization for elasticnet alpha

)
In [169]:
res_olsf.model.fit_regularized(alpha=0.65784254, L1_wt=0).params
Out[169]:
array([ 1.49953012,  1.52156642,  0.03113179,  0.03650024,  0.02768384,
        0.01913562,  0.03457198,  0.01286132,  0.03242746,  0.00531061])

In [97]:
mod_r = TheilGLS(ys, Xs[:, :k], r_matrix=np.eye(k), q_matrix=None, sigma_prior=0.01)
res_r = mod_r.fit(cov_type='data-prior')
res_r.params
Out[97]:
array([ 1.49953012,  1.52156642,  0.03113179,  0.03650024,  0.02768384,
        0.01913562,  0.03457198,  0.01286132,  0.03242746,  0.00531061])

@josef-pkt

Copy link
Copy Markdown
Member Author

I lowered the sample size for the unit tests compared to my experimentation script from 600 to 300.
Now, cov_type sandwich has much smaller bse than cov_type data-prior in the example.
I don't have an explanation for this. I would have expected bse to be larger with the sandwich, but without having a theoretical justification.
scale is the same for both cov_types

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.754% when pulling 51503b6 on josef-pkt:penalized_linear into 326ae0c on statsmodels:master.

1 similar comment
@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.754% when pulling 51503b6 on josef-pkt:penalized_linear into 326ae0c on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

as reference here is my notebook https://gist.github.com/josef-pkt/728ffbca867f0b4925b88383dda3cc7b
(revision 2 is restart+run all with current branch)
example 3 does not have random seed, but prints it, so running example 3 out of context of full notebook changes the random sample.

@josef-pkt

Copy link
Copy Markdown
Member Author

Given that the model is still in the sandbox, I think we can merge essentially as it is now.

The contrast/restriction helper functions need to be consolidated somewhere as we merge also the other penalized PRs. Also we get more generic code with similar purpose to test against, i.e. there is some overlap in parts of it with the GAM L2 penalization.

one inconsistency:
the inherited aic, bic use the loglike definition, the special aicc and gcv use a ssr/mse based definition
(see also standalone function for information criteria). This does not matter for choosing penalization using one of the criteria.

@josef-pkt

Copy link
Copy Markdown
Member Author

Note: cov_type='sandwich' is not HC, it is the M-estimator sandwich assuming iid observations/residuals (or at least variance uncorrelated or independent of exog). (that's similar to RLM, IIRC)

I didn't check any of the standard cov_types.
currently raises if other cov_types are specified
ValueError: cov_type has to be 'sandwich' or 'data-prior'

@josef-pkt

Copy link
Copy Markdown
Member Author

I added some renamings, a bit of cleanup and regression tests for select_pen_weight.
gist notebook at revision 3 for current master

merge when green, so I can go back to other things.

@coveralls

coveralls commented Oct 16, 2017 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.1%) to 81.771% when pulling 59bb55e on josef-pkt:penalized_linear into 326ae0c on statsmodels:master.

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, merging

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants