Skip to content

ENH: add score_factor, hessian_factor to discrete - #4716

Closed
josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset
Closed

josef-pkt wants to merge 4 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

first step towards #2107

see also #4714 sign convention in hessian_factor

score_factor and hessian_factor are copy/paste/adjust.
Unit tests verify that adjustment is correct, but need to be changed when we DRY out score and hessian by reusing the factor methods. How to recover score_obs and hessian is in the unit tests.

first target application is to make score_test from #2096 available for discrete distributions

@coveralls

coveralls commented Jun 6, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.02%) to 83.603% when pulling fe7733c on josef-pkt:discrete_scorefactor_offset into 4124437 on statsmodels:master.

@codecov-io

codecov-io commented Jun 6, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4716 into master will increase coverage by 0.11%.
The diff coverage is 95.34%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4716      +/-   ##
==========================================
+ Coverage    80.8%   80.92%   +0.11%     
==========================================
  Files         577      577              
  Lines       88571    88815     +244     
  Branches     9186     9902     +716     
==========================================
+ Hits        71571    71873     +302     
+ Misses      14732    14677      -55     
+ Partials     2268     2265       -3
Impacted Files Coverage Δ
statsmodels/genmod/generalized_linear_model.py 90.46% <100%> (+0.87%) ⬆️
statsmodels/base/_parameter_inference.py 64% <100%> (-0.94%) ⬇️
statsmodels/discrete/tests/test_sandwich_cov.py 98.4% <100%> (+0.25%) ⬆️
statsmodels/discrete/tests/test_constrained.py 90.72% <92%> (+0.12%) ⬆️
statsmodels/discrete/tests/test_discrete.py 98.29% <93.1%> (+0.46%) ⬆️
statsmodels/discrete/discrete_model.py 88.33% <94.11%> (+0.39%) ⬆️
statsmodels/sandbox/stats/multicomp.py 40.25% <0%> (ø) ⬆️
statsmodels/sandbox/distributions/mv_normal.py 38.97% <0%> (ø) ⬆️
statsmodels/stats/descriptivestats.py 24.13% <0%> (ø) ⬆️
statsmodels/sandbox/distributions/gof_new.py 0% <0%> (ø) ⬆️
... and 20 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 47315ce...e031a98. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member Author

Binary/Logit has now fit_constrained, it required almost 4 lines :)
It's fun when it works, but newton failed in test case, and I needed to switch to 'bfgs'.
Binary models still need better start_params. (I only added those to the count models.)
Logit fit is completely the default fit.

+    def fit_constrained(self, constraints, start_params=None, **fit_kwds):
+
+        res = fit_constrained_wrap(self, constraints, start_params=None,
+                                   **fit_kwds)
+        return res
+
+    fit_constrained.__doc__ = fit_constrained_wrap.__doc__

@josef-pkt josef-pkt mentioned this pull request Jun 7, 2018
@josef-pkt

josef-pkt commented Jun 7, 2018 •

Copy link
Copy Markdown
Member Author

the last commit attached score_test to GLMResults and DiscreteResults.
e.g. https://gist.github.com/josef-pkt/f20abdbd360c2e549f73e98844f5d2c4

It will not work with all subclasses of DiscreteResults, Only the binary (excluding MNLogit) and basic count models except NegativeBinomial have score_factor. (In Zero-Inflated it will be more difficult to get score_factor and hessian_factor arrays.)

The comparison GLM-discrete tests in discrete test_sandwich_cov include Poisson, Logit and Probit. I'm currently skipping OLS which has a different compare_lm_test and doesn't have fit_constrained for other than variable addition score/LM tests.

We need to test the extra params cases, NBP and GPP where I added score and hessian factors.

res2 = self.res2

if isinstance(res2.model, OLS):
# skip

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.

pls use raise pytest.skip... here.

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.

(and in analogous places throughout)



def check_jac(self):
# moved from CheckModelResults

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.

why moved? The only arg to this is self, seems like it should definitely be a method.

# moved from CheckModelResults
res1 = self.res1
exog = self.res1.model.exog
#basic cross check

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.

space after # pls. Also below for #Poisson.

h2 = np.vstack((np.column_stack((h00, h10.T)),
np.column_stack((h10, h11))))

assert_allclose(h2, h1, rtol=1e-10)

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.

Would this make sense as three separate methods? Something like check_scoreobs_sum, check_score_factor_equiv, check_hessian_factor_equiv?

rtol=0.01)

def test_jac(self):
self.res1 = self.res

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.

is res1 set anywhere else? Editing self here makes me nervous.



# this is a copy from stats._diagnostic_other
# this is a copy from stats._diagnostic_other to avoid circular imports

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.

+1 for clarity

from statsmodels.regression.linear_model import OLS
from statsmodels.genmod.generalized_linear_model import GLM
from statsmodels.genmod import families
import statsmodels.stats._diagnostic_other as diao

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.

+1 for removing unnecessary imports

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.

Thoughts on a separate PR just doing this?

not np.all((self.endog >= 0) & (self.endog <= 1))):
raise ValueError("endog must be in the unit interval.")
if offset is None:
delattr(self, 'offset')

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.

I know this is done elsewhere so it's not the absolute worst, but is there a compelling reason not to just leave self.offset = None? The only difference AFAICT would be that below instead of hasattr(self, 'offset') the check would be self.offset is not None.

exog = self.exog
dF = self.pdf(np.dot(exog, params))[:,None] * exog
linpred = self.predict(params, exog, offset=offset, linear=True)
dF = self.pdf(linpred)[:,None] * exog

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.

space after comma please (and below). Using self.predict here is nice.


def _derivative_exog(self, params, exog=None, transform='dydx',
dummy_idx=None, count_idx=None):
dummy_idx=None, count_idx=None, offset=None):

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.

+1 for fixing this. discrete_model is in dire need of these small fixups

margeff = np.dot(self.pdf(np.dot(exog, params))[:,None],
linpred = self.predict(params, exog, offset=offset, linear=True)
margeff = np.dot(self.pdf(linpred)[:,None],
params[None,:])

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.

Looks like some whitespace needs to be trimmed here

params = params[:-1]
p = self.parameterization
exog = self.exog
y = self.endog[:,None]

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.

space after comma

a1 = 1 + alpha * mu_p
a2 = mu + alpha * mu_p * y
a3 = alpha * p * mu ** (p - 1)
a4 = a3 * y

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.

are there any more meaningful names that can be given to a1, a2, a3, a4? Do they correspond to moments or something?

dparams = dmudb * (-a4 / a1 +
a3 * a2 / (a1 ** 2) +
(1 + a4) * ((y - 1) / a2 - 1 / a1) +
1 / mu)

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.

Take the two terms -a4 / a1 and (1 + a4) * ((y - 1) / a2 - 1 / a1):

(- a4 / a1
 + (1 + a4) * ((y - 1) / a2 - 1 / a1))

= (1 / a1
   - 1 / a1
   - a4 / a1
   + (1 + a4) * ((y - 1) / a2 - 1 / a1))

= (1 / a1
   - (1 + a4) / a1
   + (1 + a4) * ((y - 1) / a2 - 1 / a1))

= (1 / a1
   + (1 + a4) * ((y - 1) / a2 - 2 / a1))

The term multiplying (1+a4) here also shows up in dalpha

params = params[:-1]
p = self.parameterization
exog = self.exog
y = self.endog #[:,None]

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.

pls delete commented-out

nobs, k_vars = exog.shape
hess_fact = np.empty((nobs, 3))


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.

extra line

(y - 1) * a4 * (p - 1) / (a2 * mu) -
(y - 1) * (1 + a4)**2 / a2**2 -
a4 * (p - 1) / (a1 * mu) -
1 / mu**2) +

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.

The last -1/mu**2 term here cancels out with the +1/mu term on 1781. Ditto the a4 / (mu*a1) on 1771 with a4/a1 on 1777. ... and 1772 with 1778... Seriously, please let me help with this stuff. #4515.

mu_p * (1 + a4) / a1**2 +
a5 * y * (y - 1) / a2 -
2 * a5 * y / a1 +
a5 * a2 / a1**2) * dmudb)

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.

I think the outer parens is unnecessary. Can you pls align the indentation?

A reference to the exogenous design.
""" % {'params' : base._model_params_doc,
'extra_params' : base._missing_param_doc}
'extra_params' :

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.

convention is no space before colon in dictionaries

return np.sum(np.log(np.clip(self.cdf(q*np.dot(X,params)),
FLOAT_EPS, 1)))
linpred = self.predict(params, linear=True)
return np.sum(np.log(np.clip(self.cdf(q * linpred), FLOAT_EPS, 1)))

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.

splitting this into multiple lines might be more readable

X = self.exog
return np.log(np.clip(self.cdf(q*np.dot(X,params)), FLOAT_EPS, 1))
linpred = self.predict(params, linear=True)
return np.log(np.clip(self.cdf(q*linpred), FLOAT_EPS, 1))

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.

whitespace around operator pls

@jbrockmendel

Copy link
Copy Markdown
Contributor

Generally looks quite nice; I expect it'll improve performance for score and hessian calls. Let me know when ready for another pass.

@josef-pkt

Copy link
Copy Markdown
Member Author

rebased, the only merge conflict is because GLM score_test and get_hat_matrix_diag/get_influence are next to each other.

@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 8 alerts and fixes 5 when merging 4ad8e7f into 5139e47 - view on LGTM.com

new alerts:

  • 8 for Unused local variable

fixed alerts:

  • 5 for Unused import

Comment posted by LGTM.com

@josef-pkt
josef-pkt force-pushed the discrete_scorefactor_offset branch from 4ad8e7f to fe7733c Compare June 30, 2018 13:55
@josef-pkt

Copy link
Copy Markdown
Member Author

This pull request introduces 8 alerts and fixes 5 when merging fe7733c into 4124437 - view on LGTM.com

new alerts:

  • 8 for Unused local variable

fixed alerts:

  • 5 for Unused import

Comment posted by LGTM.com

@josef-pkt

Copy link
Copy Markdown
Member Author

I don't know what happened, two out of three python 2.7 fail or just stop

statsmodels/base/tests/test_data.py .................................... [  0%]
........................................................................ [  1%]
                                                                         [  1%]
statsmodels/base/tests/test_distributed_estimation.py ..............     [  1%]
statsmodels/base/tests/test_generic_methods.py ...........s........s.... [  2%]
.s.....s.....s...........s.....s.......ss....ss....ss................... [  3%]
.                                                                        [  3%]
statsmodels/base/tests/test_optimize.py 
The command "pytest ${COVERAGE_OPTS} statsmodels --skip-examples" exited with 2.
Done. Your build exited with 1.

@jbrockmendel

Copy link
Copy Markdown
Contributor

Close in favor of #5711?

@josef-pkt josef-pkt modified the milestones: 0.10, 0.14 Oct 31, 2021
@josef-pkt

Copy link
Copy Markdown
Member Author

merged in #7825

@josef-pkt josef-pkt closed this Oct 31, 2021
@josef-pkt josef-pkt added the superseded Used for PRs with content that is superseded by a newer PR label Oct 31, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-discrete superseded Used for PRs with content that is superseded by a newer PR type-enh

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants