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
{{ message }}
Repository navigation
consistent definitions of nobs, n_xxx, k_xxx #1664
we need more consistent definitions and usages of the descriptive attributes, as we add more models and more general cases or functionality.
example:
I'm still using code like nobs, k_exog = self.model.exog.shape (or more often k_vars instead of k_exog)
which describe the data, but are not always what we really need.
In the OLS case we have (assuming non-singular exog): k_params = df_model + k_constant = k_exog = self.model.exog.shape[1] = rank(exog)
However, none of these equalities need to hold exept k_exog = self.model.exog.shape[1]
Moreover, df_model is used in several places that don't use necessarily the same definition. (example where I had the problems is small sample correction to df for cluster robust standard errors.)
(related: Stata defines some of these, like df, in terms of rank(cov_params).)
Similarly, once we allow for case weights, then effective nobs is not equal to exog.shape[0]. (related: Stata does the weight rescaling so nobs = sum(weights).)
I guess we have this already in time series models that condition on the initial observations.
Which attributes to we have guaranteed to be available in all models?
Stumbling across this issue made my day. Also the mention of the pylint warning in #632.
model.ResultMixin.df_modelwc isn't really used, but it's one of my favorite things. If we used properties/cache_readonlys for these attributes, we could:
define these attributes in many fewer places,
document the reasoning behind small differences in these implementations
transparently handle cases where these attributes may change dynamically (e.g. nobs being affected by k_ar)
bring naming mismatches front-and-center
identify and pay down technical debt like the scattered # assumes constant and a couple others
The only downside I can think of is that doing this involves making small changes in a lot of places. But that's only going to get worse over time.
figuring out what we actually need, and what can be consistently defined across models
making changes that are not too disruptive and do not need a lot of backwards compatibility breaks.
My trend has been to add more attributes and rely on a few that are consistently defined, and see what works out in the long run.
I think df_model without a constant was a mistake because we followed other packages. But it has lived for a long time and we cannot just redefine it. Most likely something like k_params will become a substitute. (However, we still have a related open issues whether to count estimated scale or other auxiliary parameters for df.)
df_resid should currently be pretty consistently defined. It includes counting the constant and is the one I rely most of the time for inference.
# assumes constant: this is also not just a refactoring question, but we have to decide what we want. For example has_const is mainly used in the linear model to switch rsquared, i.e. the definition differs depending on whether a (explicit or implicit) constant is included in the exog. Outside of the linear models, e.g. in the discrete models, we define llnull against a Null model that always includes the constant. I prefer the constant-only Null, but for example I read recently in the SPSS or SAS documentation that they use an empty model if has_const is false.
In other cases assumes constant is a restriction to the common case, and would need special handling for the no-constant case which doesn't exist yet.
To add more complication: what df for which computation? (IIRC, Stata has in some model 4 or 5 df_xxx)
df_resid : standard default if nothing specific is defined
df_resid_inference : df used for F distribution to take account of small sample corrections
df_scale : denominator for scale computation (currently not defined), is either nobs or df_resid
df_ic : we need nobs and k_params for information criteria if we want to account for auxiliary parameter like scale
VAR and some multivariate models have various competing definitions of degrees of freedom in the literature. I don't know the details, but there are cases where it's not clear whether to count by equations or the entire system of equations.
Then we will get ddof () as model.__init__ parameter to allow users to adjust df_resid for e.g. absorbed variables. () delta degrees of freedom in analogy to numpy.var.
This are some of the design question and issues I ran into in various places.
We need either a big up-front design to come up with a good structure and naming conventions, or we work piecemeal and make it up and refactor and improve consistency as we figure out one part at a time.
But that's only going to get worse over time.
That's true, and in some cases I wished we had done some refactoring that requires backwards compatibility break earlier when we didn't have as many users. (But I have a hard time convincing myself to break backwards compatibility, when I'm only 60% sure what is the right approach)
In the cases of fixed parameters in constrained estimation and singular/reduced rank exog or cov_params, df_resid depends on the free parameters, k_params will then not be equal to df_modelwc.
I think this should currently be properly reflected in df_resid.
Before either of spend a lot of time on this topic: is this a steadfast "no" or are you open to being convinced?
... I wrote that, then proceeded to write an essay. Woops. TLDR; can we find a way to do a proof-of-concept in something like a Project or shared dev branch?
I've implemented this in my local dev branch for almost everything outside the sandbox, so many of the issues you mention have been worked out.
figuring out what we actually need, and what can be consistently defined across models
My big concern is with identifying things that are currently inconsistently defined across models. Or in some cases where the df_xyz in the results object does not match the version in the model (the cases where I've seen this appear to be intentional, but the reasoning is not always spelled out).
Most of the difficult questions revolve around df_xyz, but there are simpler cases that can be subtly tricky. nobs, k_exog, and k_endog can be defined in a surprising number of ways. You mentioned k_params; often times that matches params.size, or nnz_params, but not always. Wouldn't that relationship (or exceptions to it) be a good one to formalize?
making changes that are not too disruptive and do not need a lot of backwards compatibility breaks.
This one I have no good answer for. This is going to suck regardless.
On the other hand, the only place where I've actually changed the underlying logic was in AR.df_resid, which you agreed looked like a mistake in the original (see #3568). Everything else has just been a matter of inheriting mixins and deleting lines that set these attributes.
My trend has been to add more attributes and rely on a few that are consistently defined, and see what works out in the long run.
You've got more accumulated wisdom than I do on the subject, but this seems like a recipe for attribute proliferation. Then a newcomer comes along, sees a bunch of similarly-defined and similarly-named attributes, and can't tell what the difference is between them. Human sacrifice, dogs and cats living together, mass hysteria.
df_resid should currently be pretty consistently defined. It includes counting the constant and is the one I rely most of the time for inference.
It is pretty consistent. I've got it down to being defined in only 9 places. My contention is that the very fact that this has a simple unifying logic suggests that it should be formalized, and any time it is overridden should be a Big Deal necessitating explanation.
# assumes constant: this is also not just a refactoring question, but we have to decide what we want.
Yes to this and everything in that paragraph. Shouldn't this decision be made Once In One Place? And for that matter, aren't you curious in which cases that assumption is valid and can be discarded, vs places where internal consistency may have room for improvement?
For example, it is very difficult to override or reassign to cached attributes.
Yes, I found a couple of tests that override these manually. The solution I ended up using was defining _df_resid, _df_model, and _rank as standard attributes that could be manually fiddled with, and the non-underscore versions as properties that define them iff self._foo is not None:.
[...] tries to infer df_model df_resid for a generic likelihood model where we don't have much information about the structure of the underlying likelihood model.
Trying to define these in multiple places, along with (often nested) super(...).__init__ calls means we have to do a lot of detective work to track down how these are defined. Or they get defined in places they don't belong. Or they get defined in identical ways across different models that could have a clear unifying logic behind them.
If you make df_model a property in a parent class, then you can override it entirely in the child class and spell out exactly why you did so.
To add more complication: what df for which computation? (IIRC, Stata has in some model 4 or 5 df_xxx)
We discussed this briefly in #3574, and I agree it's a difficult question. Improving the consistency and transparency of the definitions can only make this better. This is an argument for defining appropriate variants in a consistent manner, then making an appropriate choice between them (or offering users a choice) when it comes time to calculate e.g. information criteria.
Broken record time: it can also help us identify places where inconsistencies have snuck in. Part of the reason this is a strong opinion is because there are a handful of small differences that aren't documented as intentional.
VAR and some multivariate models have various competing definitions of degrees of freedom in the literature. I don't know the details, but there are cases where it's not clear whether to count by equations or the entire system of equations.
Yep, touched on that in #3568 and #3574. I don't have a strong opinion on how to resolve this, just that it can be made more transparent by doing it in fewer places.
In the cases of fixed parameters in constrained estimation and singular/reduced rank exog or cov_params, df_resid depends on the free parameters, k_params will then not be equal to df_modelwc.
I think this should currently be properly reflected in df_resid.
It is, mostly. The L1 models/results in discrete_model have their own way of doing things that is internally consistent, so I've put that in its own mixin. MixedLM kind of does its own thing that I haven't totally sorted out. There are a couple other special cases, but I'm not sure they are distinct from things mentioned above, and this comment is already way too long.
Before either of spend a lot of time on this topic: is this a steadfast "no" or are you open to being convinced?
As the many open issues indicate, I'm convinced there is a problem but not convinced that we have a solution. I'm also open to finding a solution. Also, if you already did some work, then you can always open a PR and more issues.
The main limitation comes in the review and the timing. Refactoring, unless they are locally restricted, take a lot of time to review, whether they make sense, whether they are worth the complications/deprecations, whether they improve "future-proofness", and, a major point, whether they might introduce new hidden bugs (given that I don't fully trust our test coverage). This is a strong limitation as long as I'm essentially the only generic reviewer.
(It's much easier with new functionality, because users are warned that it is not yet stable.)
To shorten the remainder (after writing the above many hours ago)
I'm not under production and delivery pressure, so I don't mind using years to figure out some design. Many of the issues that I open are notes until I feel comfortable enough, and have the time, to implement something that looks general enough and might work. (The collaboration with Skipper was useful because he was pushing code faster into statsmodels, but I didn't have to maintain it and answer questions about it, or at least not in the details.)
(Just one more example: I took me years to figure out "weights", and we finally get them, but there are still nasty details, like what's the meaning of var_weights in loglike, that delay any quick merges and decisions. #3692 And there is no expert available that we could just ask.)
As the many open issues indicate, I'm convinced there is a problem but not convinced that we have a solution. I'm also open to finding a solution. Also, if you already did some work, then you can always open a PR and more issues.
I'll try to cut up the proposed solution(s) into PRs that can be evaluated in isolation.
k_params
323 matches for k_params but it looks like most of the time as local temporary variable
60 matches for self.k_params
many cases also in tsa and statespace
nparams
53 matches
a few local uses in holtwinters and diagnostic
old code (from before k_params): including attribute self.nparams
GenericLikelihoodModel, miscmodels
GMM, and some other sandbox regression code
n_params:
very few cases only local/temp, but many cases as part of name mean_params, return_params
param_names 374 matches self.param_names 33 matches, only statsmodels.base.data and (newer) tsa .param_names 109 matches, many refering to data.param_namesextra_params_names14 matches used in GenericLikelihood, miscmodelsexog_names279 matches, shows up in all parts.exog_names` 134 matches for attribute, also shows up in all parts
Activity
jbrockmendel commentedon May 24, 2017
Stumbling across this issue made my day. Also the mention of the pylint warning in #632.
model.ResultMixin.df_modelwcisn't really used, but it's one of my favorite things. If we used properties/cache_readonlys for these attributes, we could:nobsbeing affected byk_ar)# assumes constantand a couple othersThe only downside I can think of is that doing this involves making small changes in a lot of places. But that's only going to get worse over time.
josef-pkt commentedon May 24, 2017
see also #1970 and many other related issues
This is another difficult topic
My trend has been to add more attributes and rely on a few that are consistently defined, and see what works out in the long run.
I think df_model without a constant was a mistake because we followed other packages. But it has lived for a long time and we cannot just redefine it. Most likely something like
k_paramswill become a substitute. (However, we still have a related open issues whether to count estimated scale or other auxiliary parameters for df.)df_residshould currently be pretty consistently defined. It includes counting the constant and is the one I rely most of the time for inference.# assumes constant: this is also not just a refactoring question, but we have to decide what we want. For example has_const is mainly used in the linear model to switch rsquared, i.e. the definition differs depending on whether a (explicit or implicit) constant is included in the exog. Outside of the linear models, e.g. in the discrete models, we define llnull against a Null model that always includes the constant. I prefer the constant-only Null, but for example I read recently in the SPSS or SAS documentation that they use an empty model if has_const is false.In other cases
assumes constantis a restriction to the common case, and would need special handling for the no-constant case which doesn't exist yet.About properties/cached attributes: My experience here is negative. For example, it is very difficult to override or reassign to cached attributes. The df_xxx and similar need to be changed possibly by an instance, and a simple attribute is the easiest.
e.g. https://github.com/statsmodels/statsmodels/blob/master/statsmodels/base/model.py#L2052 tries to infer df_model df_resid for a generic likelihood model where we don't have much information about the structure of the underlying likelihood model.
To add more complication: what df for which computation? (IIRC, Stata has in some model 4 or 5 df_xxx)
df_resid : standard default if nothing specific is defined
df_resid_inference : df used for F distribution to take account of small sample corrections
df_scale : denominator for scale computation (currently not defined), is either nobs or df_resid
df_ic : we need nobs and k_params for information criteria if we want to account for auxiliary parameter like scale
VAR and some multivariate models have various competing definitions of degrees of freedom in the literature. I don't know the details, but there are cases where it's not clear whether to count by equations or the entire system of equations.
Then we will get
ddof() asmodel.__init__parameter to allow users to adjust df_resid for e.g. absorbed variables. () delta degrees of freedom in analogy to numpy.var.This are some of the design question and issues I ran into in various places.
We need either a big up-front design to come up with a good structure and naming conventions, or we work piecemeal and make it up and refactor and improve consistency as we figure out one part at a time.
That's true, and in some cases I wished we had done some refactoring that requires backwards compatibility break earlier when we didn't have as many users. (But I have a hard time convincing myself to break backwards compatibility, when I'm only 60% sure what is the right approach)
josef-pkt commentedon May 24, 2017
I forgot one more difficulty
In the cases of fixed parameters in constrained estimation and singular/reduced rank exog or cov_params, df_resid depends on the free parameters, k_params will then not be equal to df_modelwc.
I think this should currently be properly reflected in df_resid.
jbrockmendel commentedon May 24, 2017
Before either of spend a lot of time on this topic: is this a steadfast "no" or are you open to being convinced?
... I wrote that, then proceeded to write an essay. Woops. TLDR; can we find a way to do a proof-of-concept in something like a Project or shared dev branch?
I've implemented this in my local dev branch for almost everything outside the sandbox, so many of the issues you mention have been worked out.
My big concern is with identifying things that are currently inconsistently defined across models. Or in some cases where the
df_xyzin the results object does not match the version in the model (the cases where I've seen this appear to be intentional, but the reasoning is not always spelled out).Most of the difficult questions revolve around
df_xyz, but there are simpler cases that can be subtly tricky.nobs,k_exog, andk_endogcan be defined in a surprising number of ways. You mentionedk_params; often times that matchesparams.size, ornnz_params, but not always. Wouldn't that relationship (or exceptions to it) be a good one to formalize?This one I have no good answer for. This is going to suck regardless.
On the other hand, the only place where I've actually changed the underlying logic was in
AR.df_resid, which you agreed looked like a mistake in the original (see #3568). Everything else has just been a matter of inheriting mixins and deleting lines that set these attributes.You've got more accumulated wisdom than I do on the subject, but this seems like a recipe for attribute proliferation. Then a newcomer comes along, sees a bunch of similarly-defined and similarly-named attributes, and can't tell what the difference is between them. Human sacrifice, dogs and cats living together, mass hysteria.
It is pretty consistent. I've got it down to being defined in only 9 places. My contention is that the very fact that this has a simple unifying logic suggests that it should be formalized, and any time it is overridden should be a Big Deal necessitating explanation.
Yes to this and everything in that paragraph. Shouldn't this decision be made Once In One Place? And for that matter, aren't you curious in which cases that assumption is valid and can be discarded, vs places where internal consistency may have room for improvement?
Yes, I found a couple of tests that override these manually. The solution I ended up using was defining
_df_resid,_df_model, and_rankas standard attributes that could be manually fiddled with, and the non-underscore versions as properties that define them iffself._foo is not None:.Trying to define these in multiple places, along with (often nested)
super(...).__init__calls means we have to do a lot of detective work to track down how these are defined. Or they get defined in places they don't belong. Or they get defined in identical ways across different models that could have a clear unifying logic behind them.If you make
df_modela property in a parent class, then you can override it entirely in the child class and spell out exactly why you did so.We discussed this briefly in #3574, and I agree it's a difficult question. Improving the consistency and transparency of the definitions can only make this better. This is an argument for defining appropriate variants in a consistent manner, then making an appropriate choice between them (or offering users a choice) when it comes time to calculate e.g. information criteria.
Broken record time: it can also help us identify places where inconsistencies have snuck in. Part of the reason this is a strong opinion is because there are a handful of small differences that aren't documented as intentional.
Yep, touched on that in #3568 and #3574. I don't have a strong opinion on how to resolve this, just that it can be made more transparent by doing it in fewer places.
It is, mostly. The
L1models/results in discrete_model have their own way of doing things that is internally consistent, so I've put that in its own mixin.MixedLMkind of does its own thing that I haven't totally sorted out. There are a couple other special cases, but I'm not sure they are distinct from things mentioned above, and this comment is already way too long.josef-pkt commentedon May 24, 2017
As the many open issues indicate, I'm convinced there is a problem but not convinced that we have a solution. I'm also open to finding a solution. Also, if you already did some work, then you can always open a PR and more issues.
The main limitation comes in the review and the timing. Refactoring, unless they are locally restricted, take a lot of time to review, whether they make sense, whether they are worth the complications/deprecations, whether they improve "future-proofness", and, a major point, whether they might introduce new hidden bugs (given that I don't fully trust our test coverage). This is a strong limitation as long as I'm essentially the only generic reviewer.
(It's much easier with new functionality, because users are warned that it is not yet stable.)
To shorten the remainder (after writing the above many hours ago)
I'm not under production and delivery pressure, so I don't mind using years to figure out some design. Many of the issues that I open are notes until I feel comfortable enough, and have the time, to implement something that looks general enough and might work. (The collaboration with Skipper was useful because he was pushing code faster into statsmodels, but I didn't have to maintain it and answer questions about it, or at least not in the details.)
(Just one more example: I took me years to figure out "weights", and we finally get them, but there are still nasty details, like what's the meaning of var_weights in loglike, that delay any quick merges and decisions. #3692 And there is no expert available that we could just ask.)
jbrockmendel commentedon May 26, 2017
I'll try to cut up the proposed solution(s) into PRs that can be evaluated in isolation.
jbrockmendel commentedon Jun 2, 2017
Somehow I had missed: RegressionModel already uses properties for
df_modelanddf_resid.josef-pkt commentedon Jun 12, 2021
searching in py files:
k_params323 matches for
k_paramsbut it looks like most of the time as local temporary variable60 matches for
self.k_paramsmany cases also in tsa and statespace
nparams53 matches
a few local uses in holtwinters and diagnostic
old code (from before k_params): including attribute self.nparams
GenericLikelihoodModel, miscmodels
GMM, and some other sandbox regression code
n_params:very few cases only local/temp, but many cases as part of name
mean_params,return_paramsparam_names374 matchesself.param_names33 matches, only statsmodels.base.data and (newer) tsa.param_names 109 matches, many refering todata.param_namesextra_params_names14 matches used in GenericLikelihood, miscmodelsexog_names279 matches, shows up in all parts.exog_names` 134 matches for attribute, also shows up in all partsxname431 matches, I guess all insummaryendog_name443 matchesendog_names(plural) 365 matchesyname365 matchesynames126 matchesbase.datauses mostlyy_namesbase.model.Modeladds exog_names, endog_names as cached attribute as reference to data attributes