Repository navigation
Description
Suppose I have params and cov_params estimates, and maybe a predict function, and want to get the inference from a LikelihoodModelResults class.
Sometimes I faked a model for some functions or classes that require a model as argument in experimental code by using a DummyModel and attach whatever is needed.
It would be more useful if a reusable version is officially supported, which would also make it clearer what information is actually required (e.g. .data, param_names, df_resid, ...), and review if we really need all those in specific methods.
related: I once wrote or started a multivariate normal class with linear transformation that does something similar, but having it tied into model based inference is more specific and makes it easier to figure out what we need. (e.g. nonlinear tests and inference)
(random thoughts:
I think we don't want to actually move this to a Mixin class at the current stage because of the tight integration with Results and Models and a dual class hierarchy is simpler than a triple hierarchy, e.g. adding score_tests or likelihood ratio tests doesn't fit the simple Wald pattern. Those would also need different information. (*)
The NoDataResults could initially be just Wald based inference, LR is possible with just adding llf, score would either require that the score is provided or that we have access to the full score_obs computation. (for score type tests: I have a version that uses moment conditions and their derivative in GMM style which IIRC works with summary statistics instead of data.)
However, profile likelihood or score confidence intervals require a full model with data to compute large deviations from the point estimate.
)
(*) a Mixin that is only used for LikelihoodModelResults would essentially not change anything compared to the current structure.
Activity
josef-pkt commentedon Mar 22, 2017
Specific use case: combining inference from samples or estimators, or sample estimate and prior. (method
merge?)It might also provide the structure for other usages, e.g. one-step estimator for linear restrictions, which should have very similar linear algebra based on hessian and score, IIRC.
jbrockmendel commentedon Mar 24, 2017
@josef-pkt I don't see why a third hierarchy would be necessary. The whole idea of mixins would be for the existing hierarchy to inherit from them right?
One big win is de-duplication. For example, I see four models that implement _get_robustcov_results methods, only one of which passes through to the base.covtype.get_robustcov_results implementation. Same with cov_params, cov_params_approx, ... Many of these are just a couple of lines, but putting them in one place would make it easy to a) ensure they are defined in a consistent way across models and b) improve test coverage.
josef-pkt commentedon Mar 24, 2017
@jbrockmendel One problem is when the subclasses for the intermediate or final models and results need to overwrite a generic
basemethod, or adjust parts before calling thesupermethods. Then, we either need separate Mixin classes for the special cases in the subclasses, or, we need to overwrite a Mixin method in a regular Model class, which mixes what would be in the two categories of classes.It's possible, but it's not so clean either.
_get_robustcov_resultsis partially incomplete cleanup and the methods are still defined where I initially developed them (*). The second reason is that we also have or should have some model specific sandwiches or cov_types, and we will always need some adjustments in the method of some individual models.(*) the main duplication currently is that the regression.linear_models still define the full
_get_robustcov_resultstype and it could mostly use the generic version instead. (In my last round of changes, I copy-pasted between the two versions.) There is also still the first sandwich version in GMM that doesn't follow the generic setup, that's also because it is used in the GMM weight matrix and not just for cov_params.(The actual generic get_robustcov_results is almost fully outsourced into a standalone function
For the models itself there wouldn't be much change in code sharing compared to now, because currently we already share the code through the model and results inheritance. The advantage of separating it out into a Mixin class would be that we can reuse it for cases that don't inherit from the Results hierarchy. This will be the main reason for me to switch to a Mixin class for inference, but currently I'm not sure what should go there.
Another reason will be if we need several cases of generic methods. One unresolved problem right now is that wald inference has problems when
paramsis 2-dimensional as in balanced multivariate models, currently MNLogit, VAR/VECM and the currently unfinished _MultivariateOLS.(Some of it is my reluctance to refactor when there is no strong need and clear alternative.)
jbrockmendel commentedon Jun 26, 2017
After calling
remove_data, there are a whole bunch of attributes that are no longer accessible, e.g.In many of these cases the problems could be avoided by ensuring that all of the
cache_readonlyattributes have been evaluated before callingremove_data. Alsores.data.xnamesandres.data.ynamesare@cache_writableand need to be evaluated.jbrockmendel commentedon Jun 26, 2017
Should
wendogbe inMNLogit._data_attr?josef-pkt commentedon Jun 26, 2017
That's up to the user, the only thing that should be guaranteed to work is predict.
In the unit tests, and IIRC I recommend in a docstring, calling summary() before remove data creates most of the cached attributes. We could add a check that summary() works again after unpickling (if it was called before). We would have to skip the diagnostic table in OLS/linear model summary in that case.
If MNLogit still has nobs length arrays, then it hasn't been added to the generic pickle tests in base, or those are incorrect. In that case it's a bug which needs unit tests and fixes, and that would be a separate issue.
jbrockmendel commentedon Jun 26, 2017
w/r/t MNLogit in particular, I'm patching that left and right for day-job responsibilities. Once the current fires are put out I'll clean that up and do an omnibus PR and try to collect a bunch of outstanding related issues.
What about e.g. labels for
res.paramsetc? Those are stored inxnamesorendog_namesorparam_namesor ... I'm really not sure. But wherever they are stored, they are not reliably attached after callingremove_data.To the extent that we want to offer a polished experience that Just Works, wrapping is worth getting really right.
I considered patching
remove_datato just look for any arrays of lengthnobs, but that heuristic is liable to break ifnobsis very small.The other big problem with this is that the design of
ModelandModelDatamake it hard to reason about what attributes will exist. In particular,self.__dict__.update(**kwargs)inModelData.__init__andsetattr(self, key, data.__dict__.pop(key))inModel._handle_datamodel.data.row_labelsmay be a corner case to give special thought to. When present, it may be a nobs array, but it could in many cases by a small-memory object likexrange(nobs).To clarify the relation of my comment to the original post: I am agreeing with (and offering to help with) the idea of an explicit, specific implementation of to make sure all the necessary attributes are retained independent of the underlying data.
josef-pkt commentedon Jun 26, 2017
I think the issue needs to go the other way: We guarantee supporting some specific usecases after remove_data. We support those, The rest, e.g. what is in cache and kept, is up to the user. The main use case that was requested was to get
predictto work. Currently there are no other verified usecases. If there are more use cases, then we can add more options.Inspection to remove data will to a large extend not work well because looking at a cached attribute might trigger it's computation, and I liked the explicitness of adding the relevant keys. (AFAIK, the most subclasses in tsa don't support remove_data because historical data is needed for forecasting.)
I agree that param_names needs to be fixed if this is not stored and kept by default. I don't see a reason to keep the index, row_labels, of the original data for the
predictusecase.josef-pkt commentedon Jun 26, 2017
in other words, we need requirements, use cases or definitions and unit tests for what "necessary attributes" are
jbrockmendel commentedon Jun 26, 2017
Fair enough. Most of my complaints would be resolved by getting the param_names etc to work reliably.
resid_obscure_variantis a much lower priority.Yah, I tried using
inspectto figure out which attributes wherecache_xyzonlyto avoid evaluating them. It's doable but really ugly.My goal for this thread -- aside from returning it to its original focus -- is to agree on a reasonable scope for a PR to address some of these issues. Before making an opening bid can I get your opinion on moving away from
self.__dict__.update(...)and/orsetattr?josef-pkt commentedon Jun 26, 2017
Why? What would be the problem? What would be the alternative?
I don't have a strong opinion but it worked well and don't remember ever having problems with it. We use it a lot. So any moving away would depend on a better alternative.
self.__dict__.update(mlefit.__dict__)looks like a simple way to copy over attributes.no idea, I didn't know or remember that we use it. So I don't have currently an opinion.
We use getattr with a default if the attr doesn't exist pretty often.
jbrockmendel commentedon Jun 26, 2017
That tells me enough to know that the attribute-existence-ambiguity issue should be handled separately. I'll open an issue to discuss that in its own thread. The only really pertinent case is that array-like attributes can be pinned to
ModelDatathat we won't know to append to_data_attrs.For the issue at hand, let's see if we can find an appropriate scope for a PR. How about:
Retention of param_names/endog_names/xnames/ynames/... following
remove_datato ensure wrapping works successfully.a) This does not include refactoring to do anything like disambiguating synonymous names.
Ensure that
predictworks followingremove_data. Document exactly what is and not guaranteed to work.a) Any method that fails because of removed data should include a useful error message in the exception.
Systematically identify the arrays to prune in
remove_data. We can't count on_data_attrsto be complete. (This one is more likely than the others to get pushback. If you're not immediately on board, I'd rather drop it than go back and forth on it.)Would this achieve what you had in mind with the OP?
josef-pkt commentedon Jun 26, 2017
2a) might not be feasible and should be covered by blanket warning when you use remove_data. i.e. we don't check which methods don't work, especially because we don't know or because there are too many things that won't work, and those might be model specific.
So, the presumption is that all keys together provide a complete list otherwise it is a lack in unit test coverage.
To 1.
param_namesis supposed to be the only one that is needed if provided, xnames and similar were and are still used in models that don't have extra params. param_names was added after several models ran into problems using xnames (and k_vars instead of k_params).specific to MNLogit and other multivariate models: we still need a special method to create full param names for the raveled params, the cov_params or for a multi-index.
(Also, I assume wald_tests, t_test should be supported after remove_data but I don't remember checking and unit testing this.)
Note: as a basic requirement I think requiring that the summary()/params_table still works after remove_data is a good check, and would include the names when a pandas DataFrame was used.
jbrockmendel commentedon Jun 26, 2017
I'll start with a warning at
remove_dataand later take a shot at a more ambitious error-message-wrapping.I'm going to count that as pushback and drop this idea for the time being.
I would very much like to see this made consistent, but am trying to limit the scope of the proposed PR. So the thought is to handle all the existing variants and take no stand on which should be used for the time being.
That will be at least partially addressed in the MNLogit-specific PR mentioned earlier. Ref #2610.
josef-pkt commentedon Mar 19, 2018
minimal FakeModel that works for the example
josef-pkt commentedon Mar 21, 2018
An alternative is to provide a standalone
t_testfunction based on LikelihoodModelResults.t_test. That is, we should add more helper functions based on some sufficient statistics (params, cov_params, df, ...).However, the
t_testmethod is tightly integrated with the model and results classes and would require substantial cutting after copying it to a function.jbrockmendel commentedon Mar 21, 2018
The only preference I'll express is that "functions" that take as their first argument either a Model or a Results instance should actually be methods in the appropriate class. It's easy to lose track of these or duplicate code otherwise.
josef-pkt commentedon Mar 21, 2018
@jbrockmendel that is unlikely to happen, the development advantages of taking everything that might be needed from a results or model instance are too large
I just wrote another one like that
https://github.com/statsmodels/statsmodels/pull/4365/files#diff-9ffb91d6d795ecd976d9d249d6ad5b7dR602-R684
After writing that, I understood enough to write a function that includes some parts based on the basic necessary information
https://github.com/statsmodels/statsmodels/pull/4365/files#diff-9ffb91d6d795ecd976d9d249d6ad5b7dR555
The advantage to outsourcing them even if they take a results instance is to collect common pieces together and to avoid making model files huge. Besides, in some cases it is not clear to which results class those functions should be added. (e.g.
get_predictionhas been attached only to GLM and Regression results, for now.)Nevertheless, we need more standalone functions that are more functional and are independent of model and results instances, because those can be used for cases that don't follow the model/results pattern.
e,g, we need inference, standard errors, pvalues and confidence intervals, that can be reused for other things like predict and margins.
jbrockmendel commentedon Mar 21, 2018
Oh of course, obviously nothing is going to happen. I'm just yelling into the wind here.
josef-pkt commentedon Mar 21, 2018
You don't have to be so grumpy. You proposed a design pattern and I explained why that is not feasible.
A results instance is a perfectly valid argument to a function or other class and we have been using it for a long time. Just two more examples, OLSInfluence and DiscreteMargins, both classes take a results instance as argument, OLSInfluence is for OLS only but is supposed to be extended to other model or cases, DiscreteMargins was written for discrete_model but now is delegated to also in GLM and GEE. The same applies to functions as well as classes.
One big advantage is that if enhancements require a new piece of information, then we can just take it from the results/model instance instead of adding more arguments to all affected functions.
The diagnostic tests (statsmodels.sandbox.stats.diagnostic) after OLS take a mix of results instances and specific inputs depending on how much information was needed in the function. There was no serious up-front design, because I had no idea about it and just wanted to add them with whatever way is convenient for the specific function. (Those are still waiting for extension to other models than OLS or to unit tested cases without a model/results.)
This issue here is that, while it was and is convenient to link and integrate functionality with the models, we need now standalone, functional versions for some of those cases, versions that can be reused for non-model purposes.
jbrockmendel commentedon Mar 21, 2018
Fair enough. I’ll take it down a notch.
josef-pkt commentedon Nov 12, 2023
Back to the original issue:
I would like again to just use the inference methods given params, cov_params and possibly df (if use_t=True).
The usecase is when we have different parameterization of the same model and we want (Wald) inference (and params_table?) for each of them.
current issue different representations for complex parameters
old case was normalized parameters (beta coefficients)
AFAIR, we currently use stats.contrast results class for t_test to compute params_table in those cases, but we don't have simple wald tests for those (i.e. normalization for beta coefficients has to be defined by user)