Skip to content

added discrete model fit_regularized pickle test - #2686

Closed
kashif wants to merge 1 commit into
statsmodels:masterfrom
kashif:issue-2685
Closed

kashif wants to merge 1 commit into
statsmodels:masterfrom
kashif:issue-2685

Conversation

@kashif

@kashif kashif commented Oct 30, 2015

Copy link
Copy Markdown

currently fails for issue #2685

@josef-pkt

Copy link
Copy Markdown
Member

@kashif Thanks, I think it's the first time that we get a bug report as unit test. Great.

First results on TravisCI. It passes on python 3.4 which I use, but fails on python 3.3 (others are not finished yet).

I didn't see anything directly related to pickling instance methods in the python 3 changes/release notes. But using instance methods is a bug for us.

@josef-pkt

Copy link
Copy Markdown
Member

I don't find the instance method using inspection of the instances and classes, pdb also doesn't tell.

It's somewhere in results._results (unwrapped), the model pickles without problems in python 2.7 and statsmodels master from a while ago.

@josef-pkt

Copy link
Copy Markdown
Member

Ok, I found the offending part

>>> tt.results._results.mle_settings['cov_params_func']
<bound method Poisson.cov_params_func_l1 of <statsmodels.discrete.discrete_model
.Poisson object at 0x02C69F50>>

if I delete this key, then it pickles without problems on python 2.7

del tt.results._results.mle_settings['cov_params_func']

I'm not sure what this does or why we need it.
mle_settings are just for information and not required by any code (AFAIK and at least for now).
We can either delete or store the name instead of the method itself.

@kashif

kashif commented Oct 30, 2015

Copy link
Copy Markdown
Author

ah 🆒! having a look now too

@kashif

kashif commented Nov 2, 2015

Copy link
Copy Markdown
Author

Deleting cov_params_func then saving and loading the model gives the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-72-a97f7e4d1340> in <module>()
----> 1 load.predict(exog=test_data_frame, exposure=np.array(test_data_frame['returned_items']))

/Users/krasul/.virtualenvs/asf5/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.10-x86_64.egg/statsmodels/base/model.pyc in predict(self, exog, transform, *args, **kwargs)
    737         if transform and hasattr(self.model, 'formula') and exog is not None:
    738             from patsy import dmatrix
--> 739             exog = dmatrix(self.model.data.orig_exog.design_info.builder,
    740                            exog)
    741 

/Users/krasul/.virtualenvs/asf5/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name)
   2244                 return self[name]
   2245             raise AttributeError("'%s' object has no attribute '%s'" %
-> 2246                                  (type(self).__name__, name))
   2247 
   2248     def __setattr__(self, name, value):

AttributeError: 'DataFrame' object has no attribute 'design_info'

@josef-pkt

Copy link
Copy Markdown
Member

To your last traceback

pickling when a model uses formulas was not supported in statsmodels-0.6.1

It is supported in master through a workaround that requires that the full original data is also pickled. Full support for pickling formulas directly is still missing in patsy. see #2469

Using the numpy array and pandas interface is supposed to be fully supported.

Do you have difficult transformation, like categorical interactions, in your formula?

@kashif

kashif commented Nov 5, 2015

Copy link
Copy Markdown
Author

yes so the formula a categorical feature: C(category, Sum) but no interaction terms.

@josef-pkt

Copy link
Copy Markdown
Member

@kashif Handling the categorical will be a but ugly, but because it's not an interaction effect it should still be ok. You have two option with master (until patsy allows pickling)

  • Use the current builtin workaround (in statsmodels master, not in 0.6.1), which requires to save the original data in the pickle, and rebuild the formula each time when unpickling. That should be ok if the dataset is not very large and you don't need to unpickle very often, i.e. don't create instances in a loop.
  • Write a custom transformation function, that builds a predictive exog from the data. (Assuming you pickle in order to predict.) This could use pandas to dummy function for categoricals plus a linear transformation, or maybe (need to check if patsy allows extra levels) using patsy.dmatrix directly.

@jbrockmendel

Copy link
Copy Markdown
Contributor

I'm still getting this error, will spend some time trying to troubleshoot it.

@josef-pkt

Copy link
Copy Markdown
Member

see my comment above about del tt.results._results.mle_settings['cov_params_func']

I didn't check if there is a reason to restore it after unpickling, I guessed not.

@jbrockmendel

Copy link
Copy Markdown
Contributor

DiscreteResults.__getstate__ already checks to ensure that mle_settings['callback'] is not a method. A simple solution here could look like:

    def __getstate__(self):
        settings = self.mle_settings
        settings['callback'] = None
        if 'cov_params_func' in settings:
            settings['cov_params_func'] = None
        return self.__dict__

However, a quick attempt at handling this more generally failed:

    def __getstate__(self):
        settings = self.mle_settings
        meths = [key for key in settings if inspect.ismethod(settings[key])]
        for key in meths:
            settings[key] = None

The former passes the new test, while the latter fails with the same error as the status-quo.

@josef-pkt

Copy link
Copy Markdown
Member

I prefer the first explicit version. There shouldn't be many of those ever, to need inspect

@josef-pkt

Copy link
Copy Markdown
Member

@jbrockmendel Can you take over the PR, i.e. check it out, rebase, add your changes and push to new PR?

@jbrockmendel

Copy link
Copy Markdown
Contributor

I prefer the first explicit version. There shouldn't be many of those ever, to need inspect

Agreed.

Can you take over the PR, i.e. check it out, rebase, add your changes and push to new PR?

Sure.

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