Repository navigation
Closed
Closed
Copy link
Description
The following script produces an AttributeError:
from numpy import sin, pi
import pandas
import statsmodels.api as sm
def endog(periods):
"""Fake data"""
index = pandas.timedelta_range(
start='00:00:00',
periods=periods,
freq=100 * pandas.tseries.frequencies.Milli(),
name='time'
)
level = 5.0
cycle = sin(2 * pi * 0.5 * index.total_seconds())
return pandas.DataFrame(
data=level+cycle,
index=pandas.to_datetime(
index.values
)
)
trainer = sm.tsa.UnobservedComponents(
endog(10**2),
level=True,
autoregressive=2,
)
fit = trainer.fit(
method='powell'
)
fit.save('trainer.pickle')
old_fit = sm.tsa.statespace.MLEResults.load('trainer.pickle')
old_trainer = old_fit.model
new_fit = old_trainer.fit(
old_fit.params,
method='lbfgs'
)The traceback looks like this:
Traceback (most recent call last):
File "minimal.py", line 44, in <module>
method='lbfgs'
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 448, in fit
skip_hessian=True, **kwargs)
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/base/model.py", line 436, in fit
full_output=full_output)
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/base/optimizer.py", line 184, in _fit
hess=hessian)
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/base/optimizer.py", line 378, in _fit_lbfgs
**extra_kwargs)
File "/home/lafras/.local/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py", line 193, in fmin_l_bfgs_b
**opts)
File "/home/lafras/.local/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py", line 328, in _minimize_lbfgsb
f, g = func_and_grad(x)
File "/home/lafras/.local/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py", line 273, in func_and_grad
f = fun(x, *args)
File "/home/lafras/.local/lib/python3.5/site-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
return function(*(wrapper_args + args))
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/base/model.py", line 414, in <lambda>
f = lambda params, *args: -self.loglike(params, *args) / nobs
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/mlemodel.py", line 644, in loglike
loglike = self.ssm.loglike(complex_step=complex_step, **kwargs)
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/kalman_filter.py", line 678, in loglike
return np.sum(self.filter(**kwargs)[loglikelihood_burn:])
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/kalman_filter.py", line 620, in filter
conserve_memory, tolerance, loglikelihood_burn
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/kalman_filter.py", line 261, in _initialize_filter
prefix, dtype, create_statespace = self._initialize_representation()
File "/home/lafras/.local/lib/python3.5/site-packages/statsmodels/tsa/statespace/representation.py", line 657, in _initialize_representation
not ss.obs.shape[1] == self.endog.shape[1] or
File "statsmodels\tsa\statespace\_statespace.pyx", line 4095, in statsmodels.tsa.statespace._statespace.dStatespace.obs.__get__ (statsmodels/tsa/statespace/_statespace.c:34279)
AttributeError: Memoryview is not initialized
Activity
ChadFulton commentedon Nov 25, 2016
Thanks again for reporting this. There are two options:
loadcannot be fit, filtered, or smoothed`I'm leaning towards the second, and my suggestion for your use case would be to just create a new model instance to fit using the
old_fit.paramsas starting params, rather than using the loaded model instance again.Would that work for you? I know you mentioned you have a particular work flow - is there a reason why re-using the loaded model instance is better?
v5364704 commentedon Mar 28, 2017
I've got the same error when trying to access aic attribute of loaded SARIMAXResults object. Though it could also be acquired from summary tables, that I think is something that should be available after model is restored.
ChadFulton commentedon Mar 28, 2017
I think that this means the AIC element was not cached prior to saving. If you make sure to access the elements you need prior to
save(or e.g. call thesummarycommand to cache a bunch of the most used elements), then I think they should be available afterload.But we do need a better error message than "Memoryview is not initialized".
v5364704 commentedon Mar 28, 2017
Huh... It works, thank you!
It wasn't that hard to save summaries separately, but having one single file instead of two is much better.
Though probably non-priority enhancement, but such things could be parameterized in save() method.
ChadFulton commentedon Mar 28, 2017
Maybe @josef-pkt has a perspective on why the cache / save system works as it does.
josef-pkt commentedon Mar 28, 2017
I'm not sure the details in statespace model or tsa overall.
The way it is supposed to work in general, outside of tsa, is that we
savethe full results and model instance (*) including all data, then we should be able to unpickle the full working models and results and continue in the same way as without picklingremove_dataremoves large arrays but no small stored, attributes or cached, information. For cached information only what is already in cache is getting pickled. I don't thinksaveis the right place to manipulate the cache. Cached attributes are created and cached when they are used. So users can either explicitly access the attributes that they want to be in cache and be pickled. In the generic unit tests (for non-tsa models) I added a call tosummary()before pickling, because that creates most of the cached attributes.However, which attributes are cached is a bit of an open question. (**) If the model instance without data (
remove_data) is cached, then summary would not work anymore if asummary()call wants to compute things that need something that is not available anymore. (I don't remember if I ever tried that. I think diagnostic information in OLS summary would need full arrays like resid.)(*) there is still a problem with formulas that cannot be pickled and need to be regenerated when unpickling (as a limited workaround).
(**) In the early models almost everything was cached. Results that are accessed through methods with options are not cached. For large data, there is also a trade-off between saving on recomputation and memory requirement, and the decisions about what is cached is a bit "ad-hoc".
I was also thinking several times whether we need an official way to manipulate the cache i.e. delete cached attributes so they will be recomputed (if the required data is still available). But so far I haven't heard of any usecases where users would really need to do that.
bashtage commentedon Oct 2, 2017
@josef-pkt This was fixed in master when pickling was corrected
josef-pkt commentedon Oct 2, 2017
@bashtage Thanks for the info, closing
BUG: Use new parameters in state space models restored from a pickle