Skip to content

WIP: Panel models - #690

Closed
vincentarelbundock wants to merge 12 commits into
statsmodels:masterfrom
vincentarelbundock:panel
Closed

vincentarelbundock wants to merge 12 commits into
statsmodels:masterfrom
vincentarelbundock:panel

Conversation

@vincentarelbundock

Copy link
Copy Markdown

let me know what should be added to this todo list:

  • transform_slices as a group iterator
  • move useful pandas index attributes to Group instance attributes
  • naming convention / consistency
  • current Grouping() class focuses on the unbalanced case. do we want balanced optimization?
  • detect if endog and exog have a proper index already
  • proper df in unbalanced case?
  • predict random effects?
  • optional sanity checks on user-supplied index (e.g sorted, duplicates)
  • Grouping.sortdata(array) method
  • tests
  • recover removed individual fixed effects [won't do this for initial release]
  • two-way random effects [won't do this for initial release]
  • post-estimation tests [won't do this for initial release]

@jseabold

jseabold commented Mar 2, 2013

Copy link
Copy Markdown
Member

@josef-pkt

Copy link
Copy Markdown
Member

4 day skiing trip starting tomorrow so I will most likely not have time to look at it until the end of next week.

todo:
recover removed individual fixed effects (if possible)
other post-estimation results and tools for it ? not sure what.

what about two-way random effects (individual plus time) ?

@vincentarelbundock

Copy link
Copy Markdown
Author

re: two-way random effects

after reading quickly what Baltagi has to say on the topic, I think I'll put 2way random effects on the backburner. It would just take me too much time to wrap my head around it to be worth it. I'd rather focus on nailing the rest of the stuff so it's "shippable" as soon as possible.

[checking it off the list]

@jseabold

jseabold commented Mar 2, 2013

Copy link
Copy Markdown
Member

I agree. It's most important to get the format down and get the code out there in a way that's easily extensible.

Some observations from my workflow over the last ~6-12 months. I think as a whole we spend too much time on polishing and getting everything ready-to-go. At least I know that's true for myself. I get bogged down in trying to add every feature in R/SAS/Stata when it's probably more important to have a functional estimator out there. That way we (and others) can iterate and add as we find that we need things. I imagine that we'll find that the important part will be that there's a starting point to point to, and we'll see an uptick in contributions when it's just a matter of adding a helpful method or additional feature we're adding. Compare our practices with the organic development of pandas and scikit-learn.

@josef-pkt

Copy link
Copy Markdown
Member

re: two-way random effects: Was worth a try, that's where things start to get "interesting" :)

I think overall we are organic enough, but would benefit a lot if we had more PR review capacity.

@vincentarelbundock

Copy link
Copy Markdown
Author

I moved panel.py to the regression folder, at least for development. If things don't work out we can always go back to sandbox. I also wrote some tests. There's a lot of failures, but I know the source of most of them, and they are very minor:

- rsquared_adj: ???
- conf_int: sm is right R's plm is wrong (no df correction)
- between f_pvalue: I suspect plm again does not treat df correctly (not sure)
- fvalue: why do I need to divide by 2 except for within?

@jseabold

jseabold commented Jul 9, 2013

Copy link
Copy Markdown
Member

Quick question as I'm doing a minor refactor on this (pulling the data handling to a higher abstract class for re-use).

Do we want to enforce that if users are using a MultiIndex to specify the panel that they must either 1) have it so that the levels have the names panel and time or 2) ensure that the first level is the panel and the second level is time. 2 is assumed now, but 1 would relax it a little but and allow us to internally rename the index levels also to panel and time. This way we can do things like transform_array(..., 'time') and transform_array(..., 'panel')` which makes the code a bit more readable I think.

@vincentarelbundock

Copy link
Copy Markdown
Author

can we have a hierarchy? If index well named do accordingly, otherwise assume a "proper" ordering.

Just thinking about my own workflow, I rarely have indices named "panel/time", rather stuff like "country/year", etc.

But I don/t have strong preference either way.

@jseabold

jseabold commented Jul 9, 2013

Copy link
Copy Markdown
Member

Yeah, I don't either. I'm thinking of it kind of like in stata you have to do xtset. I think you're probably right in that it's not worth it, but I'm already stumbling over the level = 0 and level = 1 stuff internally.

@vincentarelbundock

Copy link
Copy Markdown
Author

FWIW, I'm starting to think that an analogue to xtset might actually be desirable in our case because users can input so many different formats: MultiIndex Pandas, Pandas with indices as regular columns, numpy arrays, potentially a separate index as a regular list or array.

xtset could enforce some explicit standard on the user upfront and allow us to work with consistent stuff under the hood. And it would provide a natural extension to survival time set and such.

Also, R's plm uses an analogue function in that you are required to convert your dataframe into a pdata.frame

@jseabold

jseabold commented Jul 9, 2013

Copy link
Copy Markdown
Member

I mostly agree. I've abstracted the data-handling so that this is mostly embedded in all the panel models. It's similar to what you had though. We might provide different entry-points. So something like

PanelModel.from_frame('y ~ X', data=data, panel='firm', time='year')

would work too. I'll hopefully be pushing up my changes sometime tomorrow, assuming I can get what I need working first. I'm starting with a specific use case and working back up to the generic stuff.

@vincentarelbundock

Copy link
Copy Markdown
Author

should i close this PR?

@jseabold

jseabold commented Jul 9, 2013

Copy link
Copy Markdown
Member

Keep it open for now. We'll decide what to do / if my changes are worth it when we look.

@josef-pkt

Copy link
Copy Markdown
Member

Skipper wrote

as I'm doing a minor refactor on this (pulling the data handling to a higher abstract class for re-use)

Without knowing exactly what you are doing, I would prefer if we can outsource as much as possible for reuse across different models. Similar to the grouping classes that Vincent and I started.

GEE pull request, repeated measures (Anova) and similar (xtgls) would benefit if it can reuse some of the common group and time handling/ data frame conversion. But they might be different enough that we don't want to inherit.

@jseabold

Copy link
Copy Markdown
Member

I just pulled out the model data handling from PanelLM to a PanelModel class for re-use. It won't affect anything else and makes it so that all panel models inherit from PanelModel not PanelLM.

jseabold/statsmodels@panel-vincent-rebased-old...panel-vincent

@jseabold

Copy link
Copy Markdown
Member

@vincentarelbundock what's the difference between transform_slices and transform_array? It looks like both apply a function to the data by groups to me. What am I missing?

@vincentarelbundock

Copy link
Copy Markdown
Author

Works on numpy arrays. Makes no difference if you coerce panel data to pandas beforehand, but it could be handy as a stopgap measure to convert existing code that operates on np.arrays (e.g. sandwich).

@jseabold

Copy link
Copy Markdown
Member

Ok. So IIUC the only difference is that transform_slices doesn't coerce the data to a DataFrame and back to an ndarray?

@vincentarelbundock

Copy link
Copy Markdown
Author

That's right. transform_array takes an array, converts the numpy array to a dataframe before applying the transform using groupby and returns the resulting a data frame. transform_slices takes a numpy array, applies the transform (without using pandas at all), and returns a numpy array.

@vincentarelbundock

Copy link
Copy Markdown
Author

Another thing to consider is that I think there were some performance gains with the slices approach. Still, I'm not sure we absolutely need to keep that in there...

@jseabold

Copy link
Copy Markdown
Member

Ok, thanks. Will look at the performance. No sense in not keeping it for now.

@jseabold

Copy link
Copy Markdown
Member

@vincentarelbundock I'm getting a lot of EOL whitespace cleanup changes. Can you make sure your editor or git config is set to remove trailing whitespace from files?

@vincentarelbundock

Copy link
Copy Markdown
Author

thanks. just added something to .vimrc. Hopefully it does the trick.

@josef-pkt

Copy link
Copy Markdown
Member

def __init__(self, y, X, time=None, panel=None, missing='none',

can you put time after panel?
Isn't panel required for panel data (we call it groups, in GEE and repeated measures)

in GEE the signature is (endog, exog, groups, time=None, ...)
groups is required, time is optional, and used only if the correlation has a time structure (e.g. AR(1) errors)
for example http://www.stata.com/support/faqs/statistics/xtgls-and-time-variable/ with cases where time is ignored.
(unobserved heterogeneity withing group/panel/individual but no correlation across individuals)

@jseabold

Copy link
Copy Markdown
Member

Yeah sure. Hold off before you do a full review on this though. Things are still moving around, including signatures.

@josef-pkt

Copy link
Copy Markdown
Member

I won't have time for a while for a full review, I just had a quick look to get an idea of the structure.
But eventually we have to compare notes with GEE and ShortPanel to see how much this can be used with other cases, or if it is mainly "Macro-econometrics"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

FYI, I suspect this doesn't do what you think it does. np.rank is the same as array.ndims IIRC. You want np.linalg.matrix_rank. Been a pain point for a while. We used to have our own version of rank that we used.

This fixed the problem you were seeing with f_pvalue for the between model, but now I need to check the other degrees of freedom to see what else is going on.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

well this is "funny"

@josef-pkt josef-pkt mentioned this pull request Jul 11, 2013
@jseabold

jseabold commented Aug 6, 2013

Copy link
Copy Markdown
Member

Parking this here. I'm pretty sure the df correction for r.squared in PLM for the adjusted r squared is just wrong, so that's why you were seeing differences there. They use essentially this

df_resid/len(resid - 1) * r2

The -1 is inside the length, and even fixing this it's not any rsquared I've seen.

@vincentarelbundock

Copy link
Copy Markdown
Author

I had noticed the same parenthesis problem, and didn't recognize the expression either. That codebase is really strange (even by R standards).

@jseabold

jseabold commented Aug 8, 2013

Copy link
Copy Markdown
Member

Just want to park this thought here.

There's may be separation that needs to be made in LinearModelResults, or we may need more abstraction via mix-ins or better yet probably - functions. Right now anything that inherits from RegressionResults will have an fvalue. However, in some instances, we may want chi^2. Right now, the fixed effects estimators need an F test but random effects needs a chi^2. Other than that the needed results are very similar. conf_int is also another issue. Need a normal distribution for random and t for fixed but otherwise they share much. Before, we agreed to hard-code this as t, but I don't know if there's any need to be so inflexible, especially if we delegate to a function.

@josef-pkt

Copy link
Copy Markdown
Member

That's back to using use_t True or False.
Plus we need to decide how to set a sandwich cov_params as default for pvalues, for chi^2 or Wald, ... and summary().

There are several open issues on these parts.

@josef-pkt

Copy link
Copy Markdown
Member

However outsourcing some parts into Mixins would make inheritance easier.
Chad currently inherits both RegressionResults and TSAResuls for SETAR, which might be less robust (but I haven't looked at the details yet.)

@jseabold

jseabold commented Aug 8, 2013

Copy link
Copy Markdown
Member

For conf_int, we could just have a function that takes the distribution as an argument and call that from the model's method - similar to mixture_rvs. Seems cleaner to me.

There are parts of RegressionResults that are maybe more general than just linear regression models even if they may need to be overwritten in some cases -- bse, pvalues, aic, bic, rsqaured, robust covariance... I'll get a clearer picture before the PR.

While I'm also thinking about it, the scale attribute is seeming more and more like a bad idea. This isn't just from the panel work but elsewhere it's confusing. The name is horribly indescriptive and I don't think it's used consistently (arbitrarily set to 1 in place because it's not really clear what a single scale is). While greek names are not ideal either, something like a theta or sigma that's used consistently in the literature is better than scale IMO, though for panel and in the VAR rewrite, I have things like std_dev_groups, etc. that works even better.

@josef-pkt

Copy link
Copy Markdown
Member

I think scale is fine. It's very clear to me what it does. (See many discussions about scipy's curve_fit whether the normalized_cov_params should be scaled or not.)

The only thing that was always confusing to me is that the scale is the variance and not the standard deviation (scale factor of the distribution as in scipy.stats.distributions), but I got used to that.

I'm not really a big fan of having individual model specific methods being coded with the distribution, because it's an easy source of error if one method is not changed properly. See the bug that we had in genmod see #828

Note: in GLS scale is the standard terminology ASAIR, and there is always the discussion for scale=1 in families that don't have a separate scale parameter like Poisson.

@vincentarelbundock

Copy link
Copy Markdown
Author

@jseabold I may be able to work on this a bit soon, would it help? Where are you at?

@jseabold

Copy link
Copy Markdown
Member

Almost ready for a PR. Am going to put in a bit more hopefully today or tomorrow. Right now one-way fixed effects are hard-coded for panel and not time, but it should be an easy fix. Debating about whether to add the GLS estimator for random effects and an MLE estimator. Might have to wait.

Some open issues about what/how to inherit from RegressionResults that may be better off with a refactor in linear_model, but we'll see. Also naming conventions, etc. will need to be discussed.

https://github.com/jseabold/statsmodels/compare/panel-vincent

@vincentarelbundock

Copy link
Copy Markdown
Author

ok, will wait for your sign before reviewing

@vincentarelbundock

Copy link
Copy Markdown
Author

Seems

#301

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