Skip to content

"AttributeError: Memoryview is not initialized" when loading a MLEResults object #3290

Closed

Description

@lafras

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

  1. ChadFulton commented on Nov 25, 2016

    @ChadFulton
    Member

    Thanks again for reporting this. There are two options:

    1. Try to make this work.
    2. Give a better error message; something along the lines of "Models created using load cannot 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.params as 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?

  2. v5364704 commented on Mar 28, 2017

    @v5364704

    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.

  3. ChadFulton commented on Mar 28, 2017

    @ChadFulton
    Member

    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 the summary command to cache a bunch of the most used elements), then I think they should be available after load.

    But we do need a better error message than "Memoryview is not initialized".

  4. v5364704 commented on Mar 28, 2017

    @v5364704

    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.

  5. ChadFulton commented on Mar 28, 2017

    @ChadFulton
    Member

    Though probably non-priority enhancement, but such things could be parameterized in save() method.

    Maybe @josef-pkt has a perspective on why the cache / save system works as it does.

  6. josef-pkt commented on Mar 28, 2017

    @josef-pkt
    Member

    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

    • save the 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 pickling
    • for limited use cases like prediction with new data we don't need the extra information. remove_data removes 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 think save is 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 to summary() 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 a summary() 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.

  7. bashtage commented on Oct 2, 2017

    @bashtage
    Member

    @josef-pkt This was fixed in master when pickling was corrected

  8. josef-pkt commented on Oct 2, 2017

    @josef-pkt
    Member

    @bashtage Thanks for the info, closing

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

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions