Skip to content

BUG pickling formula information  #1263

Closed

Description

@josef-pkt

AFAIU:
The formula information is attached to the dataframe orig_exog. Pickling and unpickling the results and model instance looses the information.
Predict which relies on this information if transform=True, the default, is then broken and raises an exception

see http://stackoverflow.com/questions/20724919/pandas-dataframe-attributeerror-dataframe-object-has-no-attribute-design-inf/20726340

    p = result.predict(newdf)
  File "C:\Python27\lib\site-packages\statsmodels\base\model.py", line 878, in predict
    exog = dmatrix(self.model.data.orig_exog.design_info.builder,
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 2088, in __getattr__
    (type(self).__name__, name))
AttributeError: 'DataFrame' object has no attribute 'design_info'

test case

import cPickle
import pandas as pd
import numpy as np
import statsmodels.formula.api as sm

df = pd.DataFrame({"A": [10,20,30,324,2353], "B": [20, 30, 10, 1, 2332], "C": [0, -30, 120, 11, 2]})

result = sm.ols(formula="A ~ B + C", data=df).fit()
print result.summary()

test1 = result.predict(df) #works

f_myfile = open('resultobject', "wb")
cPickle.dump(result, f_myfile, 2)
f_myfile.close()
print("Result Object Saved")


f_myfile = open('resultobject', "rb")
model = cPickle.load(f_myfile)

test2 = model.predict(df) #produces error

Activity

  1. jseabold commented on Apr 11, 2014

    @jseabold
    Member

    If the builder isn't available then we just fall back to

    dmatrix(self.model.formula.split('~')[1], exog)
    
  2. jseabold commented on Apr 11, 2014

    @jseabold
    Member

    We might just do this anyway.

  3. josef-pkt commented on Apr 11, 2014

    @josef-pkt
    MemberAuthor

    Does that work with stateful transforms and category level transformation? I would think it won't.

  4. jseabold commented on Apr 11, 2014

    @jseabold
    Member

    Why wouldn't it? It's the original formula that created the data in the first place. We won't be able to guarantee that any transform functions are in the namespace. We could with dill I think, but I don't think it's worth it. I'm starting to worry about the data copies we carry around already.

  5. jseabold commented on Apr 11, 2014

    @jseabold
    Member

    Oh, if the X is different. Hmm. Right.

  6. jseabold commented on Apr 11, 2014

    @jseabold
    Member

    Yeah, we may have to pickle the builder explicitly, if we can.

  7. added this to the 0.7 milestone on Jan 10, 2015
  8. jseabold commented on Jan 10, 2015

    @jseabold
    Member

    I'm thinking we should just raise an informative error here. I don't see an easy way to pickle objects created with a formula.

    @njsmith

  9. josef-pkt commented on Jan 10, 2015

    @josef-pkt
    MemberAuthor

    We won't get a fix for 0.7, since there is not much we can do.

    But this is a bug and issue should remain open (indefinitely).

    I think we might be able to get it partially, if the eval environment is not needed.

  10. jseabold commented on Jan 10, 2015

    @jseabold
    Member

    I might have a workaround.

  11. jseabold commented on Jan 10, 2015

    @jseabold
    Member

    Thought this doesn't work right now even if you don't use a formula AFAICT

  12. jseabold commented on Jan 10, 2015

    @jseabold
    Member

    Strike that. I broke it.

  13. josef-pkt commented on Jan 10, 2015

    @josef-pkt
    MemberAuthor

    We have unit tests for pickling in base for the case when endog and exog are ndarrays, but currently no other case is tested and "officially" supported.

  14. added a commit that references this issue on Jan 10, 2015
    eeebc5c
  15. added a commit that references this issue on Feb 11, 2015
    654870c
  16. 7 remaining items

  17. njsmith commented on Apr 25, 2015

    @njsmith
    Contributor

    FYI @chrish42 got a start towards making patsy builders pickleable (which is the only real solution here) at the pycon sprints -- see pydata/patsy#66.

  18. chrimobs commented on Apr 27, 2015

    @chrimobs

    As a motivation: Would it make any difference knowing that my dissertation may depend on this (proper unpickling when the model (the RegressionResult) contains transformed variables)? :)
    Maybe I could go without categorical variables, but the models do not perform well without them. I'm pondering on workarounds in my evaluation suite, but having that unpickling/prediction at hand would be very nice.

  19. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    @chrimobs I don't think having to drop categorical variables is a reasonable option.
    What is your use case for pickling? Maybe there is an easier way to achieve the same task, at least until this is fixed.
    Do you need the transformation in the post-estimation results, like predict, or can you transform all your data at once?

  20. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    stepping up from the exception with pdb, the problem seems to be that we give patsy the transformed data and not the original data.
    I think we don't keep the original dataframe around. In the example, the original data is in frame during pickle load.

    (Pdb) data
        p  Intercept  c:C(a)[0]  c:C(a)[1]
    0  20          1          0       0.00
    1  21          1          1       0.00
    2  22          1          1       0.00
    3  23          1          0       3.00
    4  24          1          0       3.00
    5  26          1          0       4.00
    6  28          1          0       4.00
    7  29          1          0       4.95
    8  30          1          0       6.31
    9  31          1          0       7.00
    

    From this it looks like no transformation would work after unpickling. ???

  21. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    Ok, that works for the example, use frame if available, else use current behavior

                try:
                    data = d['frame']
                except KeyError:
                    data = d['orig_endog'].join(d['orig_exog'])
    

    The pickle file might be pretty large if we save several copies of the data in this case.

    Unit tests for low memory pickling, after removing data that is not needed for prediction, are only for use with ndarrays.

  22. chrimobs commented on Apr 27, 2015

    @chrimobs

    My problem is that unpickling already fails if the original data was transformed to fit the model. This is what I get in such a case:

    Traceback (most recent call last):
      File "./ru_wl_eval.py", line 26, in <module>
        res = smlm.RegressionResults.load(res_f)
      File "/usr/local/lib/python2.7/dist-packages/statsmodels-0.7.0-py2.7-linux-i686.egg/statsmodels/base/model.py", line 1675, in load
        return load_pickle(fname)
      File "/usr/local/lib/python2.7/dist-packages/statsmodels-0.7.0-py2.7-linux-i686.egg/statsmodels/iolib/smpickle.py", line 41, in load_pickle
        return cPickle.load(fin)
      File "/usr/local/lib/python2.7/dist-packages/statsmodels-0.7.0-py2.7-linux-i686.egg/statsmodels/base/data.py", line 98, in __setstate__
        return_type='dataframe')
      File "build/bdist.linux-i686/egg/patsy/highlevel.py", line 297, in dmatrices
      File "build/bdist.linux-i686/egg/patsy/highlevel.py", line 152, in _do_highlevel_design
      File "build/bdist.linux-i686/egg/patsy/highlevel.py", line 57, in _try_incr_builders
      File "build/bdist.linux-i686/egg/patsy/build.py", line 660, in design_matrix_builders
      File "build/bdist.linux-i686/egg/patsy/build.py", line 424, in _examine_factor_types
      File "build/bdist.linux-i686/egg/patsy/eval.py", line 485, in eval
        pwr_eval = ev.evaluators.PowerLevelEvaluator(pwr_mdc, 
      File "build/bdist.linux-i686/egg/patsy/eval.py", line 468, in _eval
        mach_res_dir)
      File "build/bdist.linux-i686/egg/patsy/compat.py", line 117, in call_and_wrap_exc
      File "build/bdist.linux-i686/egg/patsy/eval.py", line 127, in eval
        if type(first_pred) == pan.Series:
      File "<string>", line 1, in <module>
    NameError: name 'np' is not defined
    

    The original data was transformed using np.log10(x).

  23. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    Ok, in base.model.from_formula we save the original dataframe
    mod.data.frame = data

    (I didn't know)

    So the try except should be just a precaution and not necessary in standard usage (if frame hasn't been deleted)

  24. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    @chrimobs about NameError: name 'np' is not defined
    Do you have np in the environment where you unpickle? All functions used in the formula need to be available in the "environment". There are still some limitations in this for unpickling that we haven't implemented a work around.

    patsy's use of the surrounding environment with eval (following R and other weird packages) is the major problem for pickling formulas.

  25. chrimobs commented on Apr 27, 2015

    @chrimobs

    Yes, np is imported in the environment.

  26. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    @chrimobs I can replicate the np.log problem, and I thought that was supposed to work with the eval depth, but it doesn't.
    I'm stuck on this, I don't see much with the debugger. And I never tried to understand the evil EvalEnvironment.

    workaround: add a new column to the data frame with the transformed variable.

    Solution for this requires a formula expert, which I'm not.

    I will prepare a PR with the fix for original data.

  27. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    PR is #2375

    about EvalEnvironment: I didn't try enough depth levels before
    np. is available with depth=0 which I guess is one of our modules
    both np.log and user log are available with depth=3

    I guess either another try except for "depth search" or and option for the user will be necessary.

    edit
    Now also depth=2 works, and I don't know why or why it didn't seem to when I tried before. ???

  28. josef-pkt commented on Apr 27, 2015

    @josef-pkt
    MemberAuthor

    @chrimobs My examples work now with the two try except in my PR, including log or np.log
    You could give it a try with your cases.
    I'm out of time right now, but will try to add the unit tests and merge later today.

  29. josef-pkt commented on Jun 24, 2015

    @josef-pkt
    MemberAuthor

    closing this, this part is fixed by #2375,

    refactor for using patsy's pickling support is issue #2469

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions