Skip to content

Discrete scorefactor offset rebased3 - #7825

Merged
josef-pkt merged 6 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset_rebased3
Oct 31, 2021
Merged

josef-pkt merged 6 commits into
statsmodels:mainfrom
josef-pkt:discrete_scorefactor_offset_rebased3

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Oct 28, 2021 •

Copy link
Copy Markdown
Member

rebased version of #5711
no code removed (like NB, GPP score factor in first commit)
Logit score_factor is already in main

possible problems
sign of hessian factor, not sure how GLM and discrete really compare
docstrings need review, Resolving merge conflicts might not have left good docstrings.
duplicate shortcut name for base._parameter_inference inferandpinf`

included in PR:

  • offset in BinaryModel
    • possible problem in MNLogit, not supported
    • possible problem new code added to main after changes in this PR, needs checking
  • fit_constrained in BinaryModel
  • score_test in GLMResults
  • score_test in Discretresults
    • will likely not work in several models needs checking maybe inherited too high in class hierarchy
  • score_factor, hessian_factor in Probit
  • score_factor, hessian_factor in GeneralizedPoisson and NBP, needs decision what to do with it

fit_constrained.__doc__ = fit_constrained_wrap.__doc__

def _derivative_predict(self, params, exog=None, transform='dydx',
offset=None):

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.

offset before transform ?


return res

get_prediction.__doc__ = pred.get_prediction_glm.__doc__

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.

this has been replaced by appender
delete

@josef-pkt

josef-pkt commented Oct 28, 2021 •

Copy link
Copy Markdown
Member Author

test failures in statsmodels.stats.tests.test_influence.TestInfluenceLogitCompare and related Poisson
has nans
(I didn't run those tests locally)

I guess hessian_factor has the wrong sign for this function.
MLEInfluence.resid_studentized computes sqrt(hessian_factor)

maybe GLM started the wrong sign convention for hessian_factor
GLM uses -tmp.T.dot(self.exog) in Hessian, i.e. reverses the sign of hessian_factor
I guess we need to clean this up in GLM to have consistency across models and a proper definition as second derivative.
We will need the general version of the derivatives for multilink models in dfamilies.

a few pep-8

@lgtm-com

lgtm-com Bot commented Oct 28, 2021

Copy link
Copy Markdown

This pull request introduces 9 alerts when merging 9cd2202 into 088a792 - view on LGTM.com

new alerts:

  • 8 for Unused local variable
  • 1 for Module is imported more than once

@lgtm-com

lgtm-com Bot commented Oct 29, 2021

Copy link
Copy Markdown

This pull request introduces 8 alerts when merging 4a6526d into 088a792 - view on LGTM.com

new alerts:

  • 8 for Unused local variable

@josef-pkt
josef-pkt force-pushed the discrete_scorefactor_offset_rebased3 branch from 4a6526d to d5ad98e Compare October 29, 2021 15:15
@josef-pkt

Copy link
Copy Markdown
Member Author

test_sandwich_cov.TestGLMPoisson fails on some runs, just a bit worse than rtol.
missing seed for np.random

@josef-pkt

Copy link
Copy Markdown
Member Author

Poisson.fit_constrained has much more code than the new BinaryModel.fit_constrained
the new method uses fit_constrained_wrap

Can the Poisson method also use more of the generic code?

No unit tests for Probit fit_constrained. (all inherited)
Also, check what error MNLogit raises if inherited fit_constrained is called.

generic fit constrained is not yet supported for models with extra params as in NB and GPP

@lgtm-com

lgtm-com Bot commented Oct 29, 2021

Copy link
Copy Markdown

This pull request introduces 8 alerts when merging d5ad98e into 088a792 - view on LGTM.com

new alerts:

  • 8 for Unused local variable

@josef-pkt

josef-pkt commented Oct 29, 2021 •

Copy link
Copy Markdown
Member Author

monte carlo results in old pr #5711 (comment)
I haven't found the notebook yet

I will need to verify implementation by MonteCarlo. Not much of robust score_tests is in other packages.
GEE might have something close for cluster robust.

update
rerunning the old notebook, which had now nobs=100, n_rep = 10000 (takes some time to run)

cases are mean_misspecified, dispersed, cov_type

for mean_misspecified in [True, False]:
    for dispersed in [True, False]:
        for cov_type in cov_types:
                           0.001   0.010   0.050   0.100   0.200   0.300   0.500   0.900
(True, True, nonrobust)    0.1066  0.2694  0.4724  0.5799  0.7038  0.7820  0.8774  0.9848
(True, True, HC0)          0.0221  0.1119  0.2898  0.4195  0.5837  0.6950  0.8459  0.9819
(True, False, nonrobust)   0.1463  0.3822  0.6274  0.7380  0.8440  0.8954  0.9516  0.9952
(True, False, HC0)         0.1082  0.3358  0.6024  0.7309  0.8437  0.9032  0.9601  0.9967

(False, True, nonrobust)   0.6559  0.7493  0.8295  0.8625  0.9038  0.9276  0.9573  0.9931
(False, True, HC0)         0.0088  0.0345  0.1024  0.1871  0.3559  0.5161  0.7488  0.9672
(False, False, nonrobust)  0.0009  0.0107  0.0534  0.1029  0.1988  0.3064  0.5070  0.9010
(False, False, HC0)        0.0008  0.0079  0.0448  0.0947  0.2277  0.3733  0.6193  0.9432

second block is null of correctly specified mean function.
In overdispersed case nonrobust score test heavily overrejects. HC0 overrejects a bit (but still double the size at 0.05)
HC0 looks worse than in the previous PR comment.
Refactoring and merge conflict bugs are not ruled out yet.

However previous PR comment had larger sample size at nobs=1000 (with 1000 replication)
Worse performance here of HC0 could be small sample effect.

The score_test in the MC is a reset test for GLM-Poisson:

                res = GLM(y, x, family=families.Poisson()).fit(cov_type=cov_type)
                fitted = res.fittedvalues
                exog_extra = np.column_stack((fitted**2, fitted**3))
                results_mc.append(res.score_test(exog_extra, cov_type=cov_type)[:2])

update 2

running nobs=1000 and nrepl=1000 as in the previous pr comment
Results are similar to before
HC0 is a bit below size at no dispersion, and a little bit above size with dispersion

                           0.001  0.010  0.050  0.100  0.200  0.300  0.500  0.900
(True, True, nonrobust)    0.998  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, True, HC0)          0.968  0.997  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, nonrobust)   1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, HC0)         1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000

(False, True, nonrobust)   0.846  0.895  0.931  0.945  0.963  0.971  0.985  0.997
(False, True, HC0)         0.002  0.013  0.056  0.118  0.259  0.399  0.689  0.966
(False, False, nonrobust)  0.000  0.013  0.057  0.099  0.205  0.301  0.519  0.913
(False, False, HC0)        0.000  0.004  0.033  0.074  0.192  0.304  0.593  0.947

update 3

running the same nobs=1000 and nrepl=1000
but with discrete Poisson instead of GLM-Poisson

HC rejects a bit more often with Poisson than with GLM-Poisson.
overrejects a bit with dispersion, e.g. 0.073 instead of size 0.05, and 0.056 in GLM
otherwise similar in both models

possible difference: default optimizer is irls and eim in GLM, and newton and oim in Poisson
However, with the canonical link eim should the same as oim.
???

                           0.001  0.010  0.050  0.100  0.200  0.300  0.500  0.900
(True, True, nonrobust)    0.997  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, True, HC0)          0.971  0.996  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, nonrobust)   1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000
(True, False, HC0)         1.000  1.000  1.000  1.000  1.000  1.000  1.000  1.000

(False, True, nonrobust)   0.695  0.774  0.847  0.887  0.923  0.944  0.966  0.996
(False, True, HC0)         0.002  0.010  0.073  0.145  0.280  0.401  0.614  0.949
(False, False, nonrobust)  0.003  0.016  0.054  0.105  0.203  0.311  0.499  0.892
(False, False, HC0)        0.002  0.011  0.056  0.108  0.218  0.325  0.537  0.901

Overall results look closely what we would expect based on the theory.

@josef-pkt

josef-pkt commented Oct 29, 2021 •

Copy link
Copy Markdown
Member Author

sign of hessian factor still needs more review
The last comment in the previous PR was also about that
#5711 (comment)

update The code in score_test/_lm_robust that the old comment refers to, had already been fixed.
GLM is special case to change the sign of hessian_factor. MLE models shold have correct negative sign of hessian_factor

@josef-pkt

josef-pkt commented Oct 29, 2021 •

Copy link
Copy Markdown
Member Author

score_test for models with extra params, e.g. NBP

using exog_extra directly raises shape error because score_factor is 2d (2 components
However, testing restricted parameters in the full model works

nobs=500, DGP in notebook uses normal random effect to introduce overdispersion.
i.e. NB is not the null distribution, but mean is correctly specified (ignoring random effect)

The wald and score test versions of the reset test are very close to each other,
Both are computed with nonrobust cov_type.

res = NegativeBinomialP(y, x).fit(cov_type="nonrobust", disp=0)
fitted = res.fittedvalues
exog_expanded = np.column_stack((x, fitted**2, fitted**3))
mod_reset = NegativeBinomialP(y, exog_expanded)
res_reset = mod_reset.fit()
​
params_constrained = np.concatenate((res.params[:-1], [0, 0], res.params[-1:]))
st = res_reset.score_test(params_constrained=params_constrained, k_constraints=2, cov_type="nonrobust")
print(st)
​
wt = res_reset.wald_test("x5, x6")
print(wt)

(array([0.41471153]), array([0.81273046]), 2)
<Wald test (chi2): statistic=[[0.41349083]], p-value=0.8132266600298893, df_denom=2>

with nobs = 50:

(array([10.46623618]), array([0.00533686]), 2)
<Wald test (chi2): statistic=[[7.39262852]], p-value=0.024814819116842406, df_denom=2>

with nobs=5000

(array([2.51580992]), array([0.28424892]), 2)
<Wald test (chi2): statistic=[[2.51473342]], p-value=0.2844019538093365, df_denom=2>

The same works for GeneralizedPoisson with similar results

update
confirm with Poisson, that the two ways of using score_test produce the same result

All tests use nonrobust, even though there is overdispersion in the dgp.
They reject the null of the reset test. (see below without overdispersion


res = Poisson(y, x).fit(cov_type="nonrobust", disp=0)
fitted = res.fittedvalues
exog_expanded = np.column_stack((x, fitted**2, fitted**3))
mod_reset = Poisson(y, exog_expanded)
res_reset = mod_reset.fit(disp=0)
​
exog_extra = np.column_stack((fitted**2, fitted**3))
st_ex = res.score_test(exog_extra)
print("st_ex", st_ex)
​
params_constrained = np.concatenate((res.params, [0, 0]))
st_param = res_reset.score_test(params_constrained=params_constrained, k_constraints=2, cov_type="nonrobust")
print("st_param", st_param)
​
wt = res_reset.wald_test("x5, x6")
print(wt)

st_ex (array([32.53448598]), array([8.61442183e-08]), 2)
st_param (array([32.53448598]), array([8.61442183e-08]), 2)
<Wald test (chi2): statistic=[[32.52839596]], p-value=8.640692783883246e-08, df_denom=2>

DGP without overdispersion, i.e. without normal random effect
nonrobust tests don't reject the reset null

st_ex (array([2.85267444]), array([0.24018707]), 2)
st_param (array([2.85267444]), array([0.24018707]), 2)
<Wald test (chi2): statistic=[[2.85662702]], p-value=0.23971285496603237, df_denom=2>

@josef-pkt

Copy link
Copy Markdown
Member Author

score_test has a hypothesis='separate' but I'm not sure how this compares to the wald test
nobs=500, so parameter estimates should be close to true.

score test pvalues are at around 0.9
wald test pvalues are between 0.4 and 0.5
If I add each exog_extra separately to the model and do wald test, the the pvalues are 0.64 and 0.86, much higher than joint wald test.
The correlation between the two exog_extra (of reset test) is 0.82195873

st_ex = res.score_test(exog_extra, hypothesis='separate')
print("st_ex", st_ex)
​
st_param = res_reset.score_test(params_constrained=params_constrained, k_constraints=2, 
                                cov_type="nonrobust", hypothesis='separate')
print("st_param", st_param)
​
wt = res_reset.t_test("x5, x6")
print(wt)
​
st_ex (array([-5.21711529e-16,  1.27823763e-15,  4.13628731e-16, -2.10889713e-15,
        5.11106146e-16, -1.42808589e-01, -7.60306733e-02]), array([1.        , 1.        , 1.        , 1.        , 1.        ,
       0.88644135, 0.9393947 ]))
st_param (array([ 3.05392114e-16,  8.23965727e-16,  4.59587479e-16, -2.69192556e-15,
        5.28445773e-16, -1.42808589e-01, -7.60306733e-02]), array([1.        , 1.        , 1.        , 1.        , 1.        ,
       0.88644135, 0.9393947 ]))
                             Test for Constraints                             
==============================================================================
                 coef    std err          z      P>|z|      [0.025      0.975]
------------------------------------------------------------------------------
c0            -0.0596      0.073     -0.822      0.411      -0.202       0.083
c1             0.0132      0.019      0.712      0.477      -0.023       0.050
==============================================================================

trying some more:
It looks like score_test with "separate" produces the same results as running two score_test with each separately.

Maybe that was the idea to add that in the first place.
I thought we would get robustness to violation of the "other" hypothesis. (story for LM anc CM tests by ....)

st_ex0 = res.score_test(exog_extra[:,0], hypothesis='separate')
print("st_ex0", st_ex0)  #0.88644135
st_ex0 (array([-5.21711529e-16,  1.27823763e-15,  4.13628731e-16, -2.10889713e-15,
        5.11106146e-16, -1.42808589e-01]), array([1.        , 1.        , 1.        , 1.        , 1.        ,
       0.88644135]))

st_ex1 = res.score_test(exog_extra[:, 1], hypothesis='separate')
print("st_ex1", st_ex1)  #0.88644135
st_ex1 (array([-5.21711529e-16,  1.27823763e-15,  4.13628731e-16, -2.10889713e-15,
        5.11106146e-16, -7.60306733e-02]), array([1.       , 1.       , 1.       , 1.       , 1.       , 0.9393947]))

st_ex = res.score_test(exog_extra, hypothesis='separate')
print("st_ex", st_ex)
st_ex (array([-5.21711529e-16,  1.27823763e-15,  4.13628731e-16, -2.10889713e-15,
        5.11106146e-16, -1.42808589e-01, -7.60306733e-02]), array([1.        , 1.        , 1.        , 1.        , 1.        ,
       0.88644135, 0.9393947 ]))

I just don't remember the details here. I went through this before. links? references?

@josef-pkt

Copy link
Copy Markdown
Member Author

base._parameter_inference._lm_robust is originally a copied version of the stats._diagnostic_other function
Difference is that the base version added p-value computation with k_constraints using rank(R). 3 returns

other versions in _diagnostic_other:
lm_robust_subset, lm_robust_subset_parts and lm_robust_reparameterized return statistic and p_value, but no df
cm_test_robust return statistic, p_value and a second statistic
lm_test_glm returns a function specific Holder instance with 3 statistics and associated p-values

CMTNewey.chisquare and CMTTauchen.chisquare return 3: stat, pval, df

CMTNewey and CMTTauchen also have ztest method which should be the vectorized version analogous to score_test hypothesis="separate"

@josef-pkt

Copy link
Copy Markdown
Member Author

In my notebook, the fittedvalues for reset test is wrong and inconsistent.
I should use linpred.

GLM fittedvalues is mu
Poisson fittedvalues is still linpred.
So, switching from GLM to Poisson changed the definition of exog_extra

@josef-pkt

Copy link
Copy Markdown
Member Author

Most likely wrong: GLM score_test with freq_weights, and only maybe correct with var_weights

with freq_weights:
correction I didn't remember this correctly score_factor and hessian_factor include iweight = freq_weights * var_weights
Observation specific methods do not include with freq_weights. Those are added in the aggregation functions, loglike, score, ...
To fix score_test, we would need to add freq_weights
in the aggregation which happens in base._parameter_inference.score_test, e.g. score = score_obs.sum(0)
_lm_robust only takes matrices which are already aggregated.

Related usage question: If we use freq_weights for IPW, what should be the result?

var_weights should be correctly included in the observation specific

@josef-pkt

josef-pkt commented Oct 30, 2021 •

Copy link
Copy Markdown
Member Author

Nice

GLM-Binomial two sample case compared with specific hypothesis test
Data based on unit test case of proportions_2indep, expanded to binary endog sample
score test in constant-only model with group indicator as exog_extra

diff in p-value is 1.6e-11

tp2 = test_proportions_2indep(count1, nobs1, count2, nobs2,
                                    compare='odds-ratio',
                                    method='score', correction=False, return_results=True)
tp2
<class 'statsmodels.stats.base.HolderTuple'>
statistic = 2.258317958127243
pvalue = 0.023925843480626655
compare = 'odds-ratio'
method = 'score'
variance = 0.5666666666666667
alternative = 'two-sided'
prop1_null = 0.11764705882352941
prop2_null = 0.11764705882352941
tuple = (2.258317958127243, 0.023925843480626655)
diff = 0.1764705882352941
ratio = 7.0
odds_ratio = 8.555555555555555
value = 1

# constant only regression
res = GLM(counts, ex_const, family=families.Binomial()).fit()
st = res.score_test(exog_extra=groups)
st
(array([5.1]), array([0.02392584]), 1)

tp2.pvalue - st[1]
array([-1.63428507e-11])

In binary case we cannot have excess dispersion, so HC0 cannot help
however, the score_test results using HC0 differ by a bit

res.score_test(exog_extra=groups, cov_type="HC0")
(5.43243243243238, 0.019766128705111012, 1)

I'm not sure what this means, maybe some heteroscedasticity across groups
e.g. in constant-only GLM

res.resid_pearson[groups == 0].mean()
-0.2738612788186532
res.resid_pearson[groups == 1].mean()
0.27386127862288995

aside scale according to pearson chi2 is not 1 because of df correction

res.pearson_chi2 / res.df_resid, res.pearson_chi2 / nobs
(1.0149253731343286, 1.0000000000000002)

correction
Binary models cannot have dispersion for correctly specified mean function.
However, in the above case the mean in the constant-only Model is misspecified. The mean differs by groups, and consequently the variance differs by groups.
An HC0 test only uses the information on the means directly and compensates for the implied heteroscedasticity.

@josef-pkt

Copy link
Copy Markdown
Member Author

agreement is even better with Poisson:

same as binomial example only with family Poisson, endog is still zeros and ones.

exposure1, exposure2 = 1, 1
tr = test_poisson_2indep(count1, exposure1, count2, exposure2, ratio_null=1,
                        method='score', alternative='two-sided',
                        etest_kwds=None)

tr.pvalue - st[1]
array([-2.77555756e-17])

difference of HC0 is larger here. case is under dispersed according to pearson chi2

st = res.score_test(exog_extra=groups)
st
(array([4.5]), array([0.03389485]), 1)

st = res.score_test(exog_extra=groups, cov_type="HC0")
st
(5.432432432432467, 0.019766128705110037, 1)

res.pearson_chi2 / res.df_resid
0.8955223880597013

@josef-pkt

josef-pkt commented Oct 30, 2021 •

Copy link
Copy Markdown
Member Author

It doesn't match up closely between GLM gaussian score_test and OLS compare_lm_test

still the same 2-sample case

# GLM-Gaussian
st = res.score_test(exog_extra=groups)
st
(array([5.025]), array([0.02498393]), 1)

# OLS
res_full.compare_lm_test(res, demean=False), res_full.compare_lm_test(res, demean=True)
((5.100000000000001, 0.023925843480626655, 1.0),
 (5.100000000000001, 0.023925843480626655, 1.0))

AFAICS RegressionResults.compare_lm_test uses the scale of the full, unrestricted model restricted model, and that without df correction, only in nonrobust.
Also, all HC, ('HC0', 'HC1', 'HC2', 'HC3') map to HC0
but HAC and cluster cov_types are also available

update AFAICS now, the only difference in nonrobust lm/scoretest is the df-correction in the scale estimate
GLM uses df_resid (67 in restricted constant only model)
OLS uses nobs (68)

67 / 68 * 5.1 = 5.025
(the test statistics divides by scale, scale correction to add df is * 68 / 67)

@josef-pkt

Copy link
Copy Markdown
Member Author

looks good enough and works well, merge when green

@lgtm-com

lgtm-com Bot commented Oct 31, 2021

Copy link
Copy Markdown

This pull request introduces 1 alert and fixes 3 when merging 37763f2 into 59c41e8 - view on LGTM.com

new alerts:

  • 1 for Unused local variable

fixed alerts:

  • 2 for Unused local variable
  • 1 for Module is imported more than once

@josef-pkt
josef-pkt force-pushed the discrete_scorefactor_offset_rebased3 branch from 37763f2 to 3e272b4 Compare October 31, 2021 18:52
@lgtm-com

lgtm-com Bot commented Oct 31, 2021

Copy link
Copy Markdown

This pull request fixes 7 alerts when merging 3e272b4 into 59c41e8 - view on LGTM.com

fixed alerts:

  • 4 for Module is imported more than once
  • 3 for Unused local variable

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant