Skip to content

Absorbing fixed effects #2568

Open
Open

Description

@stoffprof

The absorption technique for estimating models with fixed effects that is available in Stata and SAS is not currently part of statsmodels. It is quite useful when one wants to include many fixed effects but is not interested in their individual estimates.

The Stata documentation on this technique ("areg") is here. Discussion of the SAS implementation is here.

See also @josef-pkt's discussion here.

Activity

  1. josef-pkt commented on Aug 1, 2015

    @josef-pkt
    Member

    robust covariance:
    Stata has robust (HC) and cluster robust standard errors.
    It's not clear to me whether applying the standard robust calculations applied to the demeaned data would be correct. According to my intuition we would need some adjustments to allow for panel specific heteroscedasticity. (HC on non-dummy exog would only correct for correlation between those exog and the variance of the error) ???

    edit see also #2758 robust standard errors with fixed effects incidental parameters

  2. added this to the 0.8 milestone on Aug 1, 2015
  3. josef-pkt commented on Aug 1, 2015

    @josef-pkt
    Member

    hypothesis test:

    Stata's areg doesn't provide tests for dummy fixed effects.
    We don't have the relevant calculations for Wald tests.
    But we can use LR or F tests. SAS has standard ANOVA table, AFAICS from the documentation.

    vce(robust)
    Running an example, the standard errors of regress and areg are identical for slope coefficients with vce(robust). Coefficient for constant and it's standard errors differ.

  4. josef-pkt commented on Aug 2, 2015

    @josef-pkt
    Member

    Another part that needs to be changed for this is predict and several results for postestimation.
    Stata has the prediction standard errors, but I don't know yet how we would get the part that relates to the estimation of the absorbed fixed effects.

    More general model and question:
    How do we get post estimation results for models with partialled out effects,
    y = x1 b1 + x2 b2 + u estimated via ey|x2 = ex1|x2 b1 + u ?
    ey, ex1 are residuals from projection on x2

  5. josef-pkt commented on Aug 2, 2015

    @josef-pkt
    Member

    Panel PR #1133 has a full results instance for the FE/Within estimator.
    It uses the same demeaning as areg.

    Stata's areg mentions the differences between areg and xtreg, fe but I don't see the difference yet. It might be mainly the defaults for cov_params.

  6. stoffprof commented on Aug 3, 2015

    @stoffprof
    Author

    There's also Stata package reghdfe that allows absorption of very large numbers of multiple fixed effects. I haven't used it yet, but it could be another source for ideas for implementation.

  7. josef-pkt commented on Aug 3, 2015

    @josef-pkt
    Member

    @Itzybitzy Thanks for the link, Looks interesting and useful, and it has an explicit license (MIT)

    SAS mentions absorbing multiple factors but I didn't see a reference and the only example is for nested factors.
    based on brief look:
    reghdfe uses a iterative fixed point algorithm https://github.com/sergiocorreia/reghdfe/blob/master/docs/explanation.pdf but I don't know how difficult it would be to implement it and to get it to work.
    Mata and Stata code actually looks "almost readable"

    As an alternative, I thought using scipy.sparse to partial out the factors would be worth investigating. That should be pretty fast if all large matrices stay sparse enough.

  8. josef-pkt commented on Sep 30, 2015

    @josef-pkt
    Member

    related: I recently saw that there is also a Julia package in the works https://github.com/matthieugomez/FixedEffectModels.jl
    which seems to use a sparse solver for getting the partialled out variables (residuals of projection)
    (includes instrumental variables)

  9. josef-pkt commented on Jan 14, 2016

    @josef-pkt
    Member

    two references:

    Somaini, P. & Wolak, F. (2015). An Algorithm to Estimate the Two-Way Fixed Effects Model. Journal of Econometric Methods, 5(1), pp. 143-152. Retrieved 14 Jan. 2016, from doi:10.1515/jem-2014-0008
    (I don't have access)
    http://economics.mit.edu/files/8529 working paper version

    "New methods to estimate models with large sets of fixed effects with an application to matched employer-employee data from Germany" https://ideas.repec.org/p/iab/iabfme/201201_en.html
    too long to read and is focused on matched data like firm-employee matched micro data.
    This matched data might be just a general crossed two-way effect, firm dummies and employee dummies.

  10. josef-pkt commented on Jan 14, 2016

    @josef-pkt
    Member

    The Somaini, P. & Wolak, F. (2015) article looks good and not too difficult to implement. Two way fixed effects only, not a generic solution. (I think it could be extended to more than two by repeated partitioned matrix inverse, but the size of the partitions would grow.)

    Their simulation results show that they are faster than areg and similar procedures in these cases.

    (I didn't quite understand their distinction between dense and sparse panels.)

  11. josef-pkt commented on Jan 15, 2016

    @josef-pkt
    Member

    The Somaini and Wolak approach seems to be standard (but not referenced by them)

    Baltagi, Badi H., Peter Egger, and Michael Pfaffermayr. Panel Data Gravity Models of International Trade. No. 4616. CESifo Group Munich, 2014. https://ideas.repec.org/p/ces/ceswps/_4616.html
    have two way and three way interactions removed by sequential partialing out the effects dummies

    and cite
    Davis, Peter. "Estimating multi-way error components models with unbalanced data structures." Journal of Econometrics 106, no. 1 (2002): 67-95.

    but Somaini and Wolak have a more explicit description of the algorithm and space requirements.

  12. stoffprof commented on Jan 16, 2016

    @stoffprof
    Author

    The Somaini & Wolak approach does seem fairly easy to implement. I will take a crack at converting their Matlab code to Python.

    It's worth noting the comparison they draw in their paper to the reg2hdfe algorithm, related to the reghdfe algorithm I mentioned earlier. The approach that Somaini & Wolak use has the nice feature that the main computational burden -- calculating inv(S'S) -- is done just once for any set of fixed effects, and can then be used in various specifications of the other exogenous variables. On the other hand, it is not designed with sparse matrices in mind, and can be slower than the other iterative procedures for very large number of fixed effects.

    A good long term goal would probably be for both of these approaches to be implemented in statsmodels, but I think the Somaini & Wolak approach is relatively easy to do first.

  13. 7 remaining items

  14. josef-pkt commented on Jan 17, 2016

    @josef-pkt
    Member

    I think it would be good if the parameterization of the included variables is the same whether the fixed effect dummies are explicitly included in exog or absorbed.

    That's ambiguous because the parameter for the constant depends on the encoding of the fixed effect categorical.

    right now I don't know how to get the same constant parameter for reference coding

    e.g. adding grand mean back in
    first parameter is constant, then two continuous exog, then the fixed effects:

    res_ols = OLS(y, exog_full[:, :-1]).fit()
    res_absorb = OLSAbsorb(y, exogd, exog_absorb).fit()
    
    >>> print(res_ols.params)
    [ 1.19534021  1.00026369  1.00017489  0.9958792   0.50486371  0.33521204
      0.24870576  0.80687075  0.30502312  0.14009588  0.05375013]
    >>> print(res_absorb.params)
    [ 1.87342033  1.00026369  1.00017489]
    
    >>> print(res_ols.bse)
    [ 0.00483023  0.00177682  0.00171016  0.00499099  0.00504791  0.00523697
      0.00500665  0.00500664  0.00517375  0.00502753  0.00501003]
    >>> print(res_absorb.bse)
    [ 0.00166034  0.00177682  0.00171016]
    

    currently I'm overwriting only df_resid, and wendog, wexog through the whiten method:
    in summary(): f_test, llf, aic and bic differ between OLS and OLSAbsorb

  15. josef-pkt commented on Jan 17, 2016

    @josef-pkt
    Member

    One more on constant and

    We need to include a constant in the residual regression to recover the fixed effects in reference encoding

    idx below are the dummies used in the full OLS plus the constant

    >>> idx = [0] + list(range(3, exog_full.shape[1] - 1))
    >>> OLS(res_absorb.resid, exog_full[:, idx]).fit().params
    array([-0.67808012,  0.9958792 ,  0.50486371,  0.33521204,  0.24870576,
            0.80687075,  0.30502312,  0.14009588,  0.05375013])
    
    >>> res_ols.params[3:]
    array([ 0.9958792 ,  0.50486371,  0.33521204,  0.24870576,  0.80687075,
            0.30502312,  0.14009588,  0.05375013])
    

    Instead of recovering effects encoding fixed effects, we need to recover the full dummy set FE restricted to sum of effect is zero, or make encoding of FE optional like patsy (maybe when patsy has sparse categoricals).
    We should be able to use sparse OLS in #2711 for the auxiliary residual regression.

  16. stoffprof commented on Jan 17, 2016

    @stoffprof
    Author

    To the last item: I think it would be good if the parameterization of the included variables is the same whether the fixed effect dummies are explicitly included in exog or absorbed.
    Do you know if this is the case in Stata?

    IIUC, yes Stata does that. So for example,

    areg y x, absorb(effects)
    

    will report the same intercept and coefficient for x as:

    xi: reg y x i.effects
    
  17. josef-pkt commented on Jan 17, 2016

    @josef-pkt
    Member

    There is a Stata article on the different parameterizations for fixed effects
    "A review of Stata commands for fixed-effects estimation in normal linear models"
    http://www.stata-journal.com/article.html?article=st0267
    (I haven't read it.)

  18. josef-pkt commented on Jan 17, 2016

    @josef-pkt
    Member

    R also has a package http://www.inside-r.org/packages/cran/lfe/docs/lfe
    but it might be for the next larger sample size where the full in memory sparse variant here might run into problems
    "The package has been tested on datasets with approx 20,000,000 observations with 15 covariates and approx 2,300,000 and 270,000 group levels (the felm took about 50 minutes on 8 cpus, the getfe takes 5 minutes)."

    If we special case the first fixed effect, then that could be done just by demeaning. But the followup effects would require a dense solution as in Davis or Somaini and Wolak, trading of speed for memory.
    reference for the lfe algorithm is Gaure.

  19. josef-pkt commented on Jan 18, 2016

    @josef-pkt
    Member

    Gaure, Simen. 2013. “OLS with Multiple High Dimensional Category Variables.” Computational Statistics & Data Analysis 66 (October): 8–18. doi:10.1016/j.csda.2013.03.024.

    Gaure (lfe) uses alternating projection instead of recursive projection like Davis. He needs to iterate a few rounds until convergence. One of the advantages is that the individual projections are just demeaning (if we have proper categorical, i.e. one 1 per row for each factor, Kerby mentioned another case using MixedLM on the mailing list).

    an implementation idea based on alternating demeaning:
    In finance or similar applications, with two-way effects the 2-dimensional arrays is pretty dense even in unbalanced samples, i.e. not too many NaNs in the rectangular representation. In this case, the fastest (my guess) demeaning would be by demeaning along the axes in an ndim array (or DataFrame), as long as nanmean is available.
    (We would need a 3d array with one axis being the variables, the other axes corresponding to the levels of the fixed effects.)

    This might be a fast special case. It won't work in firm-employee matched data because the rectangular representation would be large.

  20. josef-pkt commented on Jan 31, 2016

    @josef-pkt
    Member

    #705 I had Davis already in an issue related to the panel data work

  21. josef-pkt commented on Feb 11, 2017

    @josef-pkt
    Member

    another reference
    Rios‐Avila, Fernando. 2013. “Feasible Estimation of Linear Models with N-Fixed Effects.” SSRN Scholarly Paper ID 2366943. Rochester, NY: Social Science Research Network. http://papers.ssrn.com/abstract=2366943.
    uses alternating demeaning, some discussion and correction for empty "cells" for cov_params/bse
    (I just skimmed and didn't check details)
    It sounds similar to what I did except for the correction for unidentified parameters.

    see also comments in
    http://stats.stackexchange.com/questions/259367/is-there-a-python-equivalent-to-statas-reghdfe-for-high-dimensional-fixed-effec

  22. elliottash commented on Oct 5, 2018

    @elliottash

    This paper describes the algorithm used by @sergiocorreia in the stata module: http://scorreia.com/research/hdfe.pdf.

    Adding a substitute for reghdfe to statsmodels would bring in tons of applied economists.

  23. sergiocorreia commented on Oct 5, 2018

    @sergiocorreia

    @Ellliottt if you are interested in implementing it, we can always talk about my thoughts on the best way to approach it. For instance, if you can somehow manage to exploit pandas tools for handling categories, that would make the approach way simpler in terms of code). You might also want to look at the approach implemented in Julia (available in reghdfe through the lsmr option) which would be easier to add if you can wrap the lsmr library.

  24. josef-pkt commented on Oct 5, 2018

    @josef-pkt
    Member

    I never tried to figure out the graph laplacian approach which is more recent, because it looks complicated and I'm a bit doubtful whether it's worth the effort in the first round.

    The main problem I had with the code that I implemented is that it is difficult to get information and post-estimation results for the absorbed components. There are some references, but then I stopped reading.

    The other problem is that I couldn't make up my mind about how to define some results, and left it at that, only I have not gone back to it yet.

    I essentially implemented two main approaches, one is with sparse least squares which I guess is the scipy.version of lsmr, and the second by iterative demeaning. Iterative demeaning has the advantage that pandas groupby demeaning can be used or the same by xarray which could handle out of memory demeaning.

    I haven't looked at what approach Kevin @bashtage uses in his linearmodels package.

  25. sergiocorreia commented on Oct 6, 2018

    @sergiocorreia

    I never tried to figure out the graph laplacian approach which is more recent, because it looks complicated and I'm a bit doubtful whether it's worth the effort in the first round.

    Definitely not worth it in the first round.

    the second by iterative demeaning. Iterative demeaning has the advantage that pandas groupby demeaning can be used or the same by xarray which could handle out of memory demeaning.

    One key implementation detail is how to accelerate the iterative demeaning. Without acceleration it can be very slow; what works best on paper and in my experience was accelerating with conjugate gradient (not steep descent)

  26. karldw commented on Dec 20, 2018

    @karldw

    It's also worth mentioning Alpaca, "An R-package for fitting glm's with high-dimensional k-way fixed effects."
    (Though fixed effects do weird things in nonlinear models, so maybe not.)

  27. aeturrell commented on Aug 25, 2020

    @aeturrell
    Contributor

    There's been a bit of a discussion of this in relation to Python by Victor Chernozhukov and others on twitter. It seems that something like Stata's reghdfe could be a big draw for people to use statsmodels. As models for code, linearmodels has something for absorbing fixed effects in python here, although I'm not sure how it works, and there are some good benchmarks across R, Stata, and Julia here.

  28. josef-pkt commented on Aug 25, 2020

    @josef-pkt
    Member

    @aeturrell Thanks for the link to the twitter thread.
    It's good to hear that Victor is now interested in Python.
    (I seem to be stuck in stats and haven't done econometrics in a while. Maybe I switch fields again for a while.)

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions