You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
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
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.
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
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.
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.
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.)
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.
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:
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
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.
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:
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.
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.
@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.
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.
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)
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.)
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.
@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.)
Activity
josef-pkt commentedon Aug 1, 2015
robust covariance:
Stata has
robust(HC) andclusterrobust 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. (
HCon 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
josef-pkt commentedon Aug 1, 2015
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
regressandaregare identical for slope coefficients withvce(robust). Coefficient for constant and it's standard errors differ.josef-pkt commentedon Aug 2, 2015
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 + uestimated viaey|x2 = ex1|x2 b1 + u?ey, ex1 are residuals from projection on x2
josef-pkt commentedon Aug 2, 2015
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
aregandxtreg, febut I don't see the difference yet. It might be mainly the defaults for cov_params.stoffprof commentedon Aug 3, 2015
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.
josef-pkt commentedon Aug 3, 2015
@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.
josef-pkt commentedon Sep 30, 2015
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)
josef-pkt commentedon Jan 14, 2016
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.
josef-pkt commentedon Jan 14, 2016
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.)
josef-pkt commentedon Jan 15, 2016
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.
stoffprof commentedon Jan 16, 2016
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.
7 remaining items
josef-pkt commentedon Jan 17, 2016
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:
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
josef-pkt commentedon Jan 17, 2016
One more on constant and
We need to include a constant in the residual regression to recover the fixed effects in reference encoding
idxbelow are the dummies used in the full OLS plus the constantInstead 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
sparsecategoricals).We should be able to use sparse OLS in #2711 for the auxiliary residual regression.
stoffprof commentedon Jan 17, 2016
IIUC, yes Stata does that. So for example,
will report the same intercept and coefficient for x as:
josef-pkt commentedon Jan 17, 2016
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.)
josef-pkt commentedon Jan 17, 2016
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
lfealgorithm is Gaure.josef-pkt commentedon Jan 18, 2016
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.
josef-pkt commentedon Jan 31, 2016
#705 I had Davis already in an issue related to the panel data work
josef-pkt commentedon Feb 11, 2017
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
elliottash commentedon Oct 5, 2018
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.
sergiocorreia commentedon Oct 5, 2018
@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.
josef-pkt commentedon Oct 5, 2018
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.
sergiocorreia commentedon Oct 6, 2018
Definitely not worth it in the first round.
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)
karldw commentedon Dec 20, 2018
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.)
aeturrell commentedon Aug 25, 2020
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.
josef-pkt commentedon Aug 25, 2020
@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.)