Skip to content

ENH: diagnostic, post-estimation for binary, multinomial and ordinal models - #7094

Merged
josef-pkt merged 4 commits into
statsmodels:masterfrom
josef-pkt:diagnostic_ordinal
Nov 19, 2020
Merged

josef-pkt merged 4 commits into
statsmodels:masterfrom
josef-pkt:diagnostic_ordinal

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Oct 11, 2020 •

Copy link
Copy Markdown
Member

getting started with more diagnostics and postestimation

Hosmer-Lemeshow gof test,
multinomial support stats functions
stochastic larger P(x < y) + 0.5 P(x=y) helper functions

#7069 extension to ordered model
#1190 diagnostic after discrete, GLM
...

@pep8speaks

pep8speaks commented Oct 11, 2020 •

Copy link
Copy Markdown

Hello @josef-pkt! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2020-11-18 22:12:48 UTC

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.004%) to 88.397% when pulling e90f5fe on josef-pkt:diagnostic_ordinal into 52b142c on statsmodels:master.

@coveralls

coveralls commented Oct 11, 2020 •

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.01%) to 88.383% when pulling d8d6474 on josef-pkt:diagnostic_ordinal into 52b142c on statsmodels:master.

@josef-pkt

josef-pkt commented Oct 12, 2020 •

Copy link
Copy Markdown
Member Author

HL after MNLogit

close to but small differences to Stata mlogitgof
mlogitgof doesn't pick equal groupsizes range between 38 and 42
results are sensitive to sort_var and sort algorithm in case of ties (180 ties with 400 nobs)

""" from Stata mlogitgof
r(P) =  .0149121502729347
r(df) =  16
r(chi2) =  30.64936321793125
r(g) =  10
r(N) =  400
"""
​
​
fitted_mnl = res1_mnl.predict()
dia.test_chisquare_binning(y_dummy, fitted_mnl, sort_var=fitted_mnl[:,0], bins=10,
                           df=None, ordered=False, sort_method="quicksort")
<class 'statsmodels.stats.base.HolderTuple'>
statistic = 30.567085273820428
pvalue = 0.015274390374513567
df = 16

something strange, if I negate the sort_var, then chi2 statistic changes, when using quicksort

dia.test_chisquare_binning(y_dummy, fitted_mnl, sort_var=1 - fitted_mnl[:,0], bins=10,
                           df=None, ordered=False, sort_method="quicksort")
<class 'statsmodels.stats.base.HolderTuple'>
statistic = 24.857779368229803
pvalue = 0.07237221427411188
df = 16

​using stable sort:

sort_var is complement of prob of 1st/reference category

dia.test_chisquare_binning(y_dummy, fitted_mnl, sort_var=1 - fitted_mnl[:,0], bins=10,
                           df=None, ordered=False, sort_method="stable")
<class 'statsmodels.stats.base.HolderTuple'>
statistic = 30.023473896192286
pvalue = 0.017880857795921915
df = 16

sort_var is prob of 1st/reference category

dia.test_chisquare_binning(y_dummy, fitted_mnl, sort_var=fitted_mnl[:,0], bins=10,
                           df=None, ordered=False, sort_method="stable")
<class 'statsmodels.stats.base.HolderTuple'>
statistic = 28.829686228588606
pvalue = 0.025110144743416517
df = 16

@josef-pkt

Copy link
Copy Markdown
Member Author

nice, one line to add estimate of noncentrality parameter and confint to hosmer-lemeshow
from statsmodels.stats.effect_size import _noncentrality_chisquare
noncentrality = _noncentrality_chisquare(stat_chi2, df, alpha=alpha_nc)

<class 'statsmodels.stats.base.HolderTuple'>
statistic = 30.023473896192286
pvalue = 0.017880857795921915
df = 16
freqs = array([[32,  6,  2],
...
noncentrality = <class 'statsmodels.tools.testing.Holder'>
    nc = 14.023473896192286
    confint = array([ 0.6613193, 37.725559 ])
    nc_umvue = 14.023473896192286
    nc_lzd = 14.023473896192286
    nc_krs = 14.023473896192286
    nc_median = 14.909279081896145
    name = 'Noncentrality for chisquare-distributed random variable'

@josef-pkt

Copy link
Copy Markdown
Member Author

internal names freqs, probs are partially misnomer, because now I'm working with counts not probabilities, relative frequencies.
The misleading names just got me confused for a while.

chi2_stat is linear in nobs, i.e. nobs times the probability version.

what's the interpreation chisquare statistic computed for an individual groups? I'm not clear right now what the normalization should be.

I would like to have a partial decomposition of the overall chisquare by groups.
This is essentially a one way stratified multinomial sample (with unequal probabilities).
The overall chisquare test is that all groups follow the specified/predicted probabilities. But I want to know if individual groups look like they might be failing the corresponding tests.
i.e. a diagnostic measure like a groupwise pearson residual but for groups.
This is more general for any type of binning based gof tests. (e.g. in count models and generic article by (maybe) Andrews.

One possibility is to use a normalized noncentrality parameter, i.e. nc / nobs.
My current effect size function does not normalize.

TBC

@josef-pkt

Copy link
Copy Markdown
Member Author

ok, It looks like my confusion was because I didn't distinguish limiting behavior under null or under an alternative

under null

  • distribution is chi2 with df, which has mean = df, independent of nobs, pvalue is uniform distributed under asymptotic distribution and independent of nobs if large sample approximation works.
  • estimate of nc = chi2_stat - df has mean 0 (unbiased, but negative are invalid nc)
  • (nc - df) / nobs -> 0, true effect size is zero

under alternative

  • chi2_stat -> inf as nobs increases
  • distribution is nc-chi2 with fixed df but nc that is linear in nobs
  • normalized nc: nc / nobs and (nc - df) / nobsconverge to a constant > 0
    we use that for effect size definition

also chisquare rvs are additive
"If X_1 ~ chi2(k_1) and X_2 ~ chi2(k_2) are statistically independent, then X_1 + X_2 ~ chi2(k_1+k_2)"
https://en.wikipedia.org/wiki/Chi-square_distribution#Related_distributions

@josef-pkt

Copy link
Copy Markdown
Member Author

CI in _noncentrality_chisquare is not properly vectorized, but works with column vector of chi2_stats

from statsmodels.stats.effect_size import _noncentrality_chisquare
​
ncg = _noncentrality_chisquare(dt.chi2_stat_groups[:, None], dt.df / len(dt.freqs), alpha=0.05)
ncg
<class 'statsmodels.tools.testing.Holder'>
nc = array([[0.05408931],
           [1.15376906],
           [0.24722703],
           [0.        ],
           [4.47418417],
           [0.        ],
           [0.        ],
           [0.        ],
           [4.07009553],
           [0.        ]])
confint = array([[1.00000000e-100, 9.56431812e+000],
           [1.00000000e-100, 1.22049752e+001],
           [1.00000000e-100, 1.00623499e+001],
           [1.00000000e-100, 7.22820379e+000],
           [1.00000000e-100, 1.87696929e+001],
           [1.00000000e-100, 1.47310702e+000],
           [1.00000000e-100, 7.31720399e+000],
           [1.00000000e-100, 5.19477330e+000],
           [1.00000000e-100, 1.80322139e+001],
           [1.00000000e-100, 8.22083251e+000]])
nc_umvue = array([[ 0.05408931],
           [ 1.15376906],
           [ 0.24722703],
           [-0.73749682],
           [ 4.47418417],
           [-1.55427291],
...

@josef-pkt

Copy link
Copy Markdown
Member Author

playing a bit with multinomial model

resid_response_mnl = y_dummy - fitted_mnl
resid_p = (resid_response_mnl**2 / fitted_mnl).sum(1)

good for plot and finding "outliers"
e.g. worst misclassified cases (slighly reformatted)

ii = np.argsort(resid_p)[:-6:-1]
resid_response_mnl[ii], y_dummy[ii], fitted_mnl[ii]

(
array([[-0.65650865, -0.29573539,  0.95224404],
       [-0.64001481, -0.30699934,  0.94701416],
       [-0.63761988, -0.30860792,  0.9462278 ],
       [-0.63159114, -0.31262646,  0.9442176 ],
       [-0.62182409, -0.31904246,  0.94086655]]), 

array([[0, 0, 1],
       [0, 0, 1],
       [0, 0, 1],
       [0, 0, 1],
       [0, 0, 1]]), 

array([[0.65650865, 0.29573539, 0.04775596],
       [0.64001481, 0.30699934, 0.05298584],
       [0.63761988, 0.30860792, 0.0537722 ],
       [0.63159114, 0.31262646, 0.0557824 ],
       [0.62182409, 0.31904246, 0.05913345]]))

not clear to me yet:
Can I get a cov based statistic, e.g. something like resid_response_i @ inv(cov_prob) @ resid_response_i?
where cov_prob is the covariance for one multinomial sample (with n=1)

Analogy is Mahalanobis distance in multivariate model/sample, e.g. issues or PRs (?) on outlier detection in mv-samples and robust cov estimation.
There I also used prob plots for Maha distance compared to chi2 or beta.

Problem also here is that a single observation (one multinomial choice, n=1) doesn't justify asymptotic chisquare distribution.
Maybe, maybe not use exact distribution ?

(I haven't done any literature search for diagnostic residuals for multinomial.)

@josef-pkt

josef-pkt commented Oct 15, 2020 •

Copy link
Copy Markdown
Member Author

R code, assuming csv file is in working directory

library(MASS) # to perform ordinal regression


setwd("...")
ologit_ucla <- read.csv(file='ologit_ucla.csv')
ologit_ucla$apply2 <- as.factor(ologit_ucla$apply)
ologit_ucla$apply3 <- factor(ologit_ucla$apply2,levels=c("unlikely", "somewhat likely", "very likely"))


## fit ordered logit model
r_logit <- polr(apply2 ~ pared + public + gpa,
                data = ologit_ucla,
                method = 'logistic', # or 'probit'
                Hess=TRUE)

summary(r_logit)

# probability residuals

library(PResiduals)
presid <- presid(r_logit)
summary(presid)


# Hosmer-Lemeshow gof test

library(generalhoslem)
lg = logitgof(ologit_ucla$apply2, fitted(r_logit), g = 10, ord = TRUE)
lg
names(lg)

@josef-pkt

Copy link
Copy Markdown
Member Author

Stata code (history including commands not needed) for HL logit

note
outsample changes df
generate group = 1 if _n <= 30 for selecting subsample that has equal groupsizes, nobs multiple of 5
estat gof defaults to pearson chi2 without grouping, not compared

import delimited M:\josef_new\eclipse_ws\statsmodels\statsmodels_py37\statsmodels\statsmodels\datasets\spector\spector.csv, delimiter(space) clear 
logit grade gpa tuce psi
estat gof
return list
estat gof, group(5)
return list
generate group = 1 if _n <= 30
replace group = 2 if group==.
estat gof if group==1, group(5) table outsample
return list
estat gof, group(5) table outsample
return list
estat gof, group(5) table
return list

for ologit and mlogit (history including commands not needed)

notes
need to increase maxvar and matsize for ologitgof to run

use https://stats.idre.ucla.edu/stat/data/ologit.dta, clear
ologit apply i.pared i.public gpa
return list
ereturn list
. ologit apply i.pared i.public gpa, robust
listcoef, help
ologitgof apply pared public gpa
clear
clear matrix
clear mata
set maxvar 10000
use https://stats.idre.ucla.edu/stat/data/ologit.dta, clear
ologit apply i.pared i.public gpa
set matsize 1000
 ologitgof apply pared public gpa
return list
matrix list r(HLtableOE)
matrix list r(HLtable)
mlogit apply i.pared i.public gpa
 mlogitgof, group(10) table
return list

@josef-pkt

Copy link
Copy Markdown
Member Author

no update in more than a month

merging when it comes back green. I need to start the next round.

@josef-pkt
josef-pkt merged commit 874c666 into statsmodels:master Nov 19, 2020
@josef-pkt

Copy link
Copy Markdown
Member Author

I forgot to add stats._diagnostic_multinomial with a prob_larger_ordinal_choice helper function.
I don't remember the details right now, but we need prob_larger residuals in OrderedModel

@josef-pkt
josef-pkt deleted the diagnostic_ordinal branch February 21, 2021 14:06
@josef-pkt josef-pkt added this to the 0.13 milestone Jul 8, 2021
@josef-pkt

josef-pkt commented Oct 19, 2022 •

Copy link
Copy Markdown
Member Author

AFAICS, there is no stats._diagnostic_multinomial (unless it's uncommitted in an old checkout)

prob_larger_ordinal_choice and other multinomial helper functions are in stats.diagnostic_gen, included in this PR

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.

3 participants