Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion statsmodels/base/_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,13 @@ def fit_constrained_wrap(model, constraints, start_params=None, **fit_kwds):
res = self.fit(start_params=params, maxiter=0,
warn_convergence=False) # we get a wrapper back
res._results.params = params
res._results.normalized_cov_params = cov
res._results.cov_params_default = cov
cov_type = fit_kwds.get('cov_type', 'nonrobust')
if cov_type == 'nonrobust':
res._results.normalized_cov_params = cov / res_constr.scale
else:
res._results.normalized_cov_params = None

k_constr = len(q)
res._results.df_resid += k_constr
res._results.df_model -= k_constr
Expand Down
5 changes: 4 additions & 1 deletion statsmodels/base/covtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ def get_robustcov_results(self, cov_type='HC1', use_t=None, **kwds):
if 'kernel' in kwds:
kwds['weights_func'] = kwds.pop('kernel')

# pop because HCx raises if any kwds
sc_factor = kwds.pop('scaling_factor', None)

# TODO: make separate function that returns a robust cov plus info
use_self = kwds.pop('use_self', False)
if use_self:
Expand Down Expand Up @@ -292,7 +295,7 @@ def get_robustcov_results(self, cov_type='HC1', use_t=None, **kwds):
'available options and spelling')

# generic optional factor to scale covariance
sc_factor = kwds.get('scaling_factor', None)

res.cov_kwds['scaling_factor'] = sc_factor
if sc_factor is not None:
res.cov_params_default *= sc_factor
Expand Down
7 changes: 6 additions & 1 deletion statsmodels/discrete/discrete_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1116,7 +1116,12 @@ def fit_constrained(self, constraints, start_params=None, **fit_kwds):
'iterations', np.nan)
res.mle_retvals['converged'] = res_constr.mle_retvals['converged']
res._results.params = params
res._results.normalized_cov_params = cov
res._results.cov_params_default = cov
cov_type = fit_kwds.get('cov_type', 'nonrobust')
if cov_type != 'nonrobust':
res._results.normalized_cov_params = cov # assume scale=1
else:
res._results.normalized_cov_params = None
k_constr = len(q)
res._results.df_resid += k_constr
res._results.df_model -= k_constr
Expand Down
29 changes: 29 additions & 0 deletions statsmodels/discrete/tests/test_constrained.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
License: BSD-3

"""
from __future__ import division

from statsmodels.compat.python import StringIO
from statsmodels.compat.testing import SkipTest
Expand Down Expand Up @@ -491,6 +492,34 @@ def test_fit_constrained_wrap(self):
assert_allclose(res_wrap.params, res2.params, rtol=1e-6)


class TestGLMLogitConstrained2HC(CheckGLMConstrainedMixin):

@classmethod
def setup_class(cls):
cls.idx = slice(None) # params sequence same as Stata
#res1ul = Logit(data.endog, data.exog).fit(method="newton", disp=0)
cls.res2 = reslogit.results_constraint2_robust

mod1 = GLM(spector_data.endog, spector_data.exog,
family=families.Binomial())

# not used to match Stata for HC
# nobs, k_params = mod1.exog.shape
# k_params -= 1 # one constraint
cov_type = 'HC0'
cov_kwds = {'scaling_factor': 32/31}
Comment thread
josef-pkt marked this conversation as resolved.
Resolved
# looks like nobs / (nobs - 1) and not (nobs - 1.) / (nobs - k_params)}
constr = 'x1 - x3 = 0'
cls.res1m = mod1.fit_constrained(constr, cov_type=cov_type,
cov_kwds=cov_kwds, atol=1e-10)

R, q = cls.res1m.constraints.coefs, cls.res1m.constraints.constants
cls.res1 = fit_constrained(mod1, R, q, fit_kwds={'atol': 1e-10,
'cov_type': cov_type,
'cov_kwds': cov_kwds})
cls.constraints_rq = (R, q)


def junk():
# Singular Matrix in mod1a.fit()

Expand Down
8 changes: 7 additions & 1 deletion statsmodels/genmod/generalized_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1279,7 +1279,13 @@ def fit_constrained(self, constraints, start_params=None, **fit_kwds):
#create dummy results Instance, TODO: wire up properly
res = self.fit(start_params=params, maxiter=0) # we get a wrapper back
res._results.params = params
res._results.normalized_cov_params = cov
res._results.cov_params_default = cov
cov_type = fit_kwds.get('cov_type', 'nonrobust')
if cov_type != 'nonrobust':
res._results.normalized_cov_params = cov / res_constr.scale
else:
res._results.normalized_cov_params = None
res._results.scale = res_constr.scale
k_constr = len(q)
res._results.df_resid += k_constr
res._results.df_model -= k_constr
Expand Down
107 changes: 107 additions & 0 deletions statsmodels/genmod/tests/test_constrained.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# -*- coding: utf-8 -*-
"""
Unit tests for fit_constrained
Tests for Poisson and Binomial are in discrete


Created on Sun Jan 7 09:21:39 2018

Author: Josef Perktold
"""


import numpy as np
from numpy.testing import assert_allclose, assert_equal
from statsmodels.tools.tools import add_constant
from statsmodels.regression.linear_model import OLS
from statsmodels.genmod.generalized_linear_model import GLM


class ConstrainedCompareMixin(object):

@classmethod
def setup_class(cls):
nobs, k_exog = 100, 5
np.random.seed(987125)
x = np.random.randn(nobs, k_exog - 1)
x = add_constant(x)

y_true = x.sum(1) / 2
y = y_true + 2 * np.random.randn(nobs)
cls.endog = y
cls.exog = x
cls.idx_uc = [0, 2, 3, 4]
cls.idx_p_uc = np.array(cls.idx_uc)
cls.idx_c = [1]
cls.exogc = xc = x[:, cls.idx_uc]
mod_ols_c = OLS(y - 0.5 * x[:, 1], xc)
mod_ols_c.exog_names[:] = ['const', 'x2', 'x3', 'x4']
cls.mod2 = mod_ols_c
cls.init()

def test_params(self):
res1 = self.res1
res2 = self.res2
assert_allclose(res1.params[self.idx_p_uc], res2.params, rtol=1e-10)

def test_se(self):
res1 = self.res1
res2 = self.res2

assert_equal(res1.df_resid, res2.df_resid)
# why does scale differ
assert_allclose(res1.scale, res2.scale, rtol=0.05)
assert_allclose(res1.bse[self.idx_p_uc], res2.bse, rtol=1e-10)
assert_allclose(res1.cov_params()[self.idx_p_uc[:,None], self.idx_p_uc],
res2.cov_params(), rtol=1e-10)

def test_resid(self):
res1 = self.res1
res2 = self.res2
assert_allclose(res1.resid_response, res2.resid, rtol=1e-10)


class TestGLMGaussianOffset(ConstrainedCompareMixin):

@classmethod
def init(cls):
cls.res2 = cls.mod2.fit()
mod = GLM(cls.endog, cls.exogc,
offset=0.5 * cls.exog[:, cls.idx_c].squeeze())
mod.exog_names[:] = ['const', 'x2', 'x3', 'x4']
cls.res1 = mod.fit()
cls.idx_p_uc = np.arange(cls.exogc.shape[1])


class TestGLMGaussianConstrained(ConstrainedCompareMixin):

@classmethod
def init(cls):
cls.res2 = cls.mod2.fit()
mod = GLM(cls.endog, cls.exog)
mod.exog_names[:] = ['const', 'x1', 'x2', 'x3', 'x4']
cls.res1 = mod.fit_constrained('x1=0.5')


class TestGLMGaussianOffsetHC(ConstrainedCompareMixin):

@classmethod
def init(cls):
cov_type = 'HC0'
cls.res2 = cls.mod2.fit(cov_type=cov_type)
mod = GLM(cls.endog, cls.exogc,
offset=0.5 * cls.exog[:, cls.idx_c].squeeze())
mod.exog_names[:] = ['const', 'x2', 'x3', 'x4']
cls.res1 = mod.fit(cov_type=cov_type)
cls.idx_p_uc = np.arange(cls.exogc.shape[1])


class TestGLMGaussianConstrainedHC(ConstrainedCompareMixin):

@classmethod
def init(cls):
cov_type = 'HC0'
cls.res2 = cls.mod2.fit(cov_type=cov_type)
mod = GLM(cls.endog, cls.exog)
mod.exog_names[:] = ['const', 'x1', 'x2', 'x3', 'x4']
cls.res1 = mod.fit_constrained('x1=0.5', cov_type=cov_type)