Skip to content

ENH: large categorical, OLSAbsorb with sparse projection - #2774

Open
josef-pkt wants to merge 7 commits into
statsmodels:mainfrom
josef-pkt:absorb_fixed_effects
Open

josef-pkt wants to merge 7 commits into
statsmodels:mainfrom
josef-pkt:absorb_fixed_effects

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Jan 19, 2016 •

Copy link
Copy Markdown
Member

see #2568 for some design discussion, and references to different algorithms

We are partialing out fixed effects in panel data, or any categorical factor variable with many levels.

This includes currently only a sparse version for general multi-way factors.

Warning: some results in returned OLS are still wrong (fvalue, llf, ...)
see docstrings and comments for other current definitions and limitations.

currently missing: function that creates sparse dummy representation uses currently a dense intermediate array

see also #2711 for OLSSparse, is currently SparseOLS

module names and paths are not settled yet.
The projection class needs to be public.


Design issues

  • exog, wexog: currently I have the transformed exog in wexog using whiten
    However, several things use the original exog.

    • OLS.loglike doesn't use wexog/wresid, consequence of aic, bic
    • fittedvalues and resid are for original data in model, i.e. exog, endog (ignore absorbed effects)
    • wresid, scale, ssr, ess, mse_resid, rsquared, rsquared_adj
      are fine, those use wexog, transformed in current case
    • bse, wald inference, t_test, pvalues are fine, (except for parameter slicing and constant definition)
  • df_model:

    • still need to override

    • mse_model, fvalue (nonrobust) is incorrect without adjusting df_model
  • predict, fittedvalues, residuals
    The WLS version matches almost everything with the main exception in predict fittedvalues and resid. Those are designed for the values on the original scale and variable without taking the predictive effect of fixed effects into account. For predict we would have to solve for the fixed effects first before we can do any prediction.
    see comment below ENH: large categorical, OLSAbsorb with sparse projection #2774 (comment)

    • fittedvalues, residuals, override and retro-fit, because absorbed wresid is ols resid:
    >>> np.max(np.abs(res_ols.fittedvalues - (res_absorb.model.endog - res_absorb.wresid)))
    2.6645352591003757e-15
    >>> np.max(np.abs(res_ols.resid - res_absorb.wresid))
    2.6645352591003757e-15
    
    • predict: we need an option, doing full prediction is more expensive (not much more expensive after we have the fixed effects params, and we can store those)
  • inference, standard errors for fixed effects
    I don't see a way to calculate those without creating the full sparse inv(x'x) where we can restrict x to the fixed effects. I think inv(x'x) might not be very sparse for a general case. We could store only the diagonal if we have memory problems, but we still need to calculate for example LU xtx.solve(np.eye) in chunks of np.eye columns. Can the argument for LU solve be a dense low memory dtype (e.g. bool)?
    Orme/Yamagata. 2014: robust F-test for joint hypothesis that all individual effects are zero


applicability of different absorb methods


References

Orme, Chris D., and Takashi Yamagata. 2014. “A Heteroskedasticity-Robust F-Test Statistic for Individual Effects.” Econometric Reviews 33 (5-6): 431–71. doi:10.1080/07474938.2013.824792.

Related

  • transform models: this is similar to using an internal transformation of the model
  • ddof for OLS, for OLS with absorbing by users

@josef-pkt

Copy link
Copy Markdown
Member Author

Based on TravisCI errors, the use of sparse LU solve requires at minimum scipy 0.14.
(From what I remember, it wasn't possible to call it with multivariate endog in the old times.
But since it worked with the scipy that I use, I used vectorized projection.)

@josef-pkt
josef-pkt force-pushed the absorb_fixed_effects branch from 24bf340 to 8928809 Compare January 20, 2016 05:56
@josef-pkt

Copy link
Copy Markdown
Member Author

current status: using wexog, overriding df_resid, no other changes in subclass
params shaped attributes use slice for included exog without constant

result of np.allclose at default precision

>>> for a, r in no_fail: print(a, ' -> ', r)
... 
HC0_se  ->  True
HC1_se  ->  True
HC2_se  ->  False
HC3_se  ->  False
_data_attr  ->  True
_wexog_singular_values  ->  False
aic  ->  False
bic  ->  False
bse  ->  True
centered_tss  ->  True
condition_number  ->  False
df_model  ->  False
df_resid  ->  True
eigenvals  ->  False
ess  ->  True
f_pvalue  ->  True
fittedvalues  ->  False
fvalue  ->  False
k_constant  ->  True
llf  ->  False
mse_model  ->  False
mse_resid  ->  True
mse_total  ->  False
nobs  ->  True
params  ->  True
pvalues  ->  True
resid  ->  False
resid_pearson  ->  True
rsquared  ->  True
rsquared_adj  ->  True
scale  ->  True
ssr  ->  True
tvalues  ->  True
uncentered_tss  ->  False
use_t  ->  True
wresid  ->  True

this doesn't check/slice yet correctly the 2d covariances, see standard errors for results

>>> failing
['cov_HC0', 'cov_HC1', 'cov_HC2', 'cov_HC3', 'cov_kwds', 'cov_type', 'model', 'normalized_cov_params']

@josef-pkt

Copy link
Copy Markdown
Member Author

same after adding

        self.exog = self.wexog
        self.endog = self.wendog
        self.df_model = self.df_model + self.k_absorb - 1

we get a different pattern (also fixed effects calculation fails)

aic  ->  True
bic  ->  True
centered_tss  ->  False
df_model  ->  True
df_resid  ->  True
ess  ->  False
f_pvalue  ->  True
fittedvalues  ->  False
fvalue  ->  False
k_constant  ->  True
llf  ->  True
mse_model  ->  False
rsquared  ->  True
rsquared_adj  ->  False
scale  ->  True
ssr  ->  True
uncentered_tss  ->  False
use_t  ->  True
wresid  ->  True
HC0_se  ->  True
HC1_se  ->  True
HC2_se  ->  False
HC3_se  ->  False
_data_attr  ->  True
_wexog_singular_values  ->  False
aic  ->  True
bic  ->  True
bse  ->  True
centered_tss  ->  False
condition_number  ->  False
df_model  ->  True
df_resid  ->  True
eigenvals  ->  False
ess  ->  False
f_pvalue  ->  True
fittedvalues  ->  False
fvalue  ->  False
k_constant  ->  True
llf  ->  True
mse_model  ->  False
mse_resid  ->  True
mse_total  ->  False
nobs  ->  True
params  ->  True
pvalues  ->  True
resid  ->  True
resid_pearson  ->  True
rsquared  ->  True
rsquared_adj  ->  False
scale  ->  True
ssr  ->  True
tvalues  ->  True
uncentered_tss  ->  False
use_t  ->  True
wresid  ->  True
>>> 

@josef-pkt

Copy link
Copy Markdown
Member Author

Here is another case:
adjust df_model, df_resid
don't change endog, exog, just wendog, wexog
subclass WLS which uses weighted in likelihood calculations

The only differences to dense OLS seem to be in the

  • fittedvalues, resid, predict and the uncentered sum of squares, and in
  • collinearity measures, eigenvalues, condition number, ...
  • HC2_se and HC3_se differ, HC0 and HC1 agree, which I'm a bit surprised about.
    (other cov_types not checked yet. I was expecting a theoretical difference in what heteroscedasticity or correlation with exog is included in sandwich)

I guess centered sum of squares are correct because of the constant handling (average of fixed effects should be zero in the current version)

I currently only check a balanced panel data set.

This looks like a keeper, I will start design choices for predict in PR description on top

aic  ->  True
bic  ->  True
bse  ->  True
centered_tss  ->  True
condition_number  ->  False
df_model  ->  True
df_resid  ->  True
eigenvals  ->  False
ess  ->  True
f_pvalue  ->  True
fittedvalues  ->  False
fvalue  ->  True
k_constant  ->  True
llf  ->  True
mse_model  ->  True
mse_resid  ->  True
mse_total  ->  True
nobs  ->  True
params  ->  True
pvalues  ->  True
resid  ->  False
resid_pearson  ->  True
rsquared  ->  True
rsquared_adj  ->  True
scale  ->  True
ssr  ->  True
tvalues  ->  True
uncentered_tss  ->  False
use_t  ->  True
wresid  ->  True
>>> 

@josef-pkt

Copy link
Copy Markdown
Member Author

The last commits add _group_demean_iterative as trial version for near balanced data.
We convert to wide format with nans and iteratively nan-demean along axis.
This is an experimental version, that has still a lot of space for improvement for different use cases, e.g. take existing nd array as argument.
However, it takes just a few iterations with 10% probability of missing cells, so a lot of effort on efficient group demeaning might not be very relevant, e.g. compared to memory optimization and reusing existing data structures and functions like pandas.

reshaping between long and wide format is not "trivial" with numpy, especially for general ndim. Currently it is specialized for simple two-way fixed effects.

There is a skipped test t_est_demean which doesn't work with the current _group_demean_iterative. The example is not a simple two-way effect (with unique multi-index), because I made a mistake in the use of np.tile in the original test case.
This is an example where the general purpose sparse implementation doesn't require any assumptions on the structure of the categoricals/fixed effects. I didn't check yet why _group_demean_iterative fails in this case.

*OLS with ddof: *
The skipped test case uses OLS directly with the projected exog and endog and a ddof correction. Similar to before, params and wald inference agree, fvalue and some other things don't agree with OLSAbsorb.
Adding ddof as OLS option requires a warning in the docs or adjustments in some of the extra results that are not directly related to ddof.

@josef-pkt

Copy link
Copy Markdown
Member Author

numpy <= 1.7 doesn't have nanmean

@josef-pkt

Copy link
Copy Markdown
Member Author

typo in commit message: skip test if < 1.8.0

@josef-pkt

Copy link
Copy Markdown
Member Author

checking briefly with Stata areg documentation:

f-value is against constant plus FE dummies, same as simply using OLS on absorb-transformed data.
areg report f-test for all dummies together, but only if cov_type='nonrobust'
areg docs mention that cov_params assumes large T, fixed N asymptotics, and xtreg be should be used for large N asymptotics, description is not clear how cluster differs in the two cases, my guess, is the small sample degrees of freedom correction. (However, IIRC, cluster robust cov_params have problems it T>N.) N is n_groups the number of clusters or cross-section units.
Also based on the areg description, predict does not take FE dummies into account. constant is defined as here. It looks like I got the idea to add grand means back in from some Stata description.

So, it looks like areg is doing essentially the same thing as OLS with pretransformed data and ddof, and can be used for unit tests. not checked yet llnull and postestimation commands.
I don't know yet whether and how to get any inference for the fixed effects.

Difference to areg: We can absorb any number of fixed effects or categorical variables, not just one.

from statsmodels.tools._sparse import PartialingSparse, dummy_sparse

def cat2dummy_sparse(xcat, use_pandas=False):
"""categorical to sparse dummy, use pandas for quick implementation

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

outdated pandas, now version using sparse directly

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.

1 participant