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
4 changes: 2 additions & 2 deletions docs/source/release/version0.9.rst
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ see https://github.com/statsmodels/statsmodels/issues?q=is%3Aissue+label%3Atype-
- null_deviance and llnull in GLMResults were wrong if exposure was used and when offset was used with Binomial counts.
- GLM Binomial in the non-binary, count case used incorrect endog in recreating models which is
used by fit_regularized and fit_constrained #4599.
This case is still not sufficiently tested for extra methods.
- discrete predict with offset or exposure, #3569 fixed in 3696
- GLM observed hessian was incorrectly computed if non-canonical link is used, fixed in #4620
- discrete predict with offset or exposure, #3569 fixed in #3696
If either offset or exposure are not None but exog is None, then offset and exposure arguments in predict were ignored.
- discrete margins had wrong dummy and count effect if constant is prepended, #3695 fixed in #3696
- OLS outlier test, wrong index if order is True, #3971 fixed in #4385
Expand Down
31 changes: 20 additions & 11 deletions statsmodels/discrete/tests/test_sandwich_cov.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,13 +479,9 @@ def test_basic(self):
assert_equal(res1.cov_type, self.cov_type)
assert_equal(res2.cov_type, self.cov_type)

assert_allclose(res1.params, res2.params, rtol=1e-13)
# bug TODO res1.scale missing ? in Gaussian/OLS
assert_allclose(res1.bse, res2.bse, rtol=1e-13)
# if not self.cov_type == 'nonrobust':
# assert_allclose(res1.bse * res1.scale, res2.bse, rtol=1e-13)
# else:
# assert_allclose(res1.bse, res2.bse, rtol=1e-13)
rtol = getattr(res1, 'rtol', 1e-13)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be getting cls.rtol? That is the attribute that is set down on L514.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that's a mistake.
However, why do the tests not fail if rtol is 1e-13?

Essentially this means that GLM and the corresponding discrete model agree on very high precision with the same optimizer newton. 1e-13 should be much stricter than convergence tolerance.

assert_allclose(res1.params, res2.params, rtol=rtol)
assert_allclose(res1.bse, res2.bse, rtol=1e-10)


class TestGLMLogit(CheckDiscreteGLM):
Expand All @@ -502,19 +498,32 @@ def setup_class(cls):
cls.res2 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))


class T_estGLMProbit(CheckDiscreteGLM):
# invalid link. What's Probit as GLM?
class TestGLMProbit(CheckDiscreteGLM):

@classmethod
def setup_class(cls):
endog_bin = (endog > endog.mean()).astype(int)
cls.cov_type = 'cluster'

mod1 = GLM(endog_bin, exog, family=families.Gaussian(link=links.CDFLink()))
cls.res1 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
mod1 = GLM(endog_bin, exog, family=families.Binomial(link=links.probit()))
cls.res1 = mod1.fit(method='newton',
cov_type='cluster', cov_kwds=dict(groups=group))

mod1 = smd.Probit(endog_bin, exog)
cls.res2 = mod1.fit(cov_type='cluster', cov_kwds=dict(groups=group))
cls.rtol = 1e-6

def test_score_hessian(self):
res1 = self.res1
res2 = self.res2
# Note scale is fixed at 1, so we don't need to fix it explicitly
score1 = res1.model.score(res1.params * 0.98)
score2 = res2.model.score(res1.params * 0.98)
assert_allclose(score1, score2, rtol=1e-13)

hess1 = res1.model.hessian(res1.params)
hess2 = res2.model.hessian(res1.params)
assert_allclose(hess1, hess2, rtol=1e-10)


class TestGLMGaussNonRobust(CheckDiscreteGLM):
Expand Down
13 changes: 10 additions & 3 deletions statsmodels/genmod/generalized_linear_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ def score_factor(self, params, scale=None):

score_factor = (self.endog - mu) / self.family.link.deriv(mu)
score_factor /= self.family.variance(mu)
score_factor *= self.iweights
score_factor *= self.iweights * self.n_trials

if not scale == 1:
score_factor /= scale
Expand Down Expand Up @@ -578,9 +578,9 @@ def hessian_factor(self, params, scale=None, observed=True):
tmp = self.family.variance(mu) * self.family.link.deriv2(mu)
tmp += self.family.variance.deriv(mu) * self.family.link.deriv(mu)

tmp = score_factor * eim_factor * tmp
tmp = score_factor * tmp
# correct for duplicatee iweights in oim_factor and score_factor
tmp /= self.iweights
tmp /= self.iweights * self.n_trials
oim_factor = eim_factor * (1 + tmp)

if tmp.ndim > 1:
Expand Down Expand Up @@ -1044,6 +1044,10 @@ def _fit_gradient(self, start_params=None, method="newton",
using the scipy gradient optimizers.
"""

# fix scale during optimization, see #4616
scaletype = self.scaletype
self.scaletype = 1.

if (max_start_irls > 0) and (start_params is None):
irls_rslt = self._fit_irls(start_params=start_params,
maxiter=max_start_irls,
Expand All @@ -1056,6 +1060,9 @@ def _fit_gradient(self, start_params=None, method="newton",
maxiter=maxiter, full_output=full_output,
method=method, disp=disp, **kwargs)

# reset scaletype to original
self.scaletype = scaletype

mu = self.predict(rslt.params)
scale = self.estimate_scale(mu)

Expand Down
2 changes: 1 addition & 1 deletion statsmodels/genmod/tests/test_constrained.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def test_se(self):
assert_allclose(res1.scale, res2.scale, rtol=1e-10)
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, atol=1e-15)
self.idx_p_uc], res2.cov_params(), rtol=5e-9, atol=1e-15)

def test_resid(self):
res1 = self.res1
Expand Down
36 changes: 35 additions & 1 deletion statsmodels/genmod/tests/test_glm.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
from statsmodels.tools.sm_exceptions import PerfectSeparationError
from statsmodels.discrete import discrete_model as discrete
from statsmodels.tools.sm_exceptions import DomainWarning
from statsmodels.tools.numdiff import (approx_fprime, approx_fprime_cs,
approx_hess)
import pytest
import warnings

Expand Down Expand Up @@ -987,6 +989,27 @@ def test_summary():
rslt = model.fit(method=method)
s = rslt.summary()


def check_score_hessian(results):
# compare models core and hessian with numerical derivatives

params = results.params
# avoid checking score at MLE, score close to zero
sc = results.model.score(params * 0.98, scale=1)
# cs currently (0.9) does not work for all families
# sc2 = approx_fprime_cs(params * 0.98, results.model.loglike)
llfunc = lambda x: results.model.loglike(x, scale=1)
sc2 = approx_fprime(params * 0.98, llfunc)
assert_allclose(sc, sc2, rtol=0.05)

hess = results.model.hessian(params, scale=1)
hess2 = approx_hess(params, llfunc)
assert_allclose(hess, hess2, rtol=0.05)
scfunc = lambda x: results.model.score(x, scale=1)
hess3 = approx_fprime(params, scfunc)
assert_allclose(hess, hess3, rtol=0.05)


def test_gradient_irls():
# Compare the results when using gradient optimization and IRLS.

Expand Down Expand Up @@ -1045,6 +1068,9 @@ def test_gradient_irls():
elif (family_class, link) == (fam.Gaussian, lnk.inverse_power):
# adding skip because of convergence failure
skip_one = True
# the following fails with identity link, because endog < 0
# elif family_class == fam.Gamma:
# lin_pred = 0.5 * exog.sum(1) + np.random.uniform(size=exog.shape[0])
else:
lin_pred = np.random.uniform(size=exog.shape[0])

Expand All @@ -1055,6 +1081,12 @@ def test_gradient_irls():
mod_irls = sm.GLM(endog, exog, family=family_class(link=link()))
rslt_irls = mod_irls.fit(method="IRLS")

if not (family_class, link) in [(fam.Poisson, lnk.sqrt),
(fam.Gamma, lnk.inverse_power),
(fam.InverseGaussian, lnk.identity)
]:
check_score_hessian(rslt_irls)

# Try with and without starting values.
for max_start_irls, start_params in (0, rslt_irls.params), (3, None):
# TODO: skip convergence failures for now
Expand All @@ -1065,7 +1097,7 @@ def test_gradient_irls():
mod_gradient = sm.GLM(endog, exog, family=family_class(link=link()))
rslt_gradient = mod_gradient.fit(max_start_irls=max_start_irls,
start_params=start_params,
method="newton")
method="newton", maxiter=300)

assert_allclose(rslt_gradient.params,
rslt_irls.params, rtol=1e-6, atol=5e-5)
Expand All @@ -1083,6 +1115,8 @@ def test_gradient_irls():
assert_allclose(gradient_bse, rslt_irls.bse, rtol=1e-6, atol=5e-5)




def test_gradient_irls_eim():
# Compare the results when using eime gradient optimization and IRLS.

Expand Down