Skip to content

Design: Ad hoc state space models #2330

Closed

Description

@ChadFulton

The design question is whether or not to allow ad hoc state space models. What I mean by ad hoc model is that is created without subclassing MLEModel, but instead creating an instance of MLEModel directly.

As an example, here are two ways to create a model to estimate an AR(1) model:

Usual method

class AR1(MLEModel):

    def __init__(self, endog):
        super(AR1, self).__init__(endog, k_states=1, k_posdef=1)
        self['design'] = [1, 0]
        self['selection', 0, 0] = 1

    def transform_params(self, params):
        params[0] = params[0] / (1 + np.abs(params[1]))
        params[1] = params[1]**2
        return params

    def update(self, params):
        self['transition', 0, 0] = params[0]
        self['state_cov', 0, 0] = params[1]

    @property
    def start_params(self):
        return [0, 0.1]

    @property
    def param_names(self):
        return ['ar.L1', 'sigma2']

Ad hoc

mod = MLEModel(endog, k_states=1, k_posdef=1)
mod['design'] = [1, 0]
mod['selection', 0, 0] = 1

def transformer(mod, params):
    params[0] = params[0] / (1 + np.abs(params[1]))
    params[1] = params[1]**2
    return params
mod.transformer = transformer

def updater(mod, params):
    mod['transition', 0, 0] = params[0]
    mod['state_cov', 0, 0] = params[1]
mod.updater = updater

mod.start_params = [0, 0.1]
mod.param_names = ['ar.L1', 'sigma2']

See also #2284.

The only reason to have the ad hoc method is that it is easier for command-line work, and possibly somewhat easier to understand for a simple model than making people thing in terms of class inheritance.

For simple models I have occasionally found it convenient to use it, even though it's practically no different from a class.

Edit I opened the comment too soon by mistake, so there were errors in the first version and it was incomplete.

Activity

  1. josef-pkt commented on Mar 19, 2015

    @josef-pkt
    Member

    In your Ad hoc version in the description: Where are the def? Are these functions or methods of a class?

  2. ChadFulton commented on Mar 19, 2015

    @ChadFulton
    MemberAuthor

    (Note: the code may have changed since you saw it, I posted the comment before I meant to and it was wrong at first)

    In the ad hoc version, updater and transformer are functions which are then attached to the object, whereas in the usual version they are methods attached to the class.

  3. ChadFulton commented on Mar 19, 2015

    @ChadFulton
    MemberAuthor

    Downsides: if we allow ad hoc models (or at least the current implementation), we have to have the following:

    • MLEModel.__init__ has to run without necessarily knowing the number of parameters.
    • MLEModel.start_params is property with a getter and setter (and in fact for ad hoc models this is how the model knows how many parameters there are!)
    • MLEModel.param_names is a property with a getter and setter
    • MLEModel.update has logic such that if the (possibly confusingly-named) updater object attribute is set, then it calls that attribute with self, params as arguments (i.e. it allows a callable attribute updater to replace the class method update)
    • MLEModel.transform_params similar to update, has logic to allow transformations using a (possibly confusingly-named) transformer callable object attribute.
  4. ChadFulton commented on Mar 19, 2015

    @ChadFulton
    MemberAuthor

    Despite the downsides, I am on balance in favor of allowing the ad hoc models. But I can see an argument for not including it, so I'm happy to get rid of it and just allow inheritance-based state space modeling, particularly since the ad-hoc method would likely be unwieldy for anything even moderately complex.

  5. josef-pkt commented on Mar 19, 2015

    @josef-pkt
    Member

    Ok, I see the correct example. And it is similar to the one in the release notes.

    Maybe we should drop it from the release notes since that advertises it too much as the main approach and we can still refactor later.

    We have a bit a similar problem in nonlinear models, where I haven't fully made up my mind if we should require subclassing or also have a simple function as argument interface.

    As an alternative with a simple interface would be to add a from_functions classmethod, that would work in a similar way on the command line.
    My guess is that this creates instancemethods which cannot be pickled.

  6. ChadFulton commented on Mar 19, 2015

    @ChadFulton
    MemberAuthor

    Maybe we should drop it from the release notes since that advertises it too much as the main approach and we can still refactor later.

    I agree, I will submit a PR tonight or tomorrow to replace it with a class-based example.

    As an alternative with a simple interface would be to add a from_functions classmethod, that would work in a similar way on the command line.
    My guess is that this creates instancemethods which cannot be pickled.

    A class factory / metaclass approach might be interesting. Although I think there are still pickling issues with dynamically created classes which can be overcome but are possibly too much a hassle for this.

  7. bashtage commented on Mar 20, 2015

    @bashtage
    Member

    Seems strange that you are setting some using dictionary syntax and others as attributes/properties.

    mod['design'] = [1, 0]
    mod['selection', 0, 0] = 1

    vs.

    mod.start_params = [0, 0.1]
    mod.param_names = ['ar.L1', 'sigma2']
  8. ChadFulton commented on Mar 20, 2015

    @ChadFulton
    MemberAuthor

    Seems strange that you are setting some using dictionary syntax and others as attributes/properties.

    This is somewhat unfortunate but unavoidable (as far as I know). It's related to the issues in Pandas relating to accessing series in a dataframe.

    x = pd.DataFrame(np.arange(3), columns=['a'])
    del x.a  # raises AttributeError
    del x['a']  # okay

    And, like Pandas, you actually you could use the attribute notation for a lot of things, but there are cases where it wouldn't work and so its behavior has a WTF quality. I recommend only using the slice notation to avoid such things.

    The issue is that when using attribute notation (i.e. mod.design[0, 0] = 1) the call first resolves mod.design and then second sets the [0,0] element to be 1. In many cases this isn't a problem because the object (matrix) returned in the first step remains linked to the attribute.

    One of the main issues arises when you want to change the datatype of the underlying matrix. For example:

    mod.design = np.array([1, 0])
    mod.design[0,0] = 1+1j  # raises: TypeError: can't convert complex to float
    

    the difference is that in the slice notation, I have control of an intermediate step between the call to set the array and the actual array setting, where I can massage things like that.

    You might think - how many times am I going to use complex entries, but the answer is almost all the time because the base class MLEModel uses complex step differentiation to calculate the gradient and Hessian.

  9. ChadFulton commented on Mar 20, 2015

    @ChadFulton
    MemberAuthor

    To be clear, the slice notation only applies to the statespace representation matrices (obs_intercept, design, obs_cov, state_intercept, transition, selection, state_cov). Everything else in the class behaves as a normal class attribute / property.

  10. ChadFulton commented on Feb 12, 2016

    @ChadFulton
    MemberAuthor

    An update on this: we removed the possibility of ad-hoc models in the decoupling PR (#2473), and I think we're settled on not allowing them. So we could probably close this issue.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions