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
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
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
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.
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.
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.
@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?
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.
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).
@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.
@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.
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. ???
@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.
Activity
jseabold commentedon Apr 11, 2014
If the builder isn't available then we just fall back to
jseabold commentedon Apr 11, 2014
We might just do this anyway.
josef-pkt commentedon Apr 11, 2014
Does that work with stateful transforms and category level transformation? I would think it won't.
jseabold commentedon Apr 11, 2014
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.
jseabold commentedon Apr 11, 2014
Oh, if the X is different. Hmm. Right.
jseabold commentedon Apr 11, 2014
Yeah, we may have to pickle the builder explicitly, if we can.
jseabold commentedon Jan 10, 2015
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
josef-pkt commentedon Jan 10, 2015
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
evalenvironment is not needed.jseabold commentedon Jan 10, 2015
I might have a workaround.
jseabold commentedon Jan 10, 2015
Thought this doesn't work right now even if you don't use a formula AFAICT
jseabold commentedon Jan 10, 2015
Strike that. I broke it.
josef-pkt commentedon Jan 10, 2015
We have unit tests for pickling in
basefor the case when endog and exog are ndarrays, but currently no other case is tested and "officially" supported.ENH: pickle models created with formulas. Closes statsmodels#1263.
ENH: pickle models created with formulas. Closes statsmodels#1263.
7 remaining items
njsmith commentedon Apr 25, 2015
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.
chrimobs commentedon Apr 27, 2015
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.
josef-pkt commentedon Apr 27, 2015
@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?
josef-pkt commentedon Apr 27, 2015
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
frameduring pickle load.From this it looks like no transformation would work after unpickling. ???
josef-pkt commentedon Apr 27, 2015
Ok, that works for the example, use
frameif available, else use current behaviorThe 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.
chrimobs commentedon Apr 27, 2015
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:
The original data was transformed using
np.log10(x).josef-pkt commentedon Apr 27, 2015
Ok, in
base.model.from_formulawe save the original dataframemod.data.frame = data(I didn't know)
So the
try exceptshould be just a precaution and not necessary in standard usage (ifframehasn't been deleted)josef-pkt commentedon Apr 27, 2015
@chrimobs about
NameError: name 'np' is not definedDo you have
npin 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.chrimobs commentedon Apr 27, 2015
Yes,
npis imported in the environment.josef-pkt commentedon Apr 27, 2015
@chrimobs I can replicate the
np.logproblem, 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.
josef-pkt commentedon Apr 27, 2015
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 modulesboth
np.logand userlogare available with depth=3I guess either another
try exceptfor "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. ???
josef-pkt commentedon Apr 27, 2015
@chrimobs My examples work now with the two
try exceptin my PR, includinglogornp.logYou 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.
josef-pkt commentedon Jun 24, 2015
closing this, this part is fixed by #2375,
refactor for using patsy's pickling support is issue #2469