Repository navigation
Description
Following the pattern of Mixins that modify loglike and related methods, I started with a Mixin that does parameter transformation to impose for example nonlinear restrictions and restriction on parameters that are not exog related.
The competing design of building the transformation and restrictions directly into a LikelihoodModel is used in several places.
The advantage of a Mixin is that we can extend existing models to include parameter restrictions and transformations. The mixin modifies loglike and similar on top of existing methods and wouldn't collide with existing transformation.
The second advantage is that we can separately develop and experiment with code in how to handle this more generically, without starting to change existing models.
Basic structure of the mixin is easy, but it needs a lot more work to handle all occurences of params, and to separate estimated params from transformed/expanded params, relevant for inference and for summary.
*Difference to fit_constrained: *
fit_constrained and similar create an auxiliary model and transform the exog array making a copy of the relevant data (or a view if submatrix is aligned, I guess). The parameter of the auxiliary model is transformed into the original parameter space (this could apply also to the ConstrainedMixin), but the auxiliary model is just a standard model without restrictions.
related - still TODO: we need a more consistent patterns for Transformation and nonlinear function classes
Getting the details done is too much distraction right now, so here's the script (based on PenalizedMixin, run on python 3.4)
# -*- coding: utf-8 -*-
"""
Created on Wed May 13 20:15:34 2015
Author: Josef Perktold
License: BSD-3
"""
import numpy as np
from statsmodels.discrete.discrete_model import Poisson
class ConstrainedMixin(object):
# def __init__(self, *args, penal=None, **kwds):
# super(ConstrainedMixin, self).__init__(*args, **kwds)
#
# if penal is None:
# self.penal = smpen.SCADSmoothed(0.1, c0=0.0001)
# else:
# self.penal = penal
# self.pen_weight = len(self.endog) #100.
def set_constraints(self, transform):
self.transform = transform
def loglike(self, params, transform=True):
if transform:
params = self.transform.expand(params)
llf = super(ConstrainedMixin, self).loglike(params)
return llf
def score(self, params, transform=True):
if transform:
loglike = self.loglike
else:
loglike = lambda p: self.loglike(p, transform=transform)
from statsmodels.tools.numdiff import approx_fprime
return approx_fprime(params, loglike)
def score_todo(self, params, transform=True):
if transform:
params = self.transform.expand(params)
sc = super(ConstrainedMixin, self).score(params)
return sc
def hessian(self, params, transform=True):
if transform:
loglike = self.loglike
else:
loglike = lambda p: self.loglike(p, transform=transform)
from statsmodels.tools.numdiff import approx_hess
return approx_hess(params, loglike)
def hessian_todo(self, params, transform=True):
# add transform derivatives
if transform:
params = self.transform.expand(params)
sc = super(ConstrainedMixin, self).hessian(params)
return sc
class PoissonConstrained(ConstrainedMixin, Poisson):
pass
#class LogitConstrained(ConstrainedMixin, Logit):
# pass
#
#class ProbitConstrained(ConstrainedMixin, Probit):
# pass
class ExampleTransform(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
def expand(self, params):
"""take reduced constrained params and return full params
"""
params_new = np.zeros(self.k_params)
params_new[self.mask] = params
params_new[~self.mask] = self.func(params)
return params_new
class ExampleTransform2(object):
def __init__(self, k_params, **kwds):
self.k_params = k_params
self.change_index = [1, 2]
self.func = lambda p: [(p[0] + np.sqrt(p[3])) / 3, 2 * p[3]]
mask = np.ones(k_params, dtype=np.bool_)
mask[self.change_index] = False
self.keep_index = mask #np.arange(k_params)
self.__dict__.update(kwds)
def expand(self, params):
"""take reduced constrained params and return full params
"""
params_new = np.zeros(self.k_params)
params_new[self.keep_index] = params
params_new[self.change_index] = self.func(params_new)
return params_new
def dummy_func(*args, **kwds):
pass
# simulate data
np.set_printoptions(suppress=True)
np.random.seed(987865)
nobs, k_vars = 100, 5
k_nonzero = 4
x = (np.random.rand(nobs, k_vars) + 0.5* (np.random.rand(nobs, 1)-0.5)) * 2 - 1
x *= 1.2
x[:, 0] = 1
beta = np.zeros(k_vars)
beta[:k_nonzero] = 1. / np.arange(1, k_nonzero + 1)
linpred = x.dot(beta)
mu = np.exp(linpred)
y = np.random.poisson(mu)
res0 = Poisson(y, x).fit()
modr = PoissonConstrained(y, x)
transf = ExampleTransform2(x.shape[1])
modr.set_constraints(transf)
resr = modr.fit(start_params = res0.params[transf.keep_index], callback=dummy_func)
#example is adjusted so the difference is not too large
#transf.expand(res0.params[transf.keep_index])
p = transf.expand(resr.params)
print(p)
print(res0.model.loglike(p))
print(resr.model.loglike(p, transform=False))
print(resr.llf)
print(res0.llf)
# todo LR test
Activity