code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def linear_harvey_collier(res, order_by=None, skip=None):
"""
Harvey Collier test for linearity
The Null hypothesis is that the regression is correctly modeled as linear.
Parameters
----------
res : RegressionResults
A results instance from a linear regression.
order_by : array_like, default None
Integer array specifying the order of the residuals. If not provided,
the order of the residuals is not changed. If provided, must have
the same number of observations as the endogenous variable.
skip : int, default None
The number of observations to use for initial OLS, if None then skip is
set equal to the number of regressors (columns in exog).
Returns
-------
tvalue : float
The test statistic, based on ttest_1sample.
pvalue : float
The pvalue of the test.
See Also
--------
statsmodels.stats.diadnostic.recursive_olsresiduals
Recursive OLS residual calculation used in the test.
Notes
-----
This test is a t-test that the mean of the recursive ols residuals is zero.
Calculating the recursive residuals might take some time for large samples.
"""
# I think this has different ddof than
# B.H. Baltagi, Econometrics, 2011, chapter 8
# but it matches Gretl and R:lmtest, pvalue at decimal=13
rr = recursive_olsresiduals(res, skip=skip, alpha=0.95, order_by=order_by)
return stats.ttest_1samp(rr[3][3:], 0) | Harvey Collier test for linearity
The Null hypothesis is that the regression is correctly modeled as linear.
Parameters
----------
res : RegressionResults
A results instance from a linear regression.
order_by : array_like, default None
Integer array specifying the order of the residuals. If not provided,
the order of the residuals is not changed. If provided, must have
the same number of observations as the endogenous variable.
skip : int, default None
The number of observations to use for initial OLS, if None then skip is
set equal to the number of regressors (columns in exog).
Returns
-------
tvalue : float
The test statistic, based on ttest_1sample.
pvalue : float
The pvalue of the test.
See Also
--------
statsmodels.stats.diadnostic.recursive_olsresiduals
Recursive OLS residual calculation used in the test.
Notes
-----
This test is a t-test that the mean of the recursive ols residuals is zero.
Calculating the recursive residuals might take some time for large samples. | linear_harvey_collier | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def linear_rainbow(res, frac=0.5, order_by=None, use_distance=False,
center=None):
"""
Rainbow test for linearity
The null hypothesis is the fit of the model using full sample is the same
as using a central subset. The alternative is that the fits are difference.
The rainbow test has power against many different forms of nonlinearity.
Parameters
----------
res : RegressionResults
A results instance from a linear regression.
frac : float, default 0.5
The fraction of the data to include in the center model.
order_by : {ndarray, str, List[str]}, default None
If an ndarray, the values in the array are used to sort the
observations. If a string or a list of strings, these are interpreted
as column name(s) which are then used to lexicographically sort the
data.
use_distance : bool, default False
Flag indicating whether data should be ordered by the Mahalanobis
distance to the center.
center : {float, int}, default None
If a float, the value must be in [0, 1] and the center is center *
nobs of the ordered data. If an integer, must be in [0, nobs) and
is interpreted as the observation of the ordered data to use.
Returns
-------
fstat : float
The test statistic based on the F test.
pvalue : float
The pvalue of the test.
Notes
-----
This test assumes residuals are homoskedastic and may reject a correct
linear specification if the residuals are heteroskedastic.
"""
if not isinstance(res, RegressionResultsWrapper):
raise TypeError("res must be a results instance from a linear model.")
frac = float_like(frac, "frac")
use_distance = bool_like(use_distance, "use_distance")
nobs = res.nobs
endog = res.model.endog
exog = res.model.exog
if order_by is not None and use_distance:
raise ValueError("order_by and use_distance cannot be simultaneously"
"used.")
if order_by is not None:
if isinstance(order_by, np.ndarray):
order_by = array_like(order_by, "order_by", ndim=1, dtype="int")
else:
if isinstance(order_by, str):
order_by = [order_by]
try:
cols = res.model.data.orig_exog[order_by].copy()
except (IndexError, KeyError):
raise TypeError("order_by must contain valid column names "
"from the exog data used to construct res,"
"and exog must be a pandas DataFrame.")
name = "__index__"
while name in cols:
name += '_'
cols[name] = np.arange(cols.shape[0])
cols = cols.sort_values(order_by)
order_by = np.asarray(cols[name])
endog = endog[order_by]
exog = exog[order_by]
if use_distance:
center = int(nobs) // 2 if center is None else center
if isinstance(center, float):
if not 0.0 <= center <= 1.0:
raise ValueError("center must be in (0, 1) when a float.")
center = int(center * (nobs-1))
else:
center = int_like(center, "center")
if not 0 < center < nobs - 1:
raise ValueError("center must be in [0, nobs) when an int.")
center_obs = exog[center:center+1]
from scipy.spatial.distance import cdist
try:
err = exog - center_obs
vi = np.linalg.inv(err.T @ err / nobs)
except np.linalg.LinAlgError:
err = exog - exog.mean(0)
vi = np.linalg.inv(err.T @ err / nobs)
dist = cdist(exog, center_obs, metric='mahalanobis', VI=vi)
idx = np.argsort(dist.ravel())
endog = endog[idx]
exog = exog[idx]
lowidx = np.ceil(0.5 * (1 - frac) * nobs).astype(int)
uppidx = np.floor(lowidx + frac * nobs).astype(int)
if uppidx - lowidx < exog.shape[1]:
raise ValueError("frac is too small to perform test. frac * nobs"
"must be greater than the number of exogenous"
"variables in the model.")
mi_sl = slice(lowidx, uppidx)
res_mi = OLS(endog[mi_sl], exog[mi_sl]).fit()
nobs_mi = res_mi.model.endog.shape[0]
ss_mi = res_mi.ssr
ss = res.ssr
fstat = (ss - ss_mi) / (nobs - nobs_mi) / ss_mi * res_mi.df_resid
pval = stats.f.sf(fstat, nobs - nobs_mi, res_mi.df_resid)
return fstat, pval | Rainbow test for linearity
The null hypothesis is the fit of the model using full sample is the same
as using a central subset. The alternative is that the fits are difference.
The rainbow test has power against many different forms of nonlinearity.
Parameters
----------
res : RegressionResults
A results instance from a linear regression.
frac : float, default 0.5
The fraction of the data to include in the center model.
order_by : {ndarray, str, List[str]}, default None
If an ndarray, the values in the array are used to sort the
observations. If a string or a list of strings, these are interpreted
as column name(s) which are then used to lexicographically sort the
data.
use_distance : bool, default False
Flag indicating whether data should be ordered by the Mahalanobis
distance to the center.
center : {float, int}, default None
If a float, the value must be in [0, 1] and the center is center *
nobs of the ordered data. If an integer, must be in [0, nobs) and
is interpreted as the observation of the ordered data to use.
Returns
-------
fstat : float
The test statistic based on the F test.
pvalue : float
The pvalue of the test.
Notes
-----
This test assumes residuals are homoskedastic and may reject a correct
linear specification if the residuals are heteroskedastic. | linear_rainbow | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def linear_lm(resid, exog, func=None):
"""
Lagrange multiplier test for linearity against functional alternative
# TODO: Remove the restriction
limitations: Assumes currently that the first column is integer.
Currently it does not check whether the transformed variables contain NaNs,
for example log of negative number.
Parameters
----------
resid : ndarray
residuals of a regression
exog : ndarray
exogenous variables for which linearity is tested
func : callable, default None
If func is None, then squares are used. func needs to take an array
of exog and return an array of transformed variables.
Returns
-------
lm : float
Lagrange multiplier test statistic
lm_pval : float
p-value of Lagrange multiplier tes
ftest : ContrastResult instance
the results from the F test variant of this test
Notes
-----
Written to match Gretl's linearity test. The test runs an auxiliary
regression of the residuals on the combined original and transformed
regressors. The Null hypothesis is that the linear specification is
correct.
"""
if func is None:
def func(x):
return np.power(x, 2)
exog = np.asarray(exog)
exog_aux = np.column_stack((exog, func(exog[:, 1:])))
nobs, k_vars = exog.shape
ls = OLS(resid, exog_aux).fit()
ftest = ls.f_test(np.eye(k_vars - 1, k_vars * 2 - 1, k_vars))
lm = nobs * ls.rsquared
lm_pval = stats.chi2.sf(lm, k_vars - 1)
return lm, lm_pval, ftest | Lagrange multiplier test for linearity against functional alternative
# TODO: Remove the restriction
limitations: Assumes currently that the first column is integer.
Currently it does not check whether the transformed variables contain NaNs,
for example log of negative number.
Parameters
----------
resid : ndarray
residuals of a regression
exog : ndarray
exogenous variables for which linearity is tested
func : callable, default None
If func is None, then squares are used. func needs to take an array
of exog and return an array of transformed variables.
Returns
-------
lm : float
Lagrange multiplier test statistic
lm_pval : float
p-value of Lagrange multiplier tes
ftest : ContrastResult instance
the results from the F test variant of this test
Notes
-----
Written to match Gretl's linearity test. The test runs an auxiliary
regression of the residuals on the combined original and transformed
regressors. The Null hypothesis is that the linear specification is
correct. | linear_lm | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def spec_white(resid, exog):
"""
White's Two-Moment Specification Test
Parameters
----------
resid : array_like
OLS residuals.
exog : array_like
OLS design matrix.
Returns
-------
stat : float
The test statistic.
pval : float
A chi-square p-value for test statistic.
dof : int
The degrees of freedom.
See Also
--------
het_white
White's test for heteroskedasticity.
Notes
-----
Implements the two-moment specification test described by White's
Theorem 2 (1980, p. 823) which compares the standard OLS covariance
estimator with White's heteroscedasticity-consistent estimator. The
test statistic is shown to be chi-square distributed.
Null hypothesis is homoscedastic and correctly specified.
Assumes the OLS design matrix contains an intercept term and at least
one variable. The intercept is removed to calculate the test statistic.
Interaction terms (squares and crosses of OLS regressors) are added to
the design matrix to calculate the test statistic.
Degrees-of-freedom (full rank) = nvar + nvar * (nvar + 1) / 2
Linearly dependent columns are removed to avoid singular matrix error.
References
----------
.. [*] White, H. (1980). A heteroskedasticity-consistent covariance matrix
estimator and a direct test for heteroscedasticity. Econometrica, 48:
817-838.
"""
x = array_like(exog, "exog", ndim=2)
e = array_like(resid, "resid", ndim=1)
if x.shape[1] < 2 or not np.any(np.ptp(x, 0) == 0.0):
raise ValueError("White's specification test requires at least two"
"columns where one is a constant.")
# add interaction terms
i0, i1 = np.triu_indices(x.shape[1])
exog = np.delete(x[:, i0] * x[:, i1], 0, 1)
# collinearity check - see _fit_collinear
atol = 1e-14
rtol = 1e-13
tol = atol + rtol * exog.var(0)
r = np.linalg.qr(exog, mode="r")
mask = np.abs(r.diagonal()) < np.sqrt(tol)
exog = exog[:, np.where(~mask)[0]]
# calculate test statistic
sqe = e * e
sqmndevs = sqe - np.mean(sqe)
d = np.dot(exog.T, sqmndevs)
devx = exog - np.mean(exog, axis=0)
devx *= sqmndevs[:, None]
b = devx.T.dot(devx)
stat = d.dot(np.linalg.solve(b, d))
# chi-square test
dof = devx.shape[1]
pval = stats.chi2.sf(stat, dof)
return stat, pval, dof | White's Two-Moment Specification Test
Parameters
----------
resid : array_like
OLS residuals.
exog : array_like
OLS design matrix.
Returns
-------
stat : float
The test statistic.
pval : float
A chi-square p-value for test statistic.
dof : int
The degrees of freedom.
See Also
--------
het_white
White's test for heteroskedasticity.
Notes
-----
Implements the two-moment specification test described by White's
Theorem 2 (1980, p. 823) which compares the standard OLS covariance
estimator with White's heteroscedasticity-consistent estimator. The
test statistic is shown to be chi-square distributed.
Null hypothesis is homoscedastic and correctly specified.
Assumes the OLS design matrix contains an intercept term and at least
one variable. The intercept is removed to calculate the test statistic.
Interaction terms (squares and crosses of OLS regressors) are added to
the design matrix to calculate the test statistic.
Degrees-of-freedom (full rank) = nvar + nvar * (nvar + 1) / 2
Linearly dependent columns are removed to avoid singular matrix error.
References
----------
.. [*] White, H. (1980). A heteroskedasticity-consistent covariance matrix
estimator and a direct test for heteroscedasticity. Econometrica, 48:
817-838. | spec_white | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def recursive_olsresiduals(res, skip=None, lamda=0.0, alpha=0.95,
order_by=None):
"""
Calculate recursive ols with residuals and Cusum test statistic
Parameters
----------
res : RegressionResults
Results from estimation of a regression model.
skip : int, default None
The number of observations to use for initial OLS, if None then skip is
set equal to the number of regressors (columns in exog).
lamda : float, default 0.0
The weight for Ridge correction to initial (X'X)^{-1}.
alpha : {0.90, 0.95, 0.99}, default 0.95
Confidence level of test, currently only two values supported,
used for confidence interval in cusum graph.
order_by : array_like, default None
Integer array specifying the order of the residuals. If not provided,
the order of the residuals is not changed. If provided, must have
the same number of observations as the endogenous variable.
Returns
-------
rresid : ndarray
The recursive ols residuals.
rparams : ndarray
The recursive ols parameter estimates.
rypred : ndarray
The recursive prediction of endogenous variable.
rresid_standardized : ndarray
The recursive residuals standardized so that N(0,sigma2) distributed,
where sigma2 is the error variance.
rresid_scaled : ndarray
The recursive residuals normalize so that N(0,1) distributed.
rcusum : ndarray
The cumulative residuals for cusum test.
rcusumci : ndarray
The confidence interval for cusum test using a size of alpha.
Notes
-----
It produces same recursive residuals as other version. This version updates
the inverse of the X'X matrix and does not require matrix inversion during
updating. looks efficient but no timing
Confidence interval in Greene and Brown, Durbin and Evans is the same as
in Ploberger after a little bit of algebra.
References
----------
jplv to check formulas, follows Harvey
BigJudge 5.5.2b for formula for inverse(X'X) updating
Greene section 7.5.2
Brown, R. L., J. Durbin, and J. M. Evans. “Techniques for Testing the
Constancy of Regression Relationships over Time.”
Journal of the Royal Statistical Society. Series B (Methodological) 37,
no. 2 (1975): 149-192.
"""
if not isinstance(res, RegressionResultsWrapper):
raise TypeError("res a regression results instance")
y = res.model.endog
x = res.model.exog
order_by = array_like(order_by, "order_by", dtype="int", optional=True,
ndim=1, shape=(y.shape[0],))
# intialize with skip observations
if order_by is not None:
x = x[order_by]
y = y[order_by]
nobs, nvars = x.shape
if skip is None:
skip = nvars
rparams = np.nan * np.zeros((nobs, nvars))
rresid = np.nan * np.zeros(nobs)
rypred = np.nan * np.zeros(nobs)
rvarraw = np.nan * np.zeros(nobs)
x0 = x[:skip]
if np.linalg.matrix_rank(x0) < x0.shape[1]:
err_msg = """\
"The initial regressor matrix, x[:skip], issingular. You must use a value of
skip large enough to ensure that the first OLS estimator is well-defined.
"""
raise ValueError(err_msg)
y0 = y[:skip]
# add Ridge to start (not in jplv)
xtxi = np.linalg.inv(np.dot(x0.T, x0) + lamda * np.eye(nvars))
xty = np.dot(x0.T, y0) # xi * y #np.dot(xi, y)
beta = np.dot(xtxi, xty)
rparams[skip - 1] = beta
yipred = np.dot(x[skip - 1], beta)
rypred[skip - 1] = yipred
rresid[skip - 1] = y[skip - 1] - yipred
rvarraw[skip - 1] = 1 + np.dot(x[skip - 1], np.dot(xtxi, x[skip - 1]))
for i in range(skip, nobs):
xi = x[i:i + 1, :]
yi = y[i]
# get prediction error with previous beta
yipred = np.dot(xi, beta)
rypred[i] = np.squeeze(yipred)
residi = yi - yipred
rresid[i] = np.squeeze(residi)
# update beta and inverse(X'X)
tmp = np.dot(xtxi, xi.T)
ft = 1 + np.dot(xi, tmp)
xtxi = xtxi - np.dot(tmp, tmp.T) / ft # BigJudge equ 5.5.15
beta = beta + (tmp * residi / ft).ravel() # BigJudge equ 5.5.14
rparams[i] = beta
rvarraw[i] = np.squeeze(ft)
rresid_scaled = rresid / np.sqrt(rvarraw) # N(0,sigma2) distributed
nrr = nobs - skip
# sigma2 = rresid_scaled[skip-1:].var(ddof=1) #var or sum of squares ?
# Greene has var, jplv and Ploberger have sum of squares (Ass.:mean=0)
# Gretl uses: by reverse engineering matching their numbers
sigma2 = rresid_scaled[skip:].var(ddof=1)
rresid_standardized = rresid_scaled / np.sqrt(sigma2) # N(0,1) distributed
rcusum = rresid_standardized[skip - 1:].cumsum()
# confidence interval points in Greene p136 looks strange. Cleared up
# this assumes sum of independent standard normal, which does not take into
# account that we make many tests at the same time
if alpha == 0.90:
a = 0.850
elif alpha == 0.95:
a = 0.948
elif alpha == 0.99:
a = 1.143
else:
raise ValueError("alpha can only be 0.9, 0.95 or 0.99")
# following taken from Ploberger,
# crit = a * np.sqrt(nrr)
rcusumci = (a * np.sqrt(nrr) + 2 * a * np.arange(0, nobs - skip) / np.sqrt(
nrr)) * np.array([[-1.], [+1.]])
return (rresid, rparams, rypred, rresid_standardized, rresid_scaled,
rcusum, rcusumci) | Calculate recursive ols with residuals and Cusum test statistic
Parameters
----------
res : RegressionResults
Results from estimation of a regression model.
skip : int, default None
The number of observations to use for initial OLS, if None then skip is
set equal to the number of regressors (columns in exog).
lamda : float, default 0.0
The weight for Ridge correction to initial (X'X)^{-1}.
alpha : {0.90, 0.95, 0.99}, default 0.95
Confidence level of test, currently only two values supported,
used for confidence interval in cusum graph.
order_by : array_like, default None
Integer array specifying the order of the residuals. If not provided,
the order of the residuals is not changed. If provided, must have
the same number of observations as the endogenous variable.
Returns
-------
rresid : ndarray
The recursive ols residuals.
rparams : ndarray
The recursive ols parameter estimates.
rypred : ndarray
The recursive prediction of endogenous variable.
rresid_standardized : ndarray
The recursive residuals standardized so that N(0,sigma2) distributed,
where sigma2 is the error variance.
rresid_scaled : ndarray
The recursive residuals normalize so that N(0,1) distributed.
rcusum : ndarray
The cumulative residuals for cusum test.
rcusumci : ndarray
The confidence interval for cusum test using a size of alpha.
Notes
-----
It produces same recursive residuals as other version. This version updates
the inverse of the X'X matrix and does not require matrix inversion during
updating. looks efficient but no timing
Confidence interval in Greene and Brown, Durbin and Evans is the same as
in Ploberger after a little bit of algebra.
References
----------
jplv to check formulas, follows Harvey
BigJudge 5.5.2b for formula for inverse(X'X) updating
Greene section 7.5.2
Brown, R. L., J. Durbin, and J. M. Evans. “Techniques for Testing the
Constancy of Regression Relationships over Time.”
Journal of the Royal Statistical Society. Series B (Methodological) 37,
no. 2 (1975): 149-192. | recursive_olsresiduals | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def breaks_hansen(olsresults):
"""
Test for model stability, breaks in parameters for ols, Hansen 1992
Parameters
----------
olsresults : RegressionResults
Results from estimation of a regression model.
Returns
-------
teststat : float
Hansen's test statistic.
crit : ndarray
The critical values at alpha=0.95 for different nvars.
Notes
-----
looks good in example, maybe not very powerful for small changes in
parameters
According to Greene, distribution of test statistics depends on nvar but
not on nobs.
Test statistic is verified against R:strucchange
References
----------
Greene section 7.5.1, notation follows Greene
"""
x = olsresults.model.exog
resid = array_like(olsresults.resid, "resid", shape=(x.shape[0], 1))
nobs, nvars = x.shape
resid2 = resid ** 2
ft = np.c_[x * resid[:, None], (resid2 - resid2.mean())]
score = ft.cumsum(0)
f = nobs * (ft[:, :, None] * ft[:, None, :]).sum(0)
s = (score[:, :, None] * score[:, None, :]).sum(0)
h = np.trace(np.dot(np.linalg.inv(f), s))
crit95 = np.array([(2, 1.01), (6, 1.9), (15, 3.75), (19, 4.52)],
dtype=[("nobs", int), ("crit", float)])
# TODO: get critical values from Bruce Hansen's 1992 paper
return h, crit95 | Test for model stability, breaks in parameters for ols, Hansen 1992
Parameters
----------
olsresults : RegressionResults
Results from estimation of a regression model.
Returns
-------
teststat : float
Hansen's test statistic.
crit : ndarray
The critical values at alpha=0.95 for different nvars.
Notes
-----
looks good in example, maybe not very powerful for small changes in
parameters
According to Greene, distribution of test statistics depends on nvar but
not on nobs.
Test statistic is verified against R:strucchange
References
----------
Greene section 7.5.1, notation follows Greene | breaks_hansen | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def breaks_cusumolsresid(resid, ddof=0):
"""
Cusum test for parameter stability based on ols residuals.
Parameters
----------
resid : ndarray
An array of residuals from an OLS estimation.
ddof : int
The number of parameters in the OLS estimation, used as degrees
of freedom correction for error variance.
Returns
-------
sup_b : float
The test statistic, maximum of absolute value of scaled cumulative OLS
residuals.
pval : float
Probability of observing the data under the null hypothesis of no
structural change, based on asymptotic distribution which is a Brownian
Bridge
crit: list
The tabulated critical values, for alpha = 1%, 5% and 10%.
Notes
-----
Tested against R:structchange.
Not clear: Assumption 2 in Ploberger, Kramer assumes that exog x have
asymptotically zero mean, x.mean(0) = [1, 0, 0, ..., 0]
Is this really necessary? I do not see how it can affect the test statistic
under the null. It does make a difference under the alternative.
Also, the asymptotic distribution of test statistic depends on this.
From examples it looks like there is little power for standard cusum if
exog (other than constant) have mean zero.
References
----------
Ploberger, Werner, and Walter Kramer. “The Cusum Test with OLS Residuals.”
Econometrica 60, no. 2 (March 1992): 271-285.
"""
resid = np.asarray(resid).ravel()
nobs = len(resid)
nobssigma2 = (resid ** 2).sum()
if ddof > 0:
nobssigma2 = nobssigma2 / (nobs - ddof) * nobs
# b is asymptotically a Brownian Bridge
b = resid.cumsum() / np.sqrt(nobssigma2) # use T*sigma directly
# asymptotically distributed as standard Brownian Bridge
sup_b = np.abs(b).max()
crit = [(1, 1.63), (5, 1.36), (10, 1.22)]
# Note stats.kstwobign.isf(0.1) is distribution of sup.abs of Brownian
# Bridge
# >>> stats.kstwobign.isf([0.01,0.05,0.1])
# array([ 1.62762361, 1.35809864, 1.22384787])
pval = stats.kstwobign.sf(sup_b)
return sup_b, pval, crit | Cusum test for parameter stability based on ols residuals.
Parameters
----------
resid : ndarray
An array of residuals from an OLS estimation.
ddof : int
The number of parameters in the OLS estimation, used as degrees
of freedom correction for error variance.
Returns
-------
sup_b : float
The test statistic, maximum of absolute value of scaled cumulative OLS
residuals.
pval : float
Probability of observing the data under the null hypothesis of no
structural change, based on asymptotic distribution which is a Brownian
Bridge
crit: list
The tabulated critical values, for alpha = 1%, 5% and 10%.
Notes
-----
Tested against R:structchange.
Not clear: Assumption 2 in Ploberger, Kramer assumes that exog x have
asymptotically zero mean, x.mean(0) = [1, 0, 0, ..., 0]
Is this really necessary? I do not see how it can affect the test statistic
under the null. It does make a difference under the alternative.
Also, the asymptotic distribution of test statistic depends on this.
From examples it looks like there is little power for standard cusum if
exog (other than constant) have mean zero.
References
----------
Ploberger, Werner, and Walter Kramer. “The Cusum Test with OLS Residuals.”
Econometrica 60, no. 2 (March 1992): 271-285. | breaks_cusumolsresid | python | statsmodels/statsmodels | statsmodels/stats/diagnostic.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/diagnostic.py | BSD-3-Clause |
def variance(self, decomp_type, n=5000, conf=0.99):
"""
A helper function to calculate the variance/std. Used to keep
the decomposition functions cleaner
"""
if self.submitted_n is not None:
n = self.submitted_n
if self.submitted_conf is not None:
conf = self.submitted_conf
if self.submitted_weight is not None:
submitted_weight = [
self.submitted_weight,
1 - self.submitted_weight,
]
bi = self.bi
bifurcate = self.bifurcate
endow_eff_list = []
coef_eff_list = []
int_eff_list = []
exp_eff_list = []
unexp_eff_list = []
for _ in range(0, n):
endog = np.column_stack((self.bi_col, self.endog))
exog = self.exog
amount = len(endog)
samples = np.random.randint(0, high=amount, size=amount)
endog = endog[samples]
exog = exog[samples]
neumark = np.delete(exog, bifurcate, axis=1)
exog_f = exog[np.where(exog[:, bifurcate] == bi[0])]
exog_s = exog[np.where(exog[:, bifurcate] == bi[1])]
endog_f = endog[np.where(endog[:, 0] == bi[0])]
endog_s = endog[np.where(endog[:, 0] == bi[1])]
exog_f = np.delete(exog_f, bifurcate, axis=1)
exog_s = np.delete(exog_s, bifurcate, axis=1)
endog_f = endog_f[:, 1]
endog_s = endog_s[:, 1]
endog = endog[:, 1]
two_fold_type = self.two_fold_type
if self.hasconst is False:
exog_f = add_constant(exog_f, prepend=False)
exog_s = add_constant(exog_s, prepend=False)
exog = add_constant(exog, prepend=False)
neumark = add_constant(neumark, prepend=False)
_f_model = OLS(endog_f, exog_f).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
_s_model = OLS(endog_s, exog_s).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
exog_f_mean = np.mean(exog_f, axis=0)
exog_s_mean = np.mean(exog_s, axis=0)
if decomp_type == 3:
endow_eff = (exog_f_mean - exog_s_mean) @ _s_model.params
coef_eff = exog_s_mean @ (_f_model.params - _s_model.params)
int_eff = (exog_f_mean - exog_s_mean) @ (
_f_model.params - _s_model.params
)
endow_eff_list.append(endow_eff)
coef_eff_list.append(coef_eff)
int_eff_list.append(int_eff)
elif decomp_type == 2:
len_f = len(exog_f)
len_s = len(exog_s)
if two_fold_type == "cotton":
t_params = (len_f / (len_f + len_s) * _f_model.params) + (
len_s / (len_f + len_s) * _s_model.params
)
elif two_fold_type == "reimers":
t_params = 0.5 * (_f_model.params + _s_model.params)
elif two_fold_type == "self_submitted":
t_params = (
submitted_weight[0] * _f_model.params
+ submitted_weight[1] * _s_model.params
)
elif two_fold_type == "nuemark":
_t_model = OLS(endog, neumark).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
t_params = _t_model.params
else:
_t_model = OLS(endog, exog).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
t_params = np.delete(_t_model.params, bifurcate)
unexplained = (exog_f_mean @ (_f_model.params - t_params)) + (
exog_s_mean @ (t_params - _s_model.params)
)
explained = (exog_f_mean - exog_s_mean) @ t_params
unexp_eff_list.append(unexplained)
exp_eff_list.append(explained)
high, low = int(n * conf), int(n * (1 - conf))
if decomp_type == 3:
return [
np.std(np.sort(endow_eff_list)[low:high]),
np.std(np.sort(coef_eff_list)[low:high]),
np.std(np.sort(int_eff_list)[low:high]),
]
elif decomp_type == 2:
return [
np.std(np.sort(unexp_eff_list)[low:high]),
np.std(np.sort(exp_eff_list)[low:high]),
] | A helper function to calculate the variance/std. Used to keep
the decomposition functions cleaner | variance | python | statsmodels/statsmodels | statsmodels/stats/oaxaca.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/oaxaca.py | BSD-3-Clause |
def three_fold(self, std=False, n=None, conf=None):
"""
Calculates the three-fold Oaxaca Blinder Decompositions
Parameters
----------
std: boolean, optional
If true, bootstrapped standard errors will be calculated.
n: int, optional
A amount of iterations to calculate the bootstrapped
standard errors. This defaults to 5000.
conf: float, optional
This is the confidence required for the standard error
calculation. Defaults to .99, but could be anything less
than or equal to one. One is heavy discouraged, due to the
extreme outliers inflating the variance.
Returns
-------
OaxacaResults
A results container for the three-fold decomposition.
"""
self.submitted_n = n
self.submitted_conf = conf
self.submitted_weight = None
std_val = None
self.endow_eff = (
self.exog_f_mean - self.exog_s_mean
) @ self._s_model.params
self.coef_eff = self.exog_s_mean @ (
self._f_model.params - self._s_model.params
)
self.int_eff = (self.exog_f_mean - self.exog_s_mean) @ (
self._f_model.params - self._s_model.params
)
if std is True:
std_val = self.variance(3)
return OaxacaResults(
(self.endow_eff, self.coef_eff, self.int_eff, self.gap),
3,
std_val=std_val,
) | Calculates the three-fold Oaxaca Blinder Decompositions
Parameters
----------
std: boolean, optional
If true, bootstrapped standard errors will be calculated.
n: int, optional
A amount of iterations to calculate the bootstrapped
standard errors. This defaults to 5000.
conf: float, optional
This is the confidence required for the standard error
calculation. Defaults to .99, but could be anything less
than or equal to one. One is heavy discouraged, due to the
extreme outliers inflating the variance.
Returns
-------
OaxacaResults
A results container for the three-fold decomposition. | three_fold | python | statsmodels/statsmodels | statsmodels/stats/oaxaca.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/oaxaca.py | BSD-3-Clause |
def two_fold(
self,
std=False,
two_fold_type="pooled",
submitted_weight=None,
n=None,
conf=None,
):
"""
Calculates the two-fold or pooled Oaxaca Blinder Decompositions
Methods
-------
std: boolean, optional
If true, bootstrapped standard errors will be calculated.
two_fold_type: string, optional
This method allows for the specific calculation of the
non-discriminatory model. There are four different types
available at this time. pooled, cotton, reimers, self_submitted.
Pooled is assumed and if a non-viable parameter is given,
pooled will be ran.
pooled - This type assumes that the pooled model's parameters
(a normal regression) is the non-discriminatory model.
This includes the indicator variable. This is generally
the best idea. If you have economic justification for
using others, then use others.
nuemark - This is similar to the pooled type, but the regression
is not done including the indicator variable.
cotton - This type uses the adjusted in Cotton (1988), which
accounts for the undervaluation of one group causing the
overevalution of another. It uses the sample size weights for
a linear combination of the two model parameters
reimers - This type uses a linear combination of the two
models with both parameters being 50% of the
non-discriminatory model.
self_submitted - This allows the user to submit their
own weights. Please be sure to put the weight of the larger mean
group only. This should be submitted in the
submitted_weights variable.
submitted_weight: int/float, required only for self_submitted,
This is the submitted weight for the larger mean. If the
weight for the larger mean is p, then the weight for the
other mean is 1-p. Only submit the first value.
n: int, optional
A amount of iterations to calculate the bootstrapped
standard errors. This defaults to 5000.
conf: float, optional
This is the confidence required for the standard error
calculation. Defaults to .99, but could be anything less
than or equal to one. One is heavy discouraged, due to the
extreme outliers inflating the variance.
Returns
-------
OaxacaResults
A results container for the two-fold decomposition.
"""
self.submitted_n = n
self.submitted_conf = conf
std_val = None
self.two_fold_type = two_fold_type
self.submitted_weight = submitted_weight
if two_fold_type == "cotton":
self.t_params = (
self.len_f / (self.len_f + self.len_s) * self._f_model.params
) + (self.len_s / (self.len_f + self.len_s) * self._s_model.params)
elif two_fold_type == "reimers":
self.t_params = 0.5 * (self._f_model.params + self._s_model.params)
elif two_fold_type == "self_submitted":
if submitted_weight is None:
raise ValueError("Please submit weights")
submitted_weight = [submitted_weight, 1 - submitted_weight]
self.t_params = (
submitted_weight[0] * self._f_model.params
+ submitted_weight[1] * self._s_model.params
)
elif two_fold_type == "nuemark":
self._t_model = OLS(self.endog, self.neumark).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
self.t_params = self._t_model.params
else:
self._t_model = OLS(self.endog, self.exog).fit(
cov_type=self.cov_type, cov_kwds=self.cov_kwds
)
self.t_params = np.delete(self._t_model.params, self.bifurcate)
self.unexplained = (
self.exog_f_mean @ (self._f_model.params - self.t_params)
) + (self.exog_s_mean @ (self.t_params - self._s_model.params))
self.explained = (self.exog_f_mean - self.exog_s_mean) @ self.t_params
if std is True:
std_val = self.variance(2)
return OaxacaResults(
(self.unexplained, self.explained, self.gap), 2, std_val=std_val
) | Calculates the two-fold or pooled Oaxaca Blinder Decompositions
Methods
-------
std: boolean, optional
If true, bootstrapped standard errors will be calculated.
two_fold_type: string, optional
This method allows for the specific calculation of the
non-discriminatory model. There are four different types
available at this time. pooled, cotton, reimers, self_submitted.
Pooled is assumed and if a non-viable parameter is given,
pooled will be ran.
pooled - This type assumes that the pooled model's parameters
(a normal regression) is the non-discriminatory model.
This includes the indicator variable. This is generally
the best idea. If you have economic justification for
using others, then use others.
nuemark - This is similar to the pooled type, but the regression
is not done including the indicator variable.
cotton - This type uses the adjusted in Cotton (1988), which
accounts for the undervaluation of one group causing the
overevalution of another. It uses the sample size weights for
a linear combination of the two model parameters
reimers - This type uses a linear combination of the two
models with both parameters being 50% of the
non-discriminatory model.
self_submitted - This allows the user to submit their
own weights. Please be sure to put the weight of the larger mean
group only. This should be submitted in the
submitted_weights variable.
submitted_weight: int/float, required only for self_submitted,
This is the submitted weight for the larger mean. If the
weight for the larger mean is p, then the weight for the
other mean is 1-p. Only submit the first value.
n: int, optional
A amount of iterations to calculate the bootstrapped
standard errors. This defaults to 5000.
conf: float, optional
This is the confidence required for the standard error
calculation. Defaults to .99, but could be anything less
than or equal to one. One is heavy discouraged, due to the
extreme outliers inflating the variance.
Returns
-------
OaxacaResults
A results container for the two-fold decomposition. | two_fold | python | statsmodels/statsmodels | statsmodels/stats/oaxaca.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/oaxaca.py | BSD-3-Clause |
def summary(self):
"""
Print a summary table with the Oaxaca-Blinder effects
"""
if self.model_type == 2:
if self.std is None:
print(
dedent(
f"""\
Oaxaca-Blinder Two-fold Effects
Unexplained Effect: {self.params[0]:.5f}
Explained Effect: {self.params[1]:.5f}
Gap: {self.params[2]:.5f}"""
)
)
else:
print(
dedent(
"""\
Oaxaca-Blinder Two-fold Effects
Unexplained Effect: {:.5f}
Unexplained Standard Error: {:.5f}
Explained Effect: {:.5f}
Explained Standard Error: {:.5f}
Gap: {:.5f}""".format(
self.params[0],
self.std[0],
self.params[1],
self.std[1],
self.params[2],
)
)
)
if self.model_type == 3:
if self.std is None:
print(
dedent(
f"""\
Oaxaca-Blinder Three-fold Effects
Endowment Effect: {self.params[0]:.5f}
Coefficient Effect: {self.params[1]:.5f}
Interaction Effect: {self.params[2]:.5f}
Gap: {self.params[3]:.5f}"""
)
)
else:
print(
dedent(
f"""\
Oaxaca-Blinder Three-fold Effects
Endowment Effect: {self.params[0]:.5f}
Endowment Standard Error: {self.std[0]:.5f}
Coefficient Effect: {self.params[1]:.5f}
Coefficient Standard Error: {self.std[1]:.5f}
Interaction Effect: {self.params[2]:.5f}
Interaction Standard Error: {self.std[2]:.5f}
Gap: {self.params[3]:.5f}"""
)
) | Print a summary table with the Oaxaca-Blinder effects | summary | python | statsmodels/statsmodels | statsmodels/stats/oaxaca.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/oaxaca.py | BSD-3-Clause |
def trimboth(a, proportiontocut, axis=0):
"""
Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). You must pre-sort the array if you want
'proper' trimming. Slices off less if proportion results in a
non-integer slice index (i.e., conservatively slices off
`proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float or int
Proportion of data to trim at each end.
axis : int or None
Axis along which the observations are trimmed. The default is to trim
along axis=0. If axis is None then the array will be flattened before
trimming.
Returns
-------
out : array-like
Trimmed version of array `a`.
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,)
"""
a = np.asarray(a)
if axis is None:
a = a.ravel()
axis = 0
nobs = a.shape[axis]
lowercut = int(proportiontocut * nobs)
uppercut = nobs - lowercut
if (lowercut >= uppercut):
raise ValueError("Proportion too big.")
sl = [slice(None)] * a.ndim
sl[axis] = slice(lowercut, uppercut)
return a[tuple(sl)] | Slices off a proportion of items from both ends of an array.
Slices off the passed proportion of items from both ends of the passed
array (i.e., with `proportiontocut` = 0.1, slices leftmost 10% **and**
rightmost 10% of scores). You must pre-sort the array if you want
'proper' trimming. Slices off less if proportion results in a
non-integer slice index (i.e., conservatively slices off
`proportiontocut`).
Parameters
----------
a : array_like
Data to trim.
proportiontocut : float or int
Proportion of data to trim at each end.
axis : int or None
Axis along which the observations are trimmed. The default is to trim
along axis=0. If axis is None then the array will be flattened before
trimming.
Returns
-------
out : array-like
Trimmed version of array `a`.
Examples
--------
>>> from scipy import stats
>>> a = np.arange(20)
>>> b = stats.trimboth(a, 0.1)
>>> b.shape
(16,) | trimboth | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def trim_mean(a, proportiontocut, axis=0):
"""
Return mean of array after trimming observations from both tails.
If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
scores. Slices off LESS if proportion results in a non-integer slice
index (i.e., conservatively slices off `proportiontocut` ).
Parameters
----------
a : array_like
Input array
proportiontocut : float
Fraction to cut off at each tail of the sorted observations.
axis : int or None
Axis along which the trimmed means are computed. The default is axis=0.
If axis is None then the trimmed mean will be computed for the
flattened array.
Returns
-------
trim_mean : ndarray
Mean of trimmed array.
"""
newa = trimboth(np.sort(a, axis), proportiontocut, axis=axis)
return np.mean(newa, axis=axis) | Return mean of array after trimming observations from both tails.
If `proportiontocut` = 0.1, slices off 'leftmost' and 'rightmost' 10% of
scores. Slices off LESS if proportion results in a non-integer slice
index (i.e., conservatively slices off `proportiontocut` ).
Parameters
----------
a : array_like
Input array
proportiontocut : float
Fraction to cut off at each tail of the sorted observations.
axis : int or None
Axis along which the trimmed means are computed. The default is axis=0.
If axis is None then the trimmed mean will be computed for the
flattened array.
Returns
-------
trim_mean : ndarray
Mean of trimmed array. | trim_mean | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def data_trimmed(self):
"""numpy array of trimmed and sorted data
"""
# returns a view
return self.data_sorted[self.sl] | numpy array of trimmed and sorted data | data_trimmed | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def data_winsorized(self):
"""winsorized data
"""
lb = np.expand_dims(self.lowerbound, self.axis)
ub = np.expand_dims(self.upperbound, self.axis)
return np.clip(self.data_sorted, lb, ub) | winsorized data | data_winsorized | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def mean_trimmed(self):
"""mean of trimmed data
"""
return np.mean(self.data_sorted[tuple(self.sl)], self.axis) | mean of trimmed data | mean_trimmed | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def mean_winsorized(self):
"""mean of winsorized data
"""
return np.mean(self.data_winsorized, self.axis) | mean of winsorized data | mean_winsorized | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def var_winsorized(self):
"""variance of winsorized data
"""
# hardcoded ddof = 1
return np.var(self.data_winsorized, ddof=1, axis=self.axis) | variance of winsorized data | var_winsorized | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def std_mean_trimmed(self):
"""standard error of trimmed mean
"""
se = np.sqrt(self.var_winsorized / self.nobs_reduced)
# trimming creates correlation across trimmed observations
# trimming is based on order statistics of the data
# wilcox 2012, p.61
se *= np.sqrt(self.nobs / self.nobs_reduced)
return se | standard error of trimmed mean | std_mean_trimmed | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def std_mean_winsorized(self):
"""standard error of winsorized mean
"""
# the following matches Wilcox, WRS2
std_ = np.sqrt(self.var_winsorized / self.nobs)
std_ *= (self.nobs - 1) / (self.nobs_reduced - 1)
# old version
# tm = self
# formula from an old SAS manual page, simplified
# std_ = np.sqrt(tm.var_winsorized / (tm.nobs_reduced - 1) *
# (tm.nobs - 1.) / tm.nobs)
return std_ | standard error of winsorized mean | std_mean_winsorized | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def ttest_mean(self, value=0, transform='trimmed',
alternative='two-sided'):
"""
One sample t-test for trimmed or Winsorized mean
Parameters
----------
value : float
Value of the mean under the Null hypothesis
transform : {'trimmed', 'winsorized'}
Specified whether the mean test is based on trimmed or winsorized
data.
alternative : {'two-sided', 'larger', 'smaller'}
Notes
-----
p-value is based on the approximate t-distribution of the test
statistic. The approximation is valid if the underlying distribution
is symmetric.
"""
import statsmodels.stats.weightstats as smws
df = self.nobs_reduced - 1
if transform == 'trimmed':
mean_ = self.mean_trimmed
std_ = self.std_mean_trimmed
elif transform == 'winsorized':
mean_ = self.mean_winsorized
std_ = self.std_mean_winsorized
else:
raise ValueError("transform can only be 'trimmed' or 'winsorized'")
res = smws._tstat_generic(mean_, 0, std_,
df, alternative=alternative, diff=value)
return res + (df,) | One sample t-test for trimmed or Winsorized mean
Parameters
----------
value : float
Value of the mean under the Null hypothesis
transform : {'trimmed', 'winsorized'}
Specified whether the mean test is based on trimmed or winsorized
data.
alternative : {'two-sided', 'larger', 'smaller'}
Notes
-----
p-value is based on the approximate t-distribution of the test
statistic. The approximation is valid if the underlying distribution
is symmetric. | ttest_mean | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def reset_fraction(self, frac):
"""create a TrimmedMean instance with a new trimming fraction
This reuses the sorted array from the current instance.
"""
tm = TrimmedMean(self.data_sorted, frac, is_sorted=True,
axis=self.axis)
tm.data = self.data
# TODO: this will not work if there is processing of meta-information
# in __init__,
# for example storing a pandas DataFrame or Series index
return tm | create a TrimmedMean instance with a new trimming fraction
This reuses the sorted array from the current instance. | reset_fraction | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def scale_transform(data, center='median', transform='abs', trim_frac=0.2,
axis=0):
"""Transform data for variance comparison for Levene type tests
Parameters
----------
data : array_like
Observations for the data.
center : "median", "mean", "trimmed" or float
Statistic used for centering observations. If a float, then this
value is used to center. Default is median.
transform : 'abs', 'square', 'identity' or a callable
The transform for the centered data.
trim_frac : float in [0, 0.5)
Fraction of observations that are trimmed on each side of the sorted
observations. This is only used if center is `trimmed`.
axis : int
Axis along which the data are transformed when centering.
Returns
-------
res : ndarray
transformed data in the same shape as the original data.
"""
x = np.asarray(data) # x is shorthand from earlier code
if transform == 'abs':
tfunc = np.abs
elif transform == 'square':
tfunc = lambda x: x * x # noqa
elif transform == 'identity':
tfunc = lambda x: x # noqa
elif callable(transform):
tfunc = transform
else:
raise ValueError('transform should be abs, square or exp')
if center == 'median':
res = tfunc(x - np.expand_dims(np.median(x, axis=axis), axis))
elif center == 'mean':
res = tfunc(x - np.expand_dims(np.mean(x, axis=axis), axis))
elif center == 'trimmed':
center = trim_mean(x, trim_frac, axis=axis)
res = tfunc(x - np.expand_dims(center, axis))
elif isinstance(center, numbers.Number):
res = tfunc(x - center)
else:
raise ValueError('center should be median, mean or trimmed')
return res | Transform data for variance comparison for Levene type tests
Parameters
----------
data : array_like
Observations for the data.
center : "median", "mean", "trimmed" or float
Statistic used for centering observations. If a float, then this
value is used to center. Default is median.
transform : 'abs', 'square', 'identity' or a callable
The transform for the centered data.
trim_frac : float in [0, 0.5)
Fraction of observations that are trimmed on each side of the sorted
observations. This is only used if center is `trimmed`.
axis : int
Axis along which the data are transformed when centering.
Returns
-------
res : ndarray
transformed data in the same shape as the original data. | scale_transform | python | statsmodels/statsmodels | statsmodels/stats/robust_compare.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/robust_compare.py | BSD-3-Clause |
def _int_ifclose(x, dec=1, width=4):
'''helper function for creating result string for int or float
only dec=1 and width=4 is implemented
Parameters
----------
x : int or float
value to format
dec : 1
number of decimals to print if x is not an integer
width : 4
width of string
Returns
-------
xint : int or float
x is converted to int if it is within 1e-14 of an integer
x_string : str
x formatted as string, either '%4d' or '%4.1f'
'''
xint = int(round(x))
if np.max(np.abs(xint - x)) < 1e-14:
return xint, '%4d' % xint
else:
return x, '%4.1f' % x | helper function for creating result string for int or float
only dec=1 and width=4 is implemented
Parameters
----------
x : int or float
value to format
dec : 1
number of decimals to print if x is not an integer
width : 4
width of string
Returns
-------
xint : int or float
x is converted to int if it is within 1e-14 of an integer
x_string : str
x formatted as string, either '%4d' or '%4.1f' | _int_ifclose | python | statsmodels/statsmodels | statsmodels/stats/inter_rater.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/inter_rater.py | BSD-3-Clause |
def aggregate_raters(data, n_cat=None):
'''convert raw data with shape (subject, rater) to (subject, cat_counts)
brings data into correct format for fleiss_kappa
bincount will raise exception if data cannot be converted to integer.
Parameters
----------
data : array_like, 2-Dim
data containing category assignment with subjects in rows and raters
in columns.
n_cat : None or int
If None, then the data is converted to integer categories,
0,1,2,...,n_cat-1. Because of the relabeling only category levels
with non-zero counts are included.
If this is an integer, then the category levels in the data are already
assumed to be in integers, 0,1,2,...,n_cat-1. In this case, the
returned array may contain columns with zero count, if no subject
has been categorized with this level.
Returns
-------
arr : nd_array, (n_rows, n_cat)
Contains counts of raters that assigned a category level to individuals.
Subjects are in rows, category levels in columns.
categories : nd_array, (n_category_levels,)
Contains the category levels.
'''
data = np.asarray(data)
n_rows = data.shape[0]
if n_cat is None:
#I could add int conversion (reverse_index) to np.unique
cat_uni, cat_int = np.unique(data.ravel(), return_inverse=True)
n_cat = len(cat_uni)
data_ = cat_int.reshape(data.shape)
else:
cat_uni = np.arange(n_cat) #for return only, assumed cat levels
data_ = data
tt = np.zeros((n_rows, n_cat), int)
for idx, row in enumerate(data_):
ro = np.bincount(row)
tt[idx, :len(ro)] = ro
return tt, cat_uni | convert raw data with shape (subject, rater) to (subject, cat_counts)
brings data into correct format for fleiss_kappa
bincount will raise exception if data cannot be converted to integer.
Parameters
----------
data : array_like, 2-Dim
data containing category assignment with subjects in rows and raters
in columns.
n_cat : None or int
If None, then the data is converted to integer categories,
0,1,2,...,n_cat-1. Because of the relabeling only category levels
with non-zero counts are included.
If this is an integer, then the category levels in the data are already
assumed to be in integers, 0,1,2,...,n_cat-1. In this case, the
returned array may contain columns with zero count, if no subject
has been categorized with this level.
Returns
-------
arr : nd_array, (n_rows, n_cat)
Contains counts of raters that assigned a category level to individuals.
Subjects are in rows, category levels in columns.
categories : nd_array, (n_category_levels,)
Contains the category levels. | aggregate_raters | python | statsmodels/statsmodels | statsmodels/stats/inter_rater.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/inter_rater.py | BSD-3-Clause |
def to_table(data, bins=None):
'''convert raw data with shape (subject, rater) to (rater1, rater2)
brings data into correct format for cohens_kappa
Parameters
----------
data : array_like, 2-Dim
data containing category assignment with subjects in rows and raters
in columns.
bins : None, int or tuple of array_like
If None, then the data is converted to integer categories,
0,1,2,...,n_cat-1. Because of the relabeling only category levels
with non-zero counts are included.
If this is an integer, then the category levels in the data are already
assumed to be in integers, 0,1,2,...,n_cat-1. In this case, the
returned array may contain columns with zero count, if no subject
has been categorized with this level.
If bins are a tuple of two array_like, then the bins are directly used
by ``numpy.histogramdd``. This is useful if we want to merge categories.
Returns
-------
arr : nd_array, (n_cat, n_cat)
Contingency table that contains counts of category level with rater1
in rows and rater2 in columns.
Notes
-----
no NaN handling, delete rows with missing values
This works also for more than two raters. In that case the dimension of
the resulting contingency table is the same as the number of raters
instead of 2-dimensional.
'''
data = np.asarray(data)
n_rows, n_cols = data.shape
if bins is None:
#I could add int conversion (reverse_index) to np.unique
cat_uni, cat_int = np.unique(data.ravel(), return_inverse=True)
n_cat = len(cat_uni)
data_ = cat_int.reshape(data.shape)
bins_ = np.arange(n_cat+1) - 0.5
#alternative implementation with double loop
#tt = np.asarray([[(x == [i,j]).all(1).sum() for j in cat_uni]
# for i in cat_uni] )
#other altervative: unique rows and bincount
elif np.isscalar(bins):
bins_ = np.arange(bins+1) - 0.5
data_ = data
else:
bins_ = bins
data_ = data
tt = np.histogramdd(data_, (bins_,)*n_cols)
return tt[0], bins_ | convert raw data with shape (subject, rater) to (rater1, rater2)
brings data into correct format for cohens_kappa
Parameters
----------
data : array_like, 2-Dim
data containing category assignment with subjects in rows and raters
in columns.
bins : None, int or tuple of array_like
If None, then the data is converted to integer categories,
0,1,2,...,n_cat-1. Because of the relabeling only category levels
with non-zero counts are included.
If this is an integer, then the category levels in the data are already
assumed to be in integers, 0,1,2,...,n_cat-1. In this case, the
returned array may contain columns with zero count, if no subject
has been categorized with this level.
If bins are a tuple of two array_like, then the bins are directly used
by ``numpy.histogramdd``. This is useful if we want to merge categories.
Returns
-------
arr : nd_array, (n_cat, n_cat)
Contingency table that contains counts of category level with rater1
in rows and rater2 in columns.
Notes
-----
no NaN handling, delete rows with missing values
This works also for more than two raters. In that case the dimension of
the resulting contingency table is the same as the number of raters
instead of 2-dimensional. | to_table | python | statsmodels/statsmodels | statsmodels/stats/inter_rater.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/inter_rater.py | BSD-3-Clause |
def fleiss_kappa(table, method='fleiss'):
"""Fleiss' and Randolph's kappa multi-rater agreement measure
Parameters
----------
table : array_like, 2-D
assumes subjects in rows, and categories in columns. Convert raw data
into this format by using
:func:`statsmodels.stats.inter_rater.aggregate_raters`
method : str
Method 'fleiss' returns Fleiss' kappa which uses the sample margin
to define the chance outcome.
Method 'randolph' or 'uniform' (only first 4 letters are needed)
returns Randolph's (2005) multirater kappa which assumes a uniform
distribution of the categories to define the chance outcome.
Returns
-------
kappa : float
Fleiss's or Randolph's kappa statistic for inter rater agreement
Notes
-----
no variance or hypothesis tests yet
Interrater agreement measures like Fleiss's kappa measure agreement relative
to chance agreement. Different authors have proposed ways of defining
these chance agreements. Fleiss' is based on the marginal sample distribution
of categories, while Randolph uses a uniform distribution of categories as
benchmark. Warrens (2010) showed that Randolph's kappa is always larger or
equal to Fleiss' kappa. Under some commonly observed condition, Fleiss' and
Randolph's kappa provide lower and upper bounds for two similar kappa_like
measures by Light (1971) and Hubert (1977).
References
----------
Wikipedia https://en.wikipedia.org/wiki/Fleiss%27_kappa
Fleiss, Joseph L. 1971. "Measuring Nominal Scale Agreement among Many
Raters." Psychological Bulletin 76 (5): 378-82.
https://doi.org/10.1037/h0031619.
Randolph, Justus J. 2005 "Free-Marginal Multirater Kappa (multirater
K [free]): An Alternative to Fleiss' Fixed-Marginal Multirater Kappa."
Presented at the Joensuu Learning and Instruction Symposium, vol. 2005
https://eric.ed.gov/?id=ED490661
Warrens, Matthijs J. 2010. "Inequalities between Multi-Rater Kappas."
Advances in Data Analysis and Classification 4 (4): 271-86.
https://doi.org/10.1007/s11634-010-0073-4.
"""
table = 1.0 * np.asarray(table) #avoid integer division
n_sub, n_cat = table.shape
n_total = table.sum()
n_rater = table.sum(1)
n_rat = n_rater.max()
#assume fully ranked
assert n_total == n_sub * n_rat
#marginal frequency of categories
p_cat = table.sum(0) / n_total
table2 = table * table
p_rat = (table2.sum(1) - n_rat) / (n_rat * (n_rat - 1.))
p_mean = p_rat.mean()
if method == 'fleiss':
p_mean_exp = (p_cat*p_cat).sum()
elif method.startswith('rand') or method.startswith('unif'):
p_mean_exp = 1 / n_cat
kappa = (p_mean - p_mean_exp) / (1- p_mean_exp)
return kappa | Fleiss' and Randolph's kappa multi-rater agreement measure
Parameters
----------
table : array_like, 2-D
assumes subjects in rows, and categories in columns. Convert raw data
into this format by using
:func:`statsmodels.stats.inter_rater.aggregate_raters`
method : str
Method 'fleiss' returns Fleiss' kappa which uses the sample margin
to define the chance outcome.
Method 'randolph' or 'uniform' (only first 4 letters are needed)
returns Randolph's (2005) multirater kappa which assumes a uniform
distribution of the categories to define the chance outcome.
Returns
-------
kappa : float
Fleiss's or Randolph's kappa statistic for inter rater agreement
Notes
-----
no variance or hypothesis tests yet
Interrater agreement measures like Fleiss's kappa measure agreement relative
to chance agreement. Different authors have proposed ways of defining
these chance agreements. Fleiss' is based on the marginal sample distribution
of categories, while Randolph uses a uniform distribution of categories as
benchmark. Warrens (2010) showed that Randolph's kappa is always larger or
equal to Fleiss' kappa. Under some commonly observed condition, Fleiss' and
Randolph's kappa provide lower and upper bounds for two similar kappa_like
measures by Light (1971) and Hubert (1977).
References
----------
Wikipedia https://en.wikipedia.org/wiki/Fleiss%27_kappa
Fleiss, Joseph L. 1971. "Measuring Nominal Scale Agreement among Many
Raters." Psychological Bulletin 76 (5): 378-82.
https://doi.org/10.1037/h0031619.
Randolph, Justus J. 2005 "Free-Marginal Multirater Kappa (multirater
K [free]): An Alternative to Fleiss' Fixed-Marginal Multirater Kappa."
Presented at the Joensuu Learning and Instruction Symposium, vol. 2005
https://eric.ed.gov/?id=ED490661
Warrens, Matthijs J. 2010. "Inequalities between Multi-Rater Kappas."
Advances in Data Analysis and Classification 4 (4): 271-86.
https://doi.org/10.1007/s11634-010-0073-4. | fleiss_kappa | python | statsmodels/statsmodels | statsmodels/stats/inter_rater.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/inter_rater.py | BSD-3-Clause |
def cohens_kappa(table, weights=None, return_results=True, wt=None):
'''Compute Cohen's kappa with variance and equal-zero test
Parameters
----------
table : array_like, 2-Dim
square array with results of two raters, one rater in rows, second
rater in columns
weights : array_like
The interpretation of weights depends on the wt argument.
If both are None, then the simple kappa is computed.
see wt for the case when wt is not None
If weights is two dimensional, then it is directly used as a weight
matrix. For computing the variance of kappa, the maximum of the
weights is assumed to be smaller or equal to one.
TODO: fix conflicting definitions in the 2-Dim case for
wt : {None, str}
If wt and weights are None, then the simple kappa is computed.
If wt is given, but weights is None, then the weights are set to
be [0, 1, 2, ..., k].
If weights is a one-dimensional array, then it is used to construct
the weight matrix given the following options.
wt in ['linear', 'ca' or None] : use linear weights, Cicchetti-Allison
actual weights are linear in the score "weights" difference
wt in ['quadratic', 'fc'] : use linear weights, Fleiss-Cohen
actual weights are squared in the score "weights" difference
wt = 'toeplitz' : weight matrix is constructed as a toeplitz matrix
from the one dimensional weights.
return_results : bool
If True (default), then an instance of KappaResults is returned.
If False, then only kappa is computed and returned.
Returns
-------
results or kappa
If return_results is True (default), then a results instance with all
statistics is returned
If return_results is False, then only kappa is calculated and returned.
Notes
-----
There are two conflicting definitions of the weight matrix, Wikipedia
versus SAS manual. However, the computation are invariant to rescaling
of the weights matrix, so there is no difference in the results.
Weights for 'linear' and 'quadratic' are interpreted as scores for the
categories, the weights in the computation are based on the pairwise
difference between the scores.
Weights for 'toeplitz' are a interpreted as weighted distance. The distance
only depends on how many levels apart two entries in the table are but
not on the levels themselves.
example:
weights = '0, 1, 2, 3' and wt is either linear or toeplitz means that the
weighting only depends on the simple distance of levels.
weights = '0, 0, 1, 1' and wt = 'linear' means that the first two levels
are zero distance apart and the same for the last two levels. This is
the sample as forming two aggregated levels by merging the first two and
the last two levels, respectively.
weights = [0, 1, 2, 3] and wt = 'quadratic' is the same as squaring these
weights and using wt = 'toeplitz'.
References
----------
Wikipedia
SAS Manual
'''
table = np.asarray(table, float) #avoid integer division
agree = np.diag(table).sum()
nobs = table.sum()
probs = table / nobs
freqs = probs #TODO: rename to use freqs instead of probs for observed
probs_diag = np.diag(probs)
freq_row = table.sum(1) / nobs
freq_col = table.sum(0) / nobs
prob_exp = freq_col * freq_row[:, None]
assert np.allclose(prob_exp.sum(), 1)
#print prob_exp.sum()
agree_exp = np.diag(prob_exp).sum() #need for kappa_max
if weights is None and wt is None:
kind = 'Simple'
kappa = (agree / nobs - agree_exp) / (1 - agree_exp)
if return_results:
#variance
term_a = probs_diag * (1 - (freq_row + freq_col) * (1 - kappa))**2
term_a = term_a.sum()
term_b = probs * (freq_col[:, None] + freq_row)**2
d_idx = np.arange(table.shape[0])
term_b[d_idx, d_idx] = 0 #set diagonal to zero
term_b = (1 - kappa)**2 * term_b.sum()
term_c = (kappa - agree_exp * (1-kappa))**2
var_kappa = (term_a + term_b - term_c) / (1 - agree_exp)**2 / nobs
#term_c = freq_col * freq_row[:, None] * (freq_col + freq_row[:,None])
term_c = freq_col * freq_row * (freq_col + freq_row)
var_kappa0 = (agree_exp + agree_exp**2 - term_c.sum())
var_kappa0 /= (1 - agree_exp)**2 * nobs
else:
if weights is None:
weights = np.arange(table.shape[0])
#weights follows the Wikipedia definition, not the SAS, which is 1 -
kind = 'Weighted'
weights = np.asarray(weights, float)
if weights.ndim == 1:
if wt in ['ca', 'linear', None]:
weights = np.abs(weights[:, None] - weights) / \
(weights[-1] - weights[0])
elif wt in ['fc', 'quadratic']:
weights = (weights[:, None] - weights)**2 / \
(weights[-1] - weights[0])**2
elif wt == 'toeplitz':
#assume toeplitz structure
from scipy.linalg import toeplitz
#weights = toeplitz(np.arange(table.shape[0]))
weights = toeplitz(weights)
else:
raise ValueError('wt option is not known')
else:
rows, cols = table.shape
if (table.shape != weights.shape):
raise ValueError('weights are not square')
#this is formula from Wikipedia
kappa = 1 - (weights * table).sum() / nobs / (weights * prob_exp).sum()
#TODO: add var_kappa for weighted version
if return_results:
var_kappa = np.nan
var_kappa0 = np.nan
#switch to SAS manual weights, problem if user specifies weights
#w is negative in some examples,
#but weights is scale invariant in examples and rough check of source
w = 1. - weights
w_row = (freq_col * w).sum(1)
w_col = (freq_row[:, None] * w).sum(0)
agree_wexp = (w * freq_col * freq_row[:, None]).sum()
term_a = freqs * (w - (w_col + w_row[:, None]) * (1 - kappa))**2
fac = 1. / ((1 - agree_wexp)**2 * nobs)
var_kappa = term_a.sum() - (kappa - agree_wexp * (1 - kappa))**2
var_kappa *= fac
freqse = freq_col * freq_row[:, None]
var_kappa0 = (freqse * (w - (w_col + w_row[:, None]))**2).sum()
var_kappa0 -= agree_wexp**2
var_kappa0 *= fac
kappa_max = (np.minimum(freq_row, freq_col).sum() - agree_exp) / \
(1 - agree_exp)
if return_results:
res = KappaResults( kind=kind,
kappa=kappa,
kappa_max=kappa_max,
weights=weights,
var_kappa=var_kappa,
var_kappa0=var_kappa0)
return res
else:
return kappa | Compute Cohen's kappa with variance and equal-zero test
Parameters
----------
table : array_like, 2-Dim
square array with results of two raters, one rater in rows, second
rater in columns
weights : array_like
The interpretation of weights depends on the wt argument.
If both are None, then the simple kappa is computed.
see wt for the case when wt is not None
If weights is two dimensional, then it is directly used as a weight
matrix. For computing the variance of kappa, the maximum of the
weights is assumed to be smaller or equal to one.
TODO: fix conflicting definitions in the 2-Dim case for
wt : {None, str}
If wt and weights are None, then the simple kappa is computed.
If wt is given, but weights is None, then the weights are set to
be [0, 1, 2, ..., k].
If weights is a one-dimensional array, then it is used to construct
the weight matrix given the following options.
wt in ['linear', 'ca' or None] : use linear weights, Cicchetti-Allison
actual weights are linear in the score "weights" difference
wt in ['quadratic', 'fc'] : use linear weights, Fleiss-Cohen
actual weights are squared in the score "weights" difference
wt = 'toeplitz' : weight matrix is constructed as a toeplitz matrix
from the one dimensional weights.
return_results : bool
If True (default), then an instance of KappaResults is returned.
If False, then only kappa is computed and returned.
Returns
-------
results or kappa
If return_results is True (default), then a results instance with all
statistics is returned
If return_results is False, then only kappa is calculated and returned.
Notes
-----
There are two conflicting definitions of the weight matrix, Wikipedia
versus SAS manual. However, the computation are invariant to rescaling
of the weights matrix, so there is no difference in the results.
Weights for 'linear' and 'quadratic' are interpreted as scores for the
categories, the weights in the computation are based on the pairwise
difference between the scores.
Weights for 'toeplitz' are a interpreted as weighted distance. The distance
only depends on how many levels apart two entries in the table are but
not on the levels themselves.
example:
weights = '0, 1, 2, 3' and wt is either linear or toeplitz means that the
weighting only depends on the simple distance of levels.
weights = '0, 0, 1, 1' and wt = 'linear' means that the first two levels
are zero distance apart and the same for the last two levels. This is
the sample as forming two aggregated levels by merging the first two and
the last two levels, respectively.
weights = [0, 1, 2, 3] and wt = 'quadratic' is the same as squaring these
weights and using wt = 'toeplitz'.
References
----------
Wikipedia
SAS Manual | cohens_kappa | python | statsmodels/statsmodels | statsmodels/stats/inter_rater.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/inter_rater.py | BSD-3-Clause |
def test_mvmean(data, mean_null=0, return_results=True):
"""Hotellings test for multivariate mean in one sample
Parameters
----------
data : array_like
data with observations in rows and variables in columns
mean_null : array_like
mean of the multivariate data under the null hypothesis
return_results : bool
If true, then a results instance is returned. If False, then only
the test statistic and pvalue are returned.
Returns
-------
results : instance of a results class with attributes
statistic, pvalue, t2 and df
(statistic, pvalue) : tuple
If return_results is false, then only the test statistic and the
pvalue are returned.
"""
x = np.asarray(data)
nobs, k_vars = x.shape
mean = x.mean(0)
cov = np.cov(x, rowvar=False, ddof=1)
diff = mean - mean_null
t2 = nobs * diff.dot(np.linalg.solve(cov, diff))
factor = (nobs - 1) * k_vars / (nobs - k_vars)
statistic = t2 / factor
df = (k_vars, nobs - k_vars)
pvalue = stats.f.sf(statistic, df[0], df[1])
if return_results:
res = HolderTuple(statistic=statistic,
pvalue=pvalue,
df=df,
t2=t2,
distr="F")
return res
else:
return statistic, pvalue | Hotellings test for multivariate mean in one sample
Parameters
----------
data : array_like
data with observations in rows and variables in columns
mean_null : array_like
mean of the multivariate data under the null hypothesis
return_results : bool
If true, then a results instance is returned. If False, then only
the test statistic and pvalue are returned.
Returns
-------
results : instance of a results class with attributes
statistic, pvalue, t2 and df
(statistic, pvalue) : tuple
If return_results is false, then only the test statistic and the
pvalue are returned. | test_mvmean | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def test_mvmean_2indep(data1, data2):
"""Hotellings test for multivariate mean in two independent samples
The null hypothesis is that both samples have the same mean.
The alternative hypothesis is that means differ.
Parameters
----------
data1 : array_like
first sample data with observations in rows and variables in columns
data2 : array_like
second sample data with observations in rows and variables in columns
Returns
-------
results : instance of a results class with attributes
statistic, pvalue, t2 and df
"""
x1 = array_like(data1, "x1", ndim=2)
x2 = array_like(data2, "x2", ndim=2)
nobs1, k_vars = x1.shape
nobs2, k_vars2 = x2.shape
if k_vars2 != k_vars:
msg = "both samples need to have the same number of columns"
raise ValueError(msg)
mean1 = x1.mean(0)
mean2 = x2.mean(0)
cov1 = np.cov(x1, rowvar=False, ddof=1)
cov2 = np.cov(x2, rowvar=False, ddof=1)
nobs_t = nobs1 + nobs2
combined_cov = ((nobs1 - 1) * cov1 + (nobs2 - 1) * cov2) / (nobs_t - 2)
diff = mean1 - mean2
t2 = (nobs1 * nobs2) / nobs_t * diff @ np.linalg.solve(combined_cov, diff)
factor = ((nobs_t - 2) * k_vars) / (nobs_t - k_vars - 1)
statistic = t2 / factor
df = (k_vars, nobs_t - 1 - k_vars)
pvalue = stats.f.sf(statistic, df[0], df[1])
return HolderTuple(statistic=statistic,
pvalue=pvalue,
df=df,
t2=t2,
distr="F") | Hotellings test for multivariate mean in two independent samples
The null hypothesis is that both samples have the same mean.
The alternative hypothesis is that means differ.
Parameters
----------
data1 : array_like
first sample data with observations in rows and variables in columns
data2 : array_like
second sample data with observations in rows and variables in columns
Returns
-------
results : instance of a results class with attributes
statistic, pvalue, t2 and df | test_mvmean_2indep | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def confint_mvmean(data, lin_transf=None, alpha=0.5, simult=False):
"""Confidence interval for linear transformation of a multivariate mean
Either pointwise or simultaneous confidence intervals are returned.
Parameters
----------
data : array_like
data with observations in rows and variables in columns
lin_transf : array_like or None
The linear transformation or contrast matrix for transforming the
vector of means. If this is None, then the identity matrix is used
which specifies the means themselves.
alpha : float in (0, 1)
confidence level for the confidence interval, commonly used is
alpha=0.05.
simult : bool
If ``simult`` is False (default), then the pointwise confidence
interval is returned.
Otherwise, a simultaneous confidence interval is returned.
Warning: additional simultaneous confidence intervals might be added
and the default for those might change.
Returns
-------
low : ndarray
lower confidence bound on the linear transformed
upp : ndarray
upper confidence bound on the linear transformed
values : ndarray
mean or their linear transformation, center of the confidence region
Notes
-----
Pointwise confidence interval is based on Johnson and Wichern
equation (5-21) page 224.
Simultaneous confidence interval is based on Johnson and Wichern
Result 5.3 page 225.
This looks like Sheffe simultaneous confidence intervals.
Bonferroni corrected simultaneous confidence interval might be added in
future
References
----------
Johnson, Richard A., and Dean W. Wichern. 2007. Applied Multivariate
Statistical Analysis. 6th ed. Upper Saddle River, N.J: Pearson Prentice
Hall.
"""
x = np.asarray(data)
nobs, k_vars = x.shape
if lin_transf is None:
lin_transf = np.eye(k_vars)
mean = x.mean(0)
cov = np.cov(x, rowvar=False, ddof=0)
ci = confint_mvmean_fromstats(mean, cov, nobs, lin_transf=lin_transf,
alpha=alpha, simult=simult)
return ci | Confidence interval for linear transformation of a multivariate mean
Either pointwise or simultaneous confidence intervals are returned.
Parameters
----------
data : array_like
data with observations in rows and variables in columns
lin_transf : array_like or None
The linear transformation or contrast matrix for transforming the
vector of means. If this is None, then the identity matrix is used
which specifies the means themselves.
alpha : float in (0, 1)
confidence level for the confidence interval, commonly used is
alpha=0.05.
simult : bool
If ``simult`` is False (default), then the pointwise confidence
interval is returned.
Otherwise, a simultaneous confidence interval is returned.
Warning: additional simultaneous confidence intervals might be added
and the default for those might change.
Returns
-------
low : ndarray
lower confidence bound on the linear transformed
upp : ndarray
upper confidence bound on the linear transformed
values : ndarray
mean or their linear transformation, center of the confidence region
Notes
-----
Pointwise confidence interval is based on Johnson and Wichern
equation (5-21) page 224.
Simultaneous confidence interval is based on Johnson and Wichern
Result 5.3 page 225.
This looks like Sheffe simultaneous confidence intervals.
Bonferroni corrected simultaneous confidence interval might be added in
future
References
----------
Johnson, Richard A., and Dean W. Wichern. 2007. Applied Multivariate
Statistical Analysis. 6th ed. Upper Saddle River, N.J: Pearson Prentice
Hall. | confint_mvmean | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def confint_mvmean_fromstats(mean, cov, nobs, lin_transf=None, alpha=0.05,
simult=False):
"""Confidence interval for linear transformation of a multivariate mean
Either pointwise or simultaneous confidence intervals are returned.
Data is provided in the form of summary statistics, mean, cov, nobs.
Parameters
----------
mean : ndarray
cov : ndarray
nobs : int
lin_transf : array_like or None
The linear transformation or contrast matrix for transforming the
vector of means. If this is None, then the identity matrix is used
which specifies the means themselves.
alpha : float in (0, 1)
confidence level for the confidence interval, commonly used is
alpha=0.05.
simult : bool
If simult is False (default), then pointwise confidence interval is
returned.
Otherwise, a simultaneous confidence interval is returned.
Warning: additional simultaneous confidence intervals might be added
and the default for those might change.
Notes
-----
Pointwise confidence interval is based on Johnson and Wichern
equation (5-21) page 224.
Simultaneous confidence interval is based on Johnson and Wichern
Result 5.3 page 225.
This looks like Sheffe simultaneous confidence intervals.
Bonferroni corrected simultaneous confidence interval might be added in
future
References
----------
Johnson, Richard A., and Dean W. Wichern. 2007. Applied Multivariate
Statistical Analysis. 6th ed. Upper Saddle River, N.J: Pearson Prentice
Hall.
"""
mean = np.asarray(mean)
cov = np.asarray(cov)
c = np.atleast_2d(lin_transf)
k_vars = len(mean)
if simult is False:
values = c.dot(mean)
quad_form = (c * cov.dot(c.T).T).sum(1)
df = nobs - 1
t_critval = stats.t.isf(alpha / 2, df)
ci_diff = np.sqrt(quad_form / df) * t_critval
low = values - ci_diff
upp = values + ci_diff
else:
values = c.dot(mean)
quad_form = (c * cov.dot(c.T).T).sum(1)
factor = (nobs - 1) * k_vars / (nobs - k_vars) / nobs
df = (k_vars, nobs - k_vars)
f_critval = stats.f.isf(alpha, df[0], df[1])
ci_diff = np.sqrt(factor * quad_form * f_critval)
low = values - ci_diff
upp = values + ci_diff
return low, upp, values # , (f_critval, factor, quad_form, df) | Confidence interval for linear transformation of a multivariate mean
Either pointwise or simultaneous confidence intervals are returned.
Data is provided in the form of summary statistics, mean, cov, nobs.
Parameters
----------
mean : ndarray
cov : ndarray
nobs : int
lin_transf : array_like or None
The linear transformation or contrast matrix for transforming the
vector of means. If this is None, then the identity matrix is used
which specifies the means themselves.
alpha : float in (0, 1)
confidence level for the confidence interval, commonly used is
alpha=0.05.
simult : bool
If simult is False (default), then pointwise confidence interval is
returned.
Otherwise, a simultaneous confidence interval is returned.
Warning: additional simultaneous confidence intervals might be added
and the default for those might change.
Notes
-----
Pointwise confidence interval is based on Johnson and Wichern
equation (5-21) page 224.
Simultaneous confidence interval is based on Johnson and Wichern
Result 5.3 page 225.
This looks like Sheffe simultaneous confidence intervals.
Bonferroni corrected simultaneous confidence interval might be added in
future
References
----------
Johnson, Richard A., and Dean W. Wichern. 2007. Applied Multivariate
Statistical Analysis. 6th ed. Upper Saddle River, N.J: Pearson Prentice
Hall. | confint_mvmean_fromstats | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def test_cov(cov, nobs, cov_null):
"""One sample hypothesis test for covariance equal to null covariance
The Null hypothesis is that cov = cov_null, against the alternative that
it is not equal to cov_null
Parameters
----------
cov : array_like
Covariance matrix of the data, estimated with denominator ``(N - 1)``,
i.e. `ddof=1`.
nobs : int
number of observations used in the estimation of the covariance
cov_null : nd_array
covariance under the null hypothesis
Returns
-------
res : instance of HolderTuple
results with ``statistic, pvalue`` and other attributes like ``df``
References
----------
Bartlett, M. S. 1954. “A Note on the Multiplying Factors for Various Χ2
Approximations.” Journal of the Royal Statistical Society. Series B
(Methodological) 16 (2): 296–98.
Rencher, Alvin C., and William F. Christensen. 2012. Methods of
Multivariate Analysis: Rencher/Methods. Wiley Series in Probability and
Statistics. Hoboken, NJ, USA: John Wiley & Sons, Inc.
https://doi.org/10.1002/9781118391686.
StataCorp, L. P. Stata Multivariate Statistics: Reference Manual.
Stata Press Publication.
"""
# using Stata formulas where cov_sample use nobs in denominator
# Bartlett 1954 has fewer terms
S = np.asarray(cov) * (nobs - 1) / nobs
S0 = np.asarray(cov_null)
k = cov.shape[0]
n = nobs
fact = nobs - 1.
fact *= 1 - (2 * k + 1 - 2 / (k + 1)) / (6 * (n - 1) - 1)
fact2 = _logdet(S0) - _logdet(n / (n - 1) * S)
fact2 += np.trace(n / (n - 1) * np.linalg.solve(S0, S)) - k
statistic = fact * fact2
df = k * (k + 1) / 2
pvalue = stats.chi2.sf(statistic, df)
return HolderTuple(statistic=statistic,
pvalue=pvalue,
df=df,
distr="chi2",
null="equal value",
cov_null=cov_null
) | One sample hypothesis test for covariance equal to null covariance
The Null hypothesis is that cov = cov_null, against the alternative that
it is not equal to cov_null
Parameters
----------
cov : array_like
Covariance matrix of the data, estimated with denominator ``(N - 1)``,
i.e. `ddof=1`.
nobs : int
number of observations used in the estimation of the covariance
cov_null : nd_array
covariance under the null hypothesis
Returns
-------
res : instance of HolderTuple
results with ``statistic, pvalue`` and other attributes like ``df``
References
----------
Bartlett, M. S. 1954. “A Note on the Multiplying Factors for Various Χ2
Approximations.” Journal of the Royal Statistical Society. Series B
(Methodological) 16 (2): 296–98.
Rencher, Alvin C., and William F. Christensen. 2012. Methods of
Multivariate Analysis: Rencher/Methods. Wiley Series in Probability and
Statistics. Hoboken, NJ, USA: John Wiley & Sons, Inc.
https://doi.org/10.1002/9781118391686.
StataCorp, L. P. Stata Multivariate Statistics: Reference Manual.
Stata Press Publication. | test_cov | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def _get_blocks(mat, block_len):
"""get diagonal blocks from matrix
"""
k = len(mat)
idx = np.cumsum(block_len)
if idx[-1] == k:
idx = idx[:-1]
elif idx[-1] > k:
raise ValueError("sum of block_len larger than shape of mat")
else:
# allow one missing block that is the remainder
pass
idx_blocks = np.split(np.arange(k), idx)
blocks = []
for ii in idx_blocks:
blocks.append(mat[ii[:, None], ii])
return blocks, idx_blocks | get diagonal blocks from matrix | _get_blocks | python | statsmodels/statsmodels | statsmodels/stats/multivariate.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate.py | BSD-3-Clause |
def gof_chisquare_discrete(distfn, arg, rvs, alpha, msg):
'''perform chisquare test for random sample of a discrete distribution
Parameters
----------
distname : str
name of distribution function
arg : sequence
parameters of distribution
alpha : float
significance level, threshold for p-value
Returns
-------
result : bool
0 if test passes, 1 if test fails
Notes
-----
originally written for scipy.stats test suite,
still needs to be checked for standalone usage, insufficient input checking
may not run yet (after copy/paste)
refactor: maybe a class, check returns, or separate binning from
test results
'''
# define parameters for test
## n=2000
n = len(rvs)
nsupp = 20
wsupp = 1.0/nsupp
## distfn = getattr(stats, distname)
## np.random.seed(9765456)
## rvs = distfn.rvs(size=n,*arg)
# construct intervals with minimum mass 1/nsupp
# intervalls are left-half-open as in a cdf difference
distsupport = lrange(max(distfn.a, -1000), min(distfn.b, 1000) + 1)
last = 0
distsupp = [max(distfn.a, -1000)]
distmass = []
for ii in distsupport:
current = distfn.cdf(ii,*arg)
if current - last >= wsupp-1e-14:
distsupp.append(ii)
distmass.append(current - last)
last = current
if current > (1-wsupp):
break
if distsupp[-1] < distfn.b:
distsupp.append(distfn.b)
distmass.append(1-last)
distsupp = np.array(distsupp)
distmass = np.array(distmass)
# convert intervals to right-half-open as required by histogram
histsupp = distsupp+1e-8
histsupp[0] = distfn.a
# find sample frequencies and perform chisquare test
#TODO: move to compatibility.py
freq, hsupp = np.histogram(rvs,histsupp)
# cdfs = distfn.cdf(distsupp,*arg)
(chis,pval) = stats.chisquare(np.array(freq),n*distmass)
return chis, pval, (pval > alpha), 'chisquare - test for %s' \
'at arg = %s with pval = %s' % (msg,str(arg),str(pval)) | perform chisquare test for random sample of a discrete distribution
Parameters
----------
distname : str
name of distribution function
arg : sequence
parameters of distribution
alpha : float
significance level, threshold for p-value
Returns
-------
result : bool
0 if test passes, 1 if test fails
Notes
-----
originally written for scipy.stats test suite,
still needs to be checked for standalone usage, insufficient input checking
may not run yet (after copy/paste)
refactor: maybe a class, check returns, or separate binning from
test results | gof_chisquare_discrete | python | statsmodels/statsmodels | statsmodels/stats/gof.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/gof.py | BSD-3-Clause |
def gof_binning_discrete(rvs, distfn, arg, nsupp=20):
'''get bins for chisquare type gof tests for a discrete distribution
Parameters
----------
rvs : ndarray
sample data
distname : str
name of distribution function
arg : sequence
parameters of distribution
nsupp : int
number of bins. The algorithm tries to find bins with equal weights.
depending on the distribution, the actual number of bins can be smaller.
Returns
-------
freq : ndarray
empirical frequencies for sample; not normalized, adds up to sample size
expfreq : ndarray
theoretical frequencies according to distribution
histsupp : ndarray
bin boundaries for histogram, (added 1e-8 for numerical robustness)
Notes
-----
The results can be used for a chisquare test ::
(chis,pval) = stats.chisquare(freq, expfreq)
originally written for scipy.stats test suite,
still needs to be checked for standalone usage, insufficient input checking
may not run yet (after copy/paste)
refactor: maybe a class, check returns, or separate binning from
test results
todo :
optimal number of bins ? (check easyfit),
recommendation in literature at least 5 expected observations in each bin
'''
# define parameters for test
## n=2000
n = len(rvs)
wsupp = 1.0/nsupp
## distfn = getattr(stats, distname)
## np.random.seed(9765456)
## rvs = distfn.rvs(size=n,*arg)
# construct intervals with minimum mass 1/nsupp
# intervalls are left-half-open as in a cdf difference
distsupport = lrange(max(distfn.a, -1000), min(distfn.b, 1000) + 1)
last = 0
distsupp = [max(distfn.a, -1000)]
distmass = []
for ii in distsupport:
current = distfn.cdf(ii,*arg)
if current - last >= wsupp-1e-14:
distsupp.append(ii)
distmass.append(current - last)
last = current
if current > (1-wsupp):
break
if distsupp[-1] < distfn.b:
distsupp.append(distfn.b)
distmass.append(1-last)
distsupp = np.array(distsupp)
distmass = np.array(distmass)
# convert intervals to right-half-open as required by histogram
histsupp = distsupp+1e-8
histsupp[0] = distfn.a
# find sample frequencies and perform chisquare test
freq,hsupp = np.histogram(rvs,histsupp)
#freq,hsupp = np.histogram(rvs,histsupp,new=True)
distfn.cdf(distsupp,*arg)
return np.array(freq), n*distmass, histsupp | get bins for chisquare type gof tests for a discrete distribution
Parameters
----------
rvs : ndarray
sample data
distname : str
name of distribution function
arg : sequence
parameters of distribution
nsupp : int
number of bins. The algorithm tries to find bins with equal weights.
depending on the distribution, the actual number of bins can be smaller.
Returns
-------
freq : ndarray
empirical frequencies for sample; not normalized, adds up to sample size
expfreq : ndarray
theoretical frequencies according to distribution
histsupp : ndarray
bin boundaries for histogram, (added 1e-8 for numerical robustness)
Notes
-----
The results can be used for a chisquare test ::
(chis,pval) = stats.chisquare(freq, expfreq)
originally written for scipy.stats test suite,
still needs to be checked for standalone usage, insufficient input checking
may not run yet (after copy/paste)
refactor: maybe a class, check returns, or separate binning from
test results
todo :
optimal number of bins ? (check easyfit),
recommendation in literature at least 5 expected observations in each bin | gof_binning_discrete | python | statsmodels/statsmodels | statsmodels/stats/gof.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/gof.py | BSD-3-Clause |
def chisquare(f_obs, f_exp=None, value=0, ddof=0, return_basic=True):
'''chisquare goodness-of-fit test
The null hypothesis is that the distance between the expected distribution
and the observed frequencies is ``value``. The alternative hypothesis is
that the distance is larger than ``value``. ``value`` is normalized in
terms of effect size.
The standard chisquare test has the null hypothesis that ``value=0``, that
is the distributions are the same.
Notes
-----
The case with value greater than zero is similar to an equivalence test,
that the exact null hypothesis is replaced by an approximate hypothesis.
However, TOST "reverses" null and alternative hypothesis, while here the
alternative hypothesis is that the distance (divergence) is larger than a
threshold.
References
----------
McLaren, ...
Drost,...
See Also
--------
powerdiscrepancy
scipy.stats.chisquare
'''
f_obs = np.asarray(f_obs)
n_bins = len(f_obs)
nobs = f_obs.sum(0)
if f_exp is None:
# uniform distribution
f_exp = np.empty(n_bins, float)
f_exp.fill(nobs / float(n_bins))
f_exp = np.asarray(f_exp, float)
chisq = ((f_obs - f_exp)**2 / f_exp).sum(0)
if value == 0:
pvalue = stats.chi2.sf(chisq, n_bins - 1 - ddof)
else:
pvalue = stats.ncx2.sf(chisq, n_bins - 1 - ddof, value**2 * nobs)
if return_basic:
return chisq, pvalue
else:
return chisq, pvalue #TODO: replace with TestResults | chisquare goodness-of-fit test
The null hypothesis is that the distance between the expected distribution
and the observed frequencies is ``value``. The alternative hypothesis is
that the distance is larger than ``value``. ``value`` is normalized in
terms of effect size.
The standard chisquare test has the null hypothesis that ``value=0``, that
is the distributions are the same.
Notes
-----
The case with value greater than zero is similar to an equivalence test,
that the exact null hypothesis is replaced by an approximate hypothesis.
However, TOST "reverses" null and alternative hypothesis, while here the
alternative hypothesis is that the distance (divergence) is larger than a
threshold.
References
----------
McLaren, ...
Drost,...
See Also
--------
powerdiscrepancy
scipy.stats.chisquare | chisquare | python | statsmodels/statsmodels | statsmodels/stats/gof.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/gof.py | BSD-3-Clause |
def chisquare_power(effect_size, nobs, n_bins, alpha=0.05, ddof=0):
'''power of chisquare goodness of fit test
effect size is sqrt of chisquare statistic divided by nobs
Parameters
----------
effect_size : float
This is the deviation from the Null of the normalized chi_square
statistic. This follows Cohen's definition (sqrt).
nobs : int or float
number of observations
n_bins : int (or float)
number of bins, or points in the discrete distribution
alpha : float in (0,1)
significance level of the test, default alpha=0.05
Returns
-------
power : float
power of the test at given significance level at effect size
Notes
-----
This function also works vectorized if all arguments broadcast.
This can also be used to calculate the power for power divergence test.
However, for the range of more extreme values of the power divergence
parameter, this power is not a very good approximation for samples of
small to medium size (Drost et al. 1989)
References
----------
Drost, ...
See Also
--------
chisquare_effectsize
statsmodels.stats.GofChisquarePower
'''
crit = stats.chi2.isf(alpha, n_bins - 1 - ddof)
power = stats.ncx2.sf(crit, n_bins - 1 - ddof, effect_size**2 * nobs)
return power | power of chisquare goodness of fit test
effect size is sqrt of chisquare statistic divided by nobs
Parameters
----------
effect_size : float
This is the deviation from the Null of the normalized chi_square
statistic. This follows Cohen's definition (sqrt).
nobs : int or float
number of observations
n_bins : int (or float)
number of bins, or points in the discrete distribution
alpha : float in (0,1)
significance level of the test, default alpha=0.05
Returns
-------
power : float
power of the test at given significance level at effect size
Notes
-----
This function also works vectorized if all arguments broadcast.
This can also be used to calculate the power for power divergence test.
However, for the range of more extreme values of the power divergence
parameter, this power is not a very good approximation for samples of
small to medium size (Drost et al. 1989)
References
----------
Drost, ...
See Also
--------
chisquare_effectsize
statsmodels.stats.GofChisquarePower | chisquare_power | python | statsmodels/statsmodels | statsmodels/stats/gof.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/gof.py | BSD-3-Clause |
def chisquare_effectsize(probs0, probs1, correction=None, cohen=True, axis=0):
'''effect size for a chisquare goodness-of-fit test
Parameters
----------
probs0 : array_like
probabilities or cell frequencies under the Null hypothesis
probs1 : array_like
probabilities or cell frequencies under the Alternative hypothesis
probs0 and probs1 need to have the same length in the ``axis`` dimension.
and broadcast in the other dimensions
Both probs0 and probs1 are normalized to add to one (in the ``axis``
dimension).
correction : None or tuple
If None, then the effect size is the chisquare statistic divide by
the number of observations.
If the correction is a tuple (nobs, df), then the effectsize is
corrected to have less bias and a smaller variance. However, the
correction can make the effectsize negative. In that case, the
effectsize is set to zero.
Pederson and Johnson (1990) as referenced in McLaren et all. (1994)
cohen : bool
If True, then the square root is returned as in the definition of the
effect size by Cohen (1977), If False, then the original effect size
is returned.
axis : int
If the probability arrays broadcast to more than 1 dimension, then
this is the axis over which the sums are taken.
Returns
-------
effectsize : float
effect size of chisquare test
'''
probs0 = np.asarray(probs0, float)
probs1 = np.asarray(probs1, float)
probs0 = probs0 / probs0.sum(axis)
probs1 = probs1 / probs1.sum(axis)
d2 = ((probs1 - probs0)**2 / probs0).sum(axis)
if correction is not None:
nobs, df = correction
diff = ((probs1 - probs0) / probs0).sum(axis)
d2 = np.maximum((d2 * nobs - diff - df) / (nobs - 1.), 0)
if cohen:
return np.sqrt(d2)
else:
return d2 | effect size for a chisquare goodness-of-fit test
Parameters
----------
probs0 : array_like
probabilities or cell frequencies under the Null hypothesis
probs1 : array_like
probabilities or cell frequencies under the Alternative hypothesis
probs0 and probs1 need to have the same length in the ``axis`` dimension.
and broadcast in the other dimensions
Both probs0 and probs1 are normalized to add to one (in the ``axis``
dimension).
correction : None or tuple
If None, then the effect size is the chisquare statistic divide by
the number of observations.
If the correction is a tuple (nobs, df), then the effectsize is
corrected to have less bias and a smaller variance. However, the
correction can make the effectsize negative. In that case, the
effectsize is set to zero.
Pederson and Johnson (1990) as referenced in McLaren et all. (1994)
cohen : bool
If True, then the square root is returned as in the definition of the
effect size by Cohen (1977), If False, then the original effect size
is returned.
axis : int
If the probability arrays broadcast to more than 1 dimension, then
this is the axis over which the sums are taken.
Returns
-------
effectsize : float
effect size of chisquare test | chisquare_effectsize | python | statsmodels/statsmodels | statsmodels/stats/gof.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/gof.py | BSD-3-Clause |
def pval_corrected(self, method=None):
'''p-values corrected for multiple testing problem
This uses the default p-value correction of the instance stored in
``self.multitest_method`` if method is None.
'''
import statsmodels.stats.multitest as smt
if method is None:
method = self.multitest_method
# TODO: breaks with method=None
return smt.multipletests(self.pvals_raw, method=method)[1] | p-values corrected for multiple testing problem
This uses the default p-value correction of the instance stored in
``self.multitest_method`` if method is None. | pval_corrected | python | statsmodels/statsmodels | statsmodels/stats/base.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/base.py | BSD-3-Clause |
def pval_table(self):
'''create a (n_levels, n_levels) array with corrected p_values
this needs to improve, similar to R pairwise output
'''
k = self.n_levels
pvals_mat = np.zeros((k, k))
# if we do not assume we have all pairs
pvals_mat[lzip(*self.all_pairs)] = self.pval_corrected()
return pvals_mat | create a (n_levels, n_levels) array with corrected p_values
this needs to improve, similar to R pairwise output | pval_table | python | statsmodels/statsmodels | statsmodels/stats/base.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/base.py | BSD-3-Clause |
def summary(self):
'''returns text summarizing the results
uses the default pvalue correction of the instance stored in
``self.multitest_method``
'''
import statsmodels.stats.multitest as smt
maxlevel = max(len(ss) for ss in self.all_pairs_names)
text = ('Corrected p-values using %s p-value correction\n\n'
% smt.multitest_methods_names[self.multitest_method])
text += 'Pairs' + (' ' * (maxlevel - 5 + 1)) + 'p-values\n'
text += '\n'.join(f'{pairs} {pv:6.4g}' for (pairs, pv) in
zip(self.all_pairs_names, self.pval_corrected()))
return text | returns text summarizing the results
uses the default pvalue correction of the instance stored in
``self.multitest_method`` | summary | python | statsmodels/statsmodels | statsmodels/stats/base.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/base.py | BSD-3-Clause |
def dispersion_poisson(results):
"""Score/LM type tests for Poisson variance assumptions
.. deprecated:: 0.14
dispersion_poisson moved to discrete._diagnostic_count
Null Hypothesis is
H0: var(y) = E(y) and assuming E(y) is correctly specified
H1: var(y) ~= E(y)
The tests are based on the constrained model, i.e. the Poisson model.
The tests differ in their assumed alternatives, and in their maintained
assumptions.
Parameters
----------
results : Poisson results instance
This can be a results instance for either a discrete Poisson or a GLM
with family Poisson.
Returns
-------
res : ndarray, shape (7, 2)
each row contains the test statistic and p-value for one of the 7 tests
computed here.
description : 2-D list of strings
Each test has two strings a descriptive name and a string for the
alternative hypothesis.
"""
msg = (
'dispersion_poisson here is deprecated, use the version in '
'discrete._diagnostic_count'
)
warnings.warn(msg, FutureWarning)
from statsmodels.discrete._diagnostics_count import test_poisson_dispersion
return test_poisson_dispersion(results, _old=True) | Score/LM type tests for Poisson variance assumptions
.. deprecated:: 0.14
dispersion_poisson moved to discrete._diagnostic_count
Null Hypothesis is
H0: var(y) = E(y) and assuming E(y) is correctly specified
H1: var(y) ~= E(y)
The tests are based on the constrained model, i.e. the Poisson model.
The tests differ in their assumed alternatives, and in their maintained
assumptions.
Parameters
----------
results : Poisson results instance
This can be a results instance for either a discrete Poisson or a GLM
with family Poisson.
Returns
-------
res : ndarray, shape (7, 2)
each row contains the test statistic and p-value for one of the 7 tests
computed here.
description : 2-D list of strings
Each test has two strings a descriptive name and a string for the
alternative hypothesis. | dispersion_poisson | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def dispersion_poisson_generic(results, exog_new_test, exog_new_control=None,
include_score=False, use_endog=True,
cov_type='HC3', cov_kwds=None, use_t=False):
"""A variable addition test for the variance function
.. deprecated:: 0.14
dispersion_poisson_generic moved to discrete._diagnostic_count
This uses an artificial regression to calculate a variant of an LM or
generalized score test for the specification of the variance assumption
in a Poisson model. The performed test is a Wald test on the coefficients
of the `exog_new_test`.
Warning: insufficiently tested, especially for options
"""
msg = (
'dispersion_poisson_generic here is deprecated, use the version in '
'discrete._diagnostic_count'
)
warnings.warn(msg, FutureWarning)
from statsmodels.discrete._diagnostics_count import (
_test_poisson_dispersion_generic,
)
res_test = _test_poisson_dispersion_generic(
results, exog_new_test, exog_new_control= exog_new_control,
include_score=include_score, use_endog=use_endog,
cov_type=cov_type, cov_kwds=cov_kwds, use_t=use_t,
)
return res_test | A variable addition test for the variance function
.. deprecated:: 0.14
dispersion_poisson_generic moved to discrete._diagnostic_count
This uses an artificial regression to calculate a variant of an LM or
generalized score test for the specification of the variance assumption
in a Poisson model. The performed test is a Wald test on the coefficients
of the `exog_new_test`.
Warning: insufficiently tested, especially for options | dispersion_poisson_generic | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def lm_test_glm(result, exog_extra, mean_deriv=None):
'''score/lagrange multiplier test for GLM
Wooldridge procedure for test of mean function in GLM
Parameters
----------
results : GLMResults instance
results instance with the constrained model
exog_extra : ndarray or None
additional exogenous variables for variable addition test
This can be set to None if mean_deriv is provided.
mean_deriv : None or ndarray
Extra moment condition that correspond to the partial derivative of
a mean function with respect to some parameters.
Returns
-------
test_results : Results instance
The results instance has the following attributes which are score
statistic and p-value for 3 versions of the score test.
c1, pval1 : nonrobust score_test results
c2, pval2 : score test results robust to over or under dispersion
c3, pval3 : score test results fully robust to any heteroscedasticity
The test results instance also has a simple summary method.
Notes
-----
TODO: add `df` to results and make df detection more robust
This implements the auxiliary regression procedure of Wooldridge,
implemented based on the presentation in chapter 8 in Handbook of
Applied Econometrics 2.
References
----------
Wooldridge, Jeffrey M. 1997. “Quasi-Likelihood Methods for Count Data.”
Handbook of Applied Econometrics 2: 352–406.
and other articles and text book by Wooldridge
'''
if hasattr(result, '_result'):
res = result._result
else:
res = result
mod = result.model
nobs = mod.endog.shape[0]
#mean_func = mod.family.link.inverse
dlinkinv = mod.family.link.inverse_deriv
# derivative of mean function w.r.t. beta (linear params)
def dm(x, linpred):
return dlinkinv(linpred)[:,None] * x
var_func = mod.family.variance
x = result.model.exog
x2 = exog_extra
# test omitted
try:
lin_pred = res.predict(which="linear")
except TypeError:
# TODO: Standardized to which="linear" and remove linear kwarg
lin_pred = res.predict(linear=True)
dm_incl = dm(x, lin_pred)
if x2 is not None:
dm_excl = dm(x2, lin_pred)
if mean_deriv is not None:
# allow both and stack
dm_excl = np.column_stack((dm_excl, mean_deriv))
elif mean_deriv is not None:
dm_excl = mean_deriv
else:
raise ValueError('either exog_extra or mean_deriv have to be provided')
# TODO check for rank or redundant, note OLS calculates the rank
k_constraint = dm_excl.shape[1]
fittedvalues = res.predict() # discrete has linpred instead of mean
v = var_func(fittedvalues)
std = np.sqrt(v)
res_ols1 = OLS(res.resid_response / std, np.column_stack((dm_incl, dm_excl)) / std[:, None]).fit()
# case: nonrobust assumes variance implied by distribution is correct
c1 = res_ols1.ess
pval1 = stats.chi2.sf(c1, k_constraint)
#print c1, stats.chi2.sf(c1, 2)
# case: robust to dispersion
c2 = nobs * res_ols1.rsquared
pval2 = stats.chi2.sf(c2, k_constraint)
#print c2, stats.chi2.sf(c2, 2)
# case: robust to heteroscedasticity
from statsmodels.stats.multivariate_tools import partial_project
pp = partial_project(dm_excl / std[:,None], dm_incl / std[:,None])
resid_p = res.resid_response / std
res_ols3 = OLS(np.ones(nobs), pp.resid * resid_p[:,None]).fit()
#c3 = nobs * res_ols3.rsquared # this is Wooldridge
c3b = res_ols3.ess # simpler if endog is ones
pval3 = stats.chi2.sf(c3b, k_constraint)
tres = TestResults(c1=c1, pval1=pval1,
c2=c2, pval2=pval2,
c3=c3b, pval3=pval3)
return tres | score/lagrange multiplier test for GLM
Wooldridge procedure for test of mean function in GLM
Parameters
----------
results : GLMResults instance
results instance with the constrained model
exog_extra : ndarray or None
additional exogenous variables for variable addition test
This can be set to None if mean_deriv is provided.
mean_deriv : None or ndarray
Extra moment condition that correspond to the partial derivative of
a mean function with respect to some parameters.
Returns
-------
test_results : Results instance
The results instance has the following attributes which are score
statistic and p-value for 3 versions of the score test.
c1, pval1 : nonrobust score_test results
c2, pval2 : score test results robust to over or under dispersion
c3, pval3 : score test results fully robust to any heteroscedasticity
The test results instance also has a simple summary method.
Notes
-----
TODO: add `df` to results and make df detection more robust
This implements the auxiliary regression procedure of Wooldridge,
implemented based on the presentation in chapter 8 in Handbook of
Applied Econometrics 2.
References
----------
Wooldridge, Jeffrey M. 1997. “Quasi-Likelihood Methods for Count Data.”
Handbook of Applied Econometrics 2: 352–406.
and other articles and text book by Wooldridge | lm_test_glm | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def cm_test_robust(resid, resid_deriv, instruments, weights=1):
'''score/lagrange multiplier of Wooldridge
generic version of Wooldridge procedure for test of conditional moments
Limitation: This version allows only for one unconditional moment
restriction, i.e. resid is scalar for each observation.
Another limitation is that it assumes independent observations, no
correlation in residuals and weights cannot be replaced by cross-observation
whitening.
Parameters
----------
resid : ndarray, (nobs, )
conditional moment restriction, E(r | x, params) = 0
resid_deriv : ndarray, (nobs, k_params)
derivative of conditional moment restriction with respect to parameters
instruments : ndarray, (nobs, k_instruments)
indicator variables of Wooldridge, multiplies the conditional momen
restriction
weights : ndarray
This is a weights function as used in WLS. The moment
restrictions are multiplied by weights. This corresponds to the
inverse of the variance in a heteroskedastic model.
Returns
-------
test_results : Results instance
??? TODO
Notes
-----
This implements the auxiliary regression procedure of Wooldridge,
implemented based on procedure 2.1 in Wooldridge 1990.
Wooldridge allows for multivariate conditional moments (`resid`)
TODO: check dimensions for multivariate case for extension
References
----------
Wooldridge
Wooldridge
and more Wooldridge
'''
# notation: Wooldridge uses too mamny Greek letters
# instruments is capital lambda
# resid is small phi
# resid_deriv is capital phi
# weights is C
nobs = resid.shape[0]
from statsmodels.stats.multivariate_tools import partial_project
w_sqrt = np.sqrt(weights)
if np.size(weights) > 1:
w_sqrt = w_sqrt[:,None]
pp = partial_project(instruments * w_sqrt, resid_deriv * w_sqrt)
mom_resid = pp.resid
moms_test = mom_resid * resid[:, None] * w_sqrt
# we get this here in case we extend resid to be more than 1-D
k_constraint = moms_test.shape[1]
# use OPG variance as in Wooldridge 1990. This might generalize
cov = moms_test.T.dot(moms_test)
diff = moms_test.sum(0)
# see Wooldridge last page in appendix
stat = diff.dot(np.linalg.solve(cov, diff))
# for checking, this corresponds to nobs * rsquared of auxiliary regression
stat2 = OLS(np.ones(nobs), moms_test).fit().ess
pval = stats.chi2.sf(stat, k_constraint)
return stat, pval, stat2 | score/lagrange multiplier of Wooldridge
generic version of Wooldridge procedure for test of conditional moments
Limitation: This version allows only for one unconditional moment
restriction, i.e. resid is scalar for each observation.
Another limitation is that it assumes independent observations, no
correlation in residuals and weights cannot be replaced by cross-observation
whitening.
Parameters
----------
resid : ndarray, (nobs, )
conditional moment restriction, E(r | x, params) = 0
resid_deriv : ndarray, (nobs, k_params)
derivative of conditional moment restriction with respect to parameters
instruments : ndarray, (nobs, k_instruments)
indicator variables of Wooldridge, multiplies the conditional momen
restriction
weights : ndarray
This is a weights function as used in WLS. The moment
restrictions are multiplied by weights. This corresponds to the
inverse of the variance in a heteroskedastic model.
Returns
-------
test_results : Results instance
??? TODO
Notes
-----
This implements the auxiliary regression procedure of Wooldridge,
implemented based on procedure 2.1 in Wooldridge 1990.
Wooldridge allows for multivariate conditional moments (`resid`)
TODO: check dimensions for multivariate case for extension
References
----------
Wooldridge
Wooldridge
and more Wooldridge | cm_test_robust | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def lm_robust(score, constraint_matrix, score_deriv_inv, cov_score,
cov_params=None):
'''general formula for score/LM test
generalized score or lagrange multiplier test for implicit constraints
`r(params) = 0`, with gradient `R = d r / d params`
linear constraints are given by `R params - q = 0`
It is assumed that all arrays are evaluated at the constrained estimates.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
constraint_matrix R : ndarray
Linear restriction matrix or Jacobian of nonlinear constraints
hessian_inv, Ainv : ndarray, symmetric, square
inverse of second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
cov_params V : ndarray, symmetric, square
covariance of full parameter vector evaluated at constrained parameter
estimate. This can be specified instead of cov_score B.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
Notes
-----
'''
# shorthand alias
R, Ainv, B, V = constraint_matrix, score_deriv_inv, cov_score, cov_params
tmp = R.dot(Ainv)
wscore = tmp.dot(score) # C Ainv score
if B is None and V is None:
# only Ainv is given, so we assume information matrix identity holds
# computational short cut, should be same if Ainv == inv(B)
lm_stat = score.dot(Ainv.dot(score))
else:
# information matrix identity does not hold
if V is None:
inner = tmp.dot(B).dot(tmp.T)
else:
inner = R.dot(V).dot(R.T)
#lm_stat2 = wscore.dot(np.linalg.pinv(inner).dot(wscore))
# Let's assume inner is invertible, TODO: check if usecase for pinv exists
lm_stat = wscore.dot(np.linalg.solve(inner, wscore))
return lm_stat#, lm_stat2 | general formula for score/LM test
generalized score or lagrange multiplier test for implicit constraints
`r(params) = 0`, with gradient `R = d r / d params`
linear constraints are given by `R params - q = 0`
It is assumed that all arrays are evaluated at the constrained estimates.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
constraint_matrix R : ndarray
Linear restriction matrix or Jacobian of nonlinear constraints
hessian_inv, Ainv : ndarray, symmetric, square
inverse of second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
cov_params V : ndarray, symmetric, square
covariance of full parameter vector evaluated at constrained parameter
estimate. This can be specified instead of cov_score B.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
Notes
----- | lm_robust | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def lm_robust_subset(score, k_constraints, score_deriv_inv, cov_score):
'''general formula for score/LM test
generalized score or lagrange multiplier test for constraints on a subset
of parameters
`params_1 = value`, where params_1 is a subset of the unconstrained
parameter vector.
It is assumed that all arrays are evaluated at the constrained estimates.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
k_constraint : int
number of constraints
score_deriv_inv : ndarray, symmetric, square
inverse of second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
not cov_params V : ndarray, symmetric, square
covariance of full parameter vector evaluated at constrained parameter
estimate. This can be specified instead of cov_score B.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
The implementation is based on Boos 1992 section 4.1. The same derivation
is also in other articles and in text books.
'''
# Notation in Boos
# score `S = sum (s_i)
# score_obs `s_i`
# score_deriv `I` is derivative of score (hessian)
# `D` is covariance matrix of score, OPG product given independent observations
#k_params = len(score)
# Note: I reverse order between constraint and unconstrained compared to Boos
# submatrices of score_deriv/hessian
# these are I22 and I12 in Boos
#h_uu = score_deriv[-k_constraints:, -k_constraints:]
h_uu = score_deriv_inv[:-k_constraints, :-k_constraints]
h_cu = score_deriv_inv[-k_constraints:, :-k_constraints]
# TODO: pinv or solve ?
tmp_proj = h_cu.dot(np.linalg.inv(h_uu))
tmp = np.column_stack((-tmp_proj, np.eye(k_constraints))) #, tmp_proj))
cov_score_constraints = tmp.dot(cov_score.dot(tmp.T))
#lm_stat2 = wscore.dot(np.linalg.pinv(inner).dot(wscore))
# Let's assume inner is invertible, TODO: check if usecase for pinv exists
lm_stat = score.dot(np.linalg.solve(cov_score_constraints, score))
pval = stats.chi2.sf(lm_stat, k_constraints)
# # check second calculation Boos referencing Kent 1982 and Engle 1984
# # we can use this when robust_cov_params of full model is available
# #h_inv = np.linalg.inv(score_deriv)
# hinv = score_deriv_inv
# v = h_inv.dot(cov_score.dot(h_inv)) # this is robust cov_params
# v_cc = v[:k_constraints, :k_constraints]
# h_cc = score_deriv[:k_constraints, :k_constraints]
# # brute force calculation:
# h_resid_cu = h_cc - h_cu.dot(np.linalg.solve(h_uu, h_cu))
# cov_s_c = h_resid_cu.dot(v_cc.dot(h_resid_cu))
# diff = np.max(np.abs(cov_s_c - cov_score_constraints))
return lm_stat, pval #, lm_stat2 | general formula for score/LM test
generalized score or lagrange multiplier test for constraints on a subset
of parameters
`params_1 = value`, where params_1 is a subset of the unconstrained
parameter vector.
It is assumed that all arrays are evaluated at the constrained estimates.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
k_constraint : int
number of constraints
score_deriv_inv : ndarray, symmetric, square
inverse of second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
not cov_params V : ndarray, symmetric, square
covariance of full parameter vector evaluated at constrained parameter
estimate. This can be specified instead of cov_score B.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
The implementation is based on Boos 1992 section 4.1. The same derivation
is also in other articles and in text books. | lm_robust_subset | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def lm_robust_subset_parts(score, k_constraints,
score_deriv_uu, score_deriv_cu,
cov_score_cc, cov_score_cu, cov_score_uu):
"""robust generalized score tests on subset of parameters
This is the same as lm_robust_subset with arguments in parts of
partitioned matrices.
This can be useful, when we have the parts based on different estimation
procedures, i.e. when we do not have the full unconstrained model.
Calculates mainly the covariance of the constraint part of the score.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model. These is the score component for the restricted
part under hypothesis. The unconstrained part of the score is assumed
to be zero.
k_constraint : int
number of constraints
score_deriv_uu : ndarray, symmetric, square
first derivative of moment equation or second derivative of objective
function for the unconstrained part
TODO: could be OPG or any other estimator if information matrix
equality holds
score_deriv_cu : ndarray
first cross derivative of moment equation or second cross
derivative of objective function between.
cov_score_cc : ndarray
covariance matrix of the score for the unconstrained part.
This is the inner part of a sandwich estimator.
cov_score_cu : ndarray
covariance matrix of the score for the off-diagonal block, i.e.
covariance between constrained and unconstrained part.
cov_score_uu : ndarray
covariance matrix of the score for the unconstrained part.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
TODO: these function should just return the covariance of the score
instead of calculating the score/lm test.
Implementation similar to lm_robust_subset and is based on Boos 1992,
section 4.1 in the form attributed to Breslow (1990). It does not use the
computation attributed to Kent (1982) and Engle (1984).
"""
tmp_proj = np.linalg.solve(score_deriv_uu, score_deriv_cu.T).T
tmp = tmp_proj.dot(cov_score_cu.T)
# this needs to make a copy of cov_score_cc for further inplace modification
cov = cov_score_cc - tmp
cov -= tmp.T
cov += tmp_proj.dot(cov_score_uu).dot(tmp_proj.T)
lm_stat = score.dot(np.linalg.solve(cov, score))
pval = stats.chi2.sf(lm_stat, k_constraints)
return lm_stat, pval | robust generalized score tests on subset of parameters
This is the same as lm_robust_subset with arguments in parts of
partitioned matrices.
This can be useful, when we have the parts based on different estimation
procedures, i.e. when we do not have the full unconstrained model.
Calculates mainly the covariance of the constraint part of the score.
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model. These is the score component for the restricted
part under hypothesis. The unconstrained part of the score is assumed
to be zero.
k_constraint : int
number of constraints
score_deriv_uu : ndarray, symmetric, square
first derivative of moment equation or second derivative of objective
function for the unconstrained part
TODO: could be OPG or any other estimator if information matrix
equality holds
score_deriv_cu : ndarray
first cross derivative of moment equation or second cross
derivative of objective function between.
cov_score_cc : ndarray
covariance matrix of the score for the unconstrained part.
This is the inner part of a sandwich estimator.
cov_score_cu : ndarray
covariance matrix of the score for the off-diagonal block, i.e.
covariance between constrained and unconstrained part.
cov_score_uu : ndarray
covariance matrix of the score for the unconstrained part.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
TODO: these function should just return the covariance of the score
instead of calculating the score/lm test.
Implementation similar to lm_robust_subset and is based on Boos 1992,
section 4.1 in the form attributed to Breslow (1990). It does not use the
computation attributed to Kent (1982) and Engle (1984). | lm_robust_subset_parts | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def lm_robust_reparameterized(score, params_deriv, score_deriv, cov_score):
"""robust generalized score test for transformed parameters
The parameters are given by a nonlinear transformation of the estimated
reduced parameters
`params = g(params_reduced)` with jacobian `G = d g / d params_reduced`
score and other arrays are for full parameter space `params`
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
params_deriv : ndarray
Jacobian G of the parameter trasnformation
score_deriv : ndarray, symmetric, square
second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
Boos 1992, section 4.3, expression for T_{GS} just before example 6
"""
# Boos notation
# params_deriv G
k_params, k_reduced = params_deriv.shape
k_constraints = k_params - k_reduced
G = params_deriv # shortcut alias
tmp_c0 = np.linalg.pinv(G.T.dot(score_deriv.dot(G)))
tmp_c1 = score_deriv.dot(G.dot(tmp_c0.dot(G.T)))
tmp_c = np.eye(k_params) - tmp_c1
cov = tmp_c.dot(cov_score.dot(tmp_c.T)) # warning: reduced rank
lm_stat = score.dot(np.linalg.pinv(cov).dot(score))
pval = stats.chi2.sf(lm_stat, k_constraints)
return lm_stat, pval | robust generalized score test for transformed parameters
The parameters are given by a nonlinear transformation of the estimated
reduced parameters
`params = g(params_reduced)` with jacobian `G = d g / d params_reduced`
score and other arrays are for full parameter space `params`
Parameters
----------
score : ndarray, 1-D
derivative of objective function at estimated parameters
of constrained model
params_deriv : ndarray
Jacobian G of the parameter trasnformation
score_deriv : ndarray, symmetric, square
second derivative of objective function
TODO: could be OPG or any other estimator if information matrix
equality holds
cov_score B : ndarray, symmetric, square
covariance matrix of the score. This is the inner part of a sandwich
estimator.
Returns
-------
lm_stat : float
score/lagrange multiplier statistic
p-value : float
p-value of the LM test based on chisquare distribution
Notes
-----
Boos 1992, section 4.3, expression for T_{GS} just before example 6 | lm_robust_reparameterized | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def conditional_moment_test_generic(mom_test, mom_test_deriv,
mom_incl, mom_incl_deriv,
var_mom_all=None,
cov_type='OPG', cov_kwds=None):
"""generic conditional moment test
This is mainly intended as internal function in support of diagnostic
and specification tests. It has no conversion and checking of correct
arguments.
Parameters
----------
mom_test : ndarray, 2-D (nobs, k_constraints)
moment conditions that will be tested to be zero
mom_test_deriv : ndarray, 2-D, square (k_constraints, k_constraints)
derivative of moment conditions under test with respect to the
parameters of the model summed over observations.
mom_incl : ndarray, 2-D (nobs, k_params)
moment conditions that where use in estimation, assumed to be zero
This is score_obs in the case of (Q)MLE
mom_incl_deriv : ndarray, 2-D, square (k_params, k_params)
derivative of moment conditions of estimator summed over observations
This is the information matrix or Hessian in the case of (Q)MLE.
var_mom_all : None, or ndarray, 2-D, (k, k) with k = k_constraints + k_params
Expected product or variance of the joint (column_stacked) moment
conditions. The stacking should have the variance of the moment
conditions under test in the first k_constraint rows and columns.
If it is not None, then it will be estimated based on cov_type.
I think: This is the Hessian of the extended or alternative model
under full MLE and score test assuming information matrix identity
holds.
Returns
-------
results
Notes
-----
TODO: cov_type other than OPG is missing
initial implementation based on Cameron Trived countbook 1998 p.48, p.56
also included: mom_incl can be None if expected mom_test_deriv is zero.
References
----------
Cameron and Trivedi 1998 count book
Wooldridge ???
Pagan and Vella 1989
"""
if cov_type != 'OPG':
raise NotImplementedError
k_constraints = mom_test.shape[1]
if mom_incl is None:
# assume mom_test_deriv is zero, do not include effect of mom_incl
if var_mom_all is None:
var_cm = mom_test.T.dot(mom_test)
else:
var_cm = var_mom_all
else:
# take into account he effect of parameter estimates on mom_test
if var_mom_all is None:
mom_all = np.column_stack((mom_test, mom_incl))
# TODO: replace with inner sandwich covariance estimator
var_mom_all = mom_all.T.dot(mom_all)
tmp = mom_test_deriv.dot(np.linalg.pinv(mom_incl_deriv))
h = np.column_stack((np.eye(k_constraints), -tmp))
var_cm = h.dot(var_mom_all.dot(h.T))
# calculate test results with chisquare
var_cm_inv = np.linalg.pinv(var_cm)
mom_test_sum = mom_test.sum(0)
statistic = mom_test_sum.dot(var_cm_inv.dot(mom_test_sum))
pval = stats.chi2.sf(statistic, k_constraints)
# normal test of individual components
se = np.sqrt(np.diag(var_cm))
tvalues = mom_test_sum / se
pvalues = stats.norm.sf(np.abs(tvalues))
res = ResultsGeneric(var_cm=var_cm,
stat_cmt=statistic,
pval_cmt=pval,
tvalues=tvalues,
pvalues=pvalues)
return res | generic conditional moment test
This is mainly intended as internal function in support of diagnostic
and specification tests. It has no conversion and checking of correct
arguments.
Parameters
----------
mom_test : ndarray, 2-D (nobs, k_constraints)
moment conditions that will be tested to be zero
mom_test_deriv : ndarray, 2-D, square (k_constraints, k_constraints)
derivative of moment conditions under test with respect to the
parameters of the model summed over observations.
mom_incl : ndarray, 2-D (nobs, k_params)
moment conditions that where use in estimation, assumed to be zero
This is score_obs in the case of (Q)MLE
mom_incl_deriv : ndarray, 2-D, square (k_params, k_params)
derivative of moment conditions of estimator summed over observations
This is the information matrix or Hessian in the case of (Q)MLE.
var_mom_all : None, or ndarray, 2-D, (k, k) with k = k_constraints + k_params
Expected product or variance of the joint (column_stacked) moment
conditions. The stacking should have the variance of the moment
conditions under test in the first k_constraint rows and columns.
If it is not None, then it will be estimated based on cov_type.
I think: This is the Hessian of the extended or alternative model
under full MLE and score test assuming information matrix identity
holds.
Returns
-------
results
Notes
-----
TODO: cov_type other than OPG is missing
initial implementation based on Cameron Trived countbook 1998 p.48, p.56
also included: mom_incl can be None if expected mom_test_deriv is zero.
References
----------
Cameron and Trivedi 1998 count book
Wooldridge ???
Pagan and Vella 1989 | conditional_moment_test_generic | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def conditional_moment_test_regression(mom_test, mom_test_deriv=None,
mom_incl=None, mom_incl_deriv=None,
var_mom_all=None, demean=False,
cov_type='OPG', cov_kwds=None):
"""generic conditional moment test based artificial regression
this is very experimental, no options implemented yet
so far
OPG regression, or
artificial regression with Robust Wald test
The latter is (as far as I can see) the same as an overidentifying test
in GMM where the test statistic is the value of the GMM objective function
and it is assumed that parameters were estimated with optimial GMM, i.e.
the weight matrix equal to the expectation of the score variance.
"""
# so far coded from memory
nobs, k_constraints = mom_test.shape
endog = np.ones(nobs)
if mom_incl is not None:
ex = np.column_stack((mom_test, mom_incl))
else:
ex = mom_test
if demean:
ex -= ex.mean(0)
if cov_type == 'OPG':
res = OLS(endog, ex).fit()
statistic = nobs * res.rsquared
pval = stats.chi2.sf(statistic, k_constraints)
else:
res = OLS(endog, ex).fit(cov_type=cov_type, cov_kwds=cov_kwds)
tres = res.wald_test(np.eye(ex.shape[1]))
statistic = tres.statistic
pval = tres.pvalue
return statistic, pval | generic conditional moment test based artificial regression
this is very experimental, no options implemented yet
so far
OPG regression, or
artificial regression with Robust Wald test
The latter is (as far as I can see) the same as an overidentifying test
in GMM where the test statistic is the value of the GMM objective function
and it is assumed that parameters were estimated with optimial GMM, i.e.
the weight matrix equal to the expectation of the score variance. | conditional_moment_test_regression | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def asy_cov_moments(self):
"""
`sqrt(T) * g_T(b_0) asy N(K delta, V)`
mean is not implemented,
V is the same as cov_moments in __init__ argument
"""
return self.cov_moments | `sqrt(T) * g_T(b_0) asy N(K delta, V)`
mean is not implemented,
V is the same as cov_moments in __init__ argument | asy_cov_moments | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def ztest(self):
"""statistic, p-value and degrees of freedom of separate moment test
currently two sided test only
TODO: This can use generic ztest/ttest features and return
ContrastResults
"""
diff = self.moments_constraint
bse = np.sqrt(np.diag(self.cov_mom_constraints))
# Newey uses a generalized inverse
stat = diff / bse
pval = stats.norm.sf(np.abs(stat))*2
return stat, pval | statistic, p-value and degrees of freedom of separate moment test
currently two sided test only
TODO: This can use generic ztest/ttest features and return
ContrastResults | ztest | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def chisquare(self):
"""statistic, p-value and degrees of freedom of joint moment test
"""
diff = self.moments_constraint
cov = self.cov_mom_constraints
# Newey uses a generalized inverse
stat = diff.T.dot(np.linalg.pinv(cov).dot(diff))
df = self.rank_cov_mom_constraints
pval = stats.chi2.sf(stat, df) # Theorem 1
return stat, pval, df | statistic, p-value and degrees of freedom of joint moment test | chisquare | python | statsmodels/statsmodels | statsmodels/stats/_diagnostic_other.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/_diagnostic_other.py | BSD-3-Clause |
def conf_int_samples(self, alpha=0.05, use_t=None, nobs=None,
ci_func=None):
"""confidence intervals for the effect size estimate of samples
Additional information needs to be provided for confidence intervals
that are not based on normal distribution using available variance.
This is likely to change in future.
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
nobs : None or float
Number of observations used for degrees of freedom computation.
Only used if use_t is true.
ci_func : None or callable
User provided function to compute confidence intervals.
This is not used yet and will allow using non-standard confidence
intervals.
Returns
-------
ci_eff : tuple of ndarrays
Tuple (ci_low, ci_upp) with confidence interval computed for each
sample.
Notes
-----
CombineResults currently only has information from the combine_effects
function, which does not provide details about individual samples.
"""
# this is a bit messy, we don't have enough information about
# computing conf_int already in results for other than normal
# TODO: maybe there is a better
if (alpha, use_t) in self.cache_ci:
return self.cache_ci[(alpha, use_t)]
if use_t is None:
use_t = self.use_t
if ci_func is not None:
kwds = {"use_t": use_t} if use_t is not None else {}
ci_eff = ci_func(alpha=alpha, **kwds)
self.ci_sample_distr = "ci_func"
else:
if use_t is False:
crit = stats.norm.isf(alpha / 2)
self.ci_sample_distr = "normal"
else:
if nobs is not None:
df_resid = nobs - 1
crit = stats.t.isf(alpha / 2, df_resid)
self.ci_sample_distr = "t"
else:
msg = ("`use_t=True` requires `nobs` for each sample "
"or `ci_func`. Using normal distribution for "
"confidence interval of individual samples.")
import warnings
warnings.warn(msg)
crit = stats.norm.isf(alpha / 2)
self.ci_sample_distr = "normal"
# sgn = np.asarray([-1, 1])
# ci_eff = self.eff + sgn * crit * self.sd_eff
ci_low = self.eff - crit * self.sd_eff
ci_upp = self.eff + crit * self.sd_eff
ci_eff = (ci_low, ci_upp)
# if (alpha, use_t) not in self.cache_ci: # not needed
self.cache_ci[(alpha, use_t)] = ci_eff
return ci_eff | confidence intervals for the effect size estimate of samples
Additional information needs to be provided for confidence intervals
that are not based on normal distribution using available variance.
This is likely to change in future.
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
nobs : None or float
Number of observations used for degrees of freedom computation.
Only used if use_t is true.
ci_func : None or callable
User provided function to compute confidence intervals.
This is not used yet and will allow using non-standard confidence
intervals.
Returns
-------
ci_eff : tuple of ndarrays
Tuple (ci_low, ci_upp) with confidence interval computed for each
sample.
Notes
-----
CombineResults currently only has information from the combine_effects
function, which does not provide details about individual samples. | conf_int_samples | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def conf_int(self, alpha=0.05, use_t=None):
"""confidence interval for the overall mean estimate
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
ci_eff_fe : tuple of floats
Confidence interval for mean effects size based on fixed effects
model with scale=1.
ci_eff_re : tuple of floats
Confidence interval for mean effects size based on random effects
model with scale=1
ci_eff_fe_wls : tuple of floats
Confidence interval for mean effects size based on fixed effects
model with estimated scale corresponding to WLS, ie. HKSJ.
ci_eff_re_wls : tuple of floats
Confidence interval for mean effects size based on random effects
model with estimated scale corresponding to WLS, ie. HKSJ.
If random effects method is fully iterated, i.e. Paule-Mandel, then
the estimated scale is 1.
"""
if use_t is None:
use_t = self.use_t
if use_t is False:
crit = stats.norm.isf(alpha / 2)
else:
crit = stats.t.isf(alpha / 2, self.df_resid)
sgn = np.asarray([-1, 1])
m_fe = self.mean_effect_fe
m_re = self.mean_effect_re
ci_eff_fe = m_fe + sgn * crit * self.sd_eff_w_fe
ci_eff_re = m_re + sgn * crit * self.sd_eff_w_re
ci_eff_fe_wls = m_fe + sgn * crit * np.sqrt(self.var_hksj_fe)
ci_eff_re_wls = m_re + sgn * crit * np.sqrt(self.var_hksj_re)
return ci_eff_fe, ci_eff_re, ci_eff_fe_wls, ci_eff_re_wls | confidence interval for the overall mean estimate
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
ci_eff_fe : tuple of floats
Confidence interval for mean effects size based on fixed effects
model with scale=1.
ci_eff_re : tuple of floats
Confidence interval for mean effects size based on random effects
model with scale=1
ci_eff_fe_wls : tuple of floats
Confidence interval for mean effects size based on fixed effects
model with estimated scale corresponding to WLS, ie. HKSJ.
ci_eff_re_wls : tuple of floats
Confidence interval for mean effects size based on random effects
model with estimated scale corresponding to WLS, ie. HKSJ.
If random effects method is fully iterated, i.e. Paule-Mandel, then
the estimated scale is 1. | conf_int | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def test_homogeneity(self):
"""Test whether the means of all samples are the same
currently no options, test uses chisquare distribution
default might change depending on `use_t`
Returns
-------
res : HolderTuple instance
The results include the following attributes:
- statistic : float
Test statistic, ``q`` in meta-analysis, this is the
pearson_chi2 statistic for the fixed effects model.
- pvalue : float
P-value based on chisquare distribution.
- df : float
Degrees of freedom, equal to number of studies or samples
minus 1.
"""
pvalue = stats.chi2.sf(self.q, self.k - 1)
res = HolderTuple(statistic=self.q,
pvalue=pvalue,
df=self.k - 1,
distr="chi2")
return res | Test whether the means of all samples are the same
currently no options, test uses chisquare distribution
default might change depending on `use_t`
Returns
-------
res : HolderTuple instance
The results include the following attributes:
- statistic : float
Test statistic, ``q`` in meta-analysis, this is the
pearson_chi2 statistic for the fixed effects model.
- pvalue : float
P-value based on chisquare distribution.
- df : float
Degrees of freedom, equal to number of studies or samples
minus 1. | test_homogeneity | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def summary_array(self, alpha=0.05, use_t=None):
"""Create array with sample statistics and mean estimates
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
res : ndarray
Array with columns
['eff', "sd_eff", "ci_low", "ci_upp", "w_fe","w_re"].
Rows include statistics for samples and estimates of overall mean.
column_names : list of str
The names for the columns, used when creating summary DataFrame.
"""
ci_low, ci_upp = self.conf_int_samples(alpha=alpha, use_t=use_t)
res = np.column_stack([self.eff, self.sd_eff,
ci_low, ci_upp,
self.weights_rel_fe, self.weights_rel_re])
ci = self.conf_int(alpha=alpha, use_t=use_t)
res_fe = [[self.mean_effect_fe, self.sd_eff_w_fe,
ci[0][0], ci[0][1], 1, np.nan]]
res_re = [[self.mean_effect_re, self.sd_eff_w_re,
ci[1][0], ci[1][1], np.nan, 1]]
res_fe_wls = [[self.mean_effect_fe, self.sd_eff_w_fe_hksj,
ci[2][0], ci[2][1], 1, np.nan]]
res_re_wls = [[self.mean_effect_re, self.sd_eff_w_re_hksj,
ci[3][0], ci[3][1], np.nan, 1]]
res = np.concatenate([res, res_fe, res_re, res_fe_wls, res_re_wls],
axis=0)
column_names = ['eff', "sd_eff", "ci_low", "ci_upp", "w_fe", "w_re"]
return res, column_names | Create array with sample statistics and mean estimates
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
res : ndarray
Array with columns
['eff', "sd_eff", "ci_low", "ci_upp", "w_fe","w_re"].
Rows include statistics for samples and estimates of overall mean.
column_names : list of str
The names for the columns, used when creating summary DataFrame. | summary_array | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def summary_frame(self, alpha=0.05, use_t=None):
"""Create DataFrame with sample statistics and mean estimates
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
res : DataFrame
pandas DataFrame instance with columns
['eff', "sd_eff", "ci_low", "ci_upp", "w_fe","w_re"].
Rows include statistics for samples and estimates of overall mean.
"""
if use_t is None:
use_t = self.use_t
labels = (list(self.row_names) +
["fixed effect", "random effect",
"fixed effect wls", "random effect wls"])
res, col_names = self.summary_array(alpha=alpha, use_t=use_t)
results = pd.DataFrame(res, index=labels, columns=col_names)
return results | Create DataFrame with sample statistics and mean estimates
Parameters
----------
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
Returns
-------
res : DataFrame
pandas DataFrame instance with columns
['eff', "sd_eff", "ci_low", "ci_upp", "w_fe","w_re"].
Rows include statistics for samples and estimates of overall mean. | summary_frame | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def plot_forest(self, alpha=0.05, use_t=None, use_exp=False,
ax=None, **kwds):
"""Forest plot with means and confidence intervals
Parameters
----------
ax : None or matplotlib axis instance
If ax is provided, then the plot will be added to it.
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
use_exp : bool
If `use_exp` is True, then the effect size and confidence limits
will be exponentiated. This transform log-odds-ration into
odds-ratio, and similarly for risk-ratio.
ax : AxesSubplot, optional
If given, this axes is used to plot in instead of a new figure
being created.
kwds : optional keyword arguments
Keywords are forwarded to the dot_plot function that creates the
plot.
Returns
-------
fig : Matplotlib figure instance
See Also
--------
dot_plot
"""
from statsmodels.graphics.dotplots import dot_plot
res_df = self.summary_frame(alpha=alpha, use_t=use_t)
if use_exp:
res_df = np.exp(res_df[["eff", "ci_low", "ci_upp"]])
hw = np.abs(res_df[["ci_low", "ci_upp"]] - res_df[["eff"]].values)
fig = dot_plot(points=res_df["eff"], intervals=hw,
lines=res_df.index, line_order=res_df.index, **kwds)
return fig | Forest plot with means and confidence intervals
Parameters
----------
ax : None or matplotlib axis instance
If ax is provided, then the plot will be added to it.
alpha : float in (0, 1)
Significance level for confidence interval. Nominal coverage is
``1 - alpha``.
use_t : None or bool
If use_t is None, then the attribute `use_t` determines whether
normal or t-distribution is used for confidence intervals.
Specifying use_t overrides the attribute.
If use_t is false, then confidence intervals are based on the
normal distribution. If it is true, then the t-distribution is
used.
use_exp : bool
If `use_exp` is True, then the effect size and confidence limits
will be exponentiated. This transform log-odds-ration into
odds-ratio, and similarly for risk-ratio.
ax : AxesSubplot, optional
If given, this axes is used to plot in instead of a new figure
being created.
kwds : optional keyword arguments
Keywords are forwarded to the dot_plot function that creates the
plot.
Returns
-------
fig : Matplotlib figure instance
See Also
--------
dot_plot | plot_forest | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def effectsize_smd(mean1, sd1, nobs1, mean2, sd2, nobs2):
"""effect sizes for mean difference for use in meta-analysis
mean1, sd1, nobs1 are for treatment
mean2, sd2, nobs2 are for control
Effect sizes are computed for the mean difference ``mean1 - mean2``
standardized by an estimate of the within variance.
This does not have option yet.
It uses standardized mean difference with bias correction as effect size.
This currently does not use np.asarray, all computations are possible in
pandas.
Parameters
----------
mean1 : array
mean of second sample, treatment groups
sd1 : array
standard deviation of residuals in treatment groups, within
nobs1 : array
number of observations in treatment groups
mean2, sd2, nobs2 : arrays
mean, standard deviation and number of observations of control groups
Returns
-------
smd_bc : array
bias corrected estimate of standardized mean difference
var_smdbc : array
estimate of variance of smd_bc
Notes
-----
Status: API will still change. This is currently intended for support of
meta-analysis.
References
----------
Borenstein, Michael. 2009. Introduction to Meta-Analysis.
Chichester: Wiley.
Chen, Ding-Geng, and Karl E. Peace. 2013. Applied Meta-Analysis with R.
Chapman & Hall/CRC Biostatistics Series.
Boca Raton: CRC Press/Taylor & Francis Group.
"""
# TODO: not used yet, design and options ?
# k = len(mean1)
# if row_names is None:
# row_names = list(range(k))
# crit = stats.norm.isf(alpha / 2)
# var_diff_uneq = sd1**2 / nobs1 + sd2**2 / nobs2
var_diff = (sd1**2 * (nobs1 - 1) +
sd2**2 * (nobs2 - 1)) / (nobs1 + nobs2 - 2)
sd_diff = np.sqrt(var_diff)
nobs = nobs1 + nobs2
bias_correction = 1 - 3 / (4 * nobs - 9)
smd = (mean1 - mean2) / sd_diff
smd_bc = bias_correction * smd
var_smdbc = nobs / nobs1 / nobs2 + smd_bc**2 / 2 / (nobs - 3.94)
return smd_bc, var_smdbc | effect sizes for mean difference for use in meta-analysis
mean1, sd1, nobs1 are for treatment
mean2, sd2, nobs2 are for control
Effect sizes are computed for the mean difference ``mean1 - mean2``
standardized by an estimate of the within variance.
This does not have option yet.
It uses standardized mean difference with bias correction as effect size.
This currently does not use np.asarray, all computations are possible in
pandas.
Parameters
----------
mean1 : array
mean of second sample, treatment groups
sd1 : array
standard deviation of residuals in treatment groups, within
nobs1 : array
number of observations in treatment groups
mean2, sd2, nobs2 : arrays
mean, standard deviation and number of observations of control groups
Returns
-------
smd_bc : array
bias corrected estimate of standardized mean difference
var_smdbc : array
estimate of variance of smd_bc
Notes
-----
Status: API will still change. This is currently intended for support of
meta-analysis.
References
----------
Borenstein, Michael. 2009. Introduction to Meta-Analysis.
Chichester: Wiley.
Chen, Ding-Geng, and Karl E. Peace. 2013. Applied Meta-Analysis with R.
Chapman & Hall/CRC Biostatistics Series.
Boca Raton: CRC Press/Taylor & Francis Group. | effectsize_smd | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def effectsize_2proportions(count1, nobs1, count2, nobs2, statistic="diff",
zero_correction=None, zero_kwds=None):
"""Effects sizes for two sample binomial proportions
Parameters
----------
count1, nobs1, count2, nobs2 : array_like
data for two samples
statistic : {"diff", "odds-ratio", "risk-ratio", "arcsine"}
statistic for the comparison of two proportions
Effect sizes for "odds-ratio" and "risk-ratio" are in logarithm.
zero_correction : {None, float, "tac", "clip"}
Some statistics are not finite when zero counts are in the data.
The options to remove zeros are:
* float : if zero_correction is a single float, then it will be added
to all count (cells) if the sample has any zeros.
* "tac" : treatment arm continuity correction see Ruecker et al 2009,
section 3.2
* "clip" : clip proportions without adding a value to all cells
The clip bounds can be set with zero_kwds["clip_bounds"]
zero_kwds : dict
additional options to handle zero counts
"clip_bounds" tuple, default (1e-6, 1 - 1e-6) if zero_correction="clip"
other options not yet implemented
Returns
-------
effect size : array
Effect size for each sample.
var_es : array
Estimate of variance of the effect size
Notes
-----
Status: API is experimental, Options for zero handling is incomplete.
The names for ``statistics`` keyword can be shortened to "rd", "rr", "or"
and "as".
The statistics are defined as:
- risk difference = p1 - p2
- log risk ratio = log(p1 / p2)
- log odds_ratio = log(p1 / (1 - p1) * (1 - p2) / p2)
- arcsine-sqrt = arcsin(sqrt(p1)) - arcsin(sqrt(p2))
where p1 and p2 are the estimated proportions in sample 1 (treatment) and
sample 2 (control).
log-odds-ratio and log-risk-ratio can be transformed back to ``or`` and
`rr` using `exp` function.
See Also
--------
statsmodels.stats.contingency_tables
"""
if zero_correction is None:
cc1 = cc2 = 0
elif zero_correction == "tac":
# treatment arm continuity correction Ruecker et al 2009, section 3.2
nobs_t = nobs1 + nobs2
cc1 = nobs2 / nobs_t
cc2 = nobs1 / nobs_t
elif zero_correction == "clip":
clip_bounds = zero_kwds.get("clip_bounds", (1e-6, 1 - 1e-6))
cc1 = cc2 = 0
elif zero_correction:
# TODO: check is float_like
cc1 = cc2 = zero_correction
else:
msg = "zero_correction not recognized or supported"
raise NotImplementedError(msg)
zero_mask1 = (count1 == 0) | (count1 == nobs1)
zero_mask2 = (count2 == 0) | (count2 == nobs2)
zmask = np.logical_or(zero_mask1, zero_mask2)
n1 = nobs1 + (cc1 + cc2) * zmask
n2 = nobs2 + (cc1 + cc2) * zmask
p1 = (count1 + cc1) / (n1)
p2 = (count2 + cc2) / (n2)
if zero_correction == "clip":
p1 = np.clip(p1, *clip_bounds)
p2 = np.clip(p2, *clip_bounds)
if statistic in ["diff", "rd"]:
rd = p1 - p2
rd_var = p1 * (1 - p1) / n1 + p2 * (1 - p2) / n2
eff = rd
var_eff = rd_var
elif statistic in ["risk-ratio", "rr"]:
# rr = p1 / p2
log_rr = np.log(p1) - np.log(p2)
log_rr_var = (1 - p1) / p1 / n1 + (1 - p2) / p2 / n2
eff = log_rr
var_eff = log_rr_var
elif statistic in ["odds-ratio", "or"]:
# or_ = p1 / (1 - p1) * (1 - p2) / p2
log_or = np.log(p1) - np.log(1 - p1) - np.log(p2) + np.log(1 - p2)
log_or_var = 1 / (p1 * (1 - p1) * n1) + 1 / (p2 * (1 - p2) * n2)
eff = log_or
var_eff = log_or_var
elif statistic in ["arcsine", "arcsin", "as"]:
as_ = np.arcsin(np.sqrt(p1)) - np.arcsin(np.sqrt(p2))
as_var = (1 / n1 + 1 / n2) / 4
eff = as_
var_eff = as_var
else:
msg = 'statistic not recognized, use one of "rd", "rr", "or", "as"'
raise NotImplementedError(msg)
return eff, var_eff | Effects sizes for two sample binomial proportions
Parameters
----------
count1, nobs1, count2, nobs2 : array_like
data for two samples
statistic : {"diff", "odds-ratio", "risk-ratio", "arcsine"}
statistic for the comparison of two proportions
Effect sizes for "odds-ratio" and "risk-ratio" are in logarithm.
zero_correction : {None, float, "tac", "clip"}
Some statistics are not finite when zero counts are in the data.
The options to remove zeros are:
* float : if zero_correction is a single float, then it will be added
to all count (cells) if the sample has any zeros.
* "tac" : treatment arm continuity correction see Ruecker et al 2009,
section 3.2
* "clip" : clip proportions without adding a value to all cells
The clip bounds can be set with zero_kwds["clip_bounds"]
zero_kwds : dict
additional options to handle zero counts
"clip_bounds" tuple, default (1e-6, 1 - 1e-6) if zero_correction="clip"
other options not yet implemented
Returns
-------
effect size : array
Effect size for each sample.
var_es : array
Estimate of variance of the effect size
Notes
-----
Status: API is experimental, Options for zero handling is incomplete.
The names for ``statistics`` keyword can be shortened to "rd", "rr", "or"
and "as".
The statistics are defined as:
- risk difference = p1 - p2
- log risk ratio = log(p1 / p2)
- log odds_ratio = log(p1 / (1 - p1) * (1 - p2) / p2)
- arcsine-sqrt = arcsin(sqrt(p1)) - arcsin(sqrt(p2))
where p1 and p2 are the estimated proportions in sample 1 (treatment) and
sample 2 (control).
log-odds-ratio and log-risk-ratio can be transformed back to ``or`` and
`rr` using `exp` function.
See Also
--------
statsmodels.stats.contingency_tables | effectsize_2proportions | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def combine_effects(effect, variance, method_re="iterated", row_names=None,
use_t=False, alpha=0.05, **kwds):
"""combining effect sizes for effect sizes using meta-analysis
This currently does not use np.asarray, all computations are possible in
pandas.
Parameters
----------
effect : array
mean of effect size measure for all samples
variance : array
variance of mean or effect size measure for all samples
method_re : {"iterated", "chi2"}
method that is use to compute the between random effects variance
"iterated" or "pm" uses Paule and Mandel method to iteratively
estimate the random effects variance. Options for the iteration can
be provided in the ``kwds``
"chi2" or "dl" uses DerSimonian and Laird one-step estimator.
row_names : list of strings (optional)
names for samples or studies, will be included in results summary and
table.
alpha : float in (0, 1)
significance level, default is 0.05, for the confidence intervals
Returns
-------
results : CombineResults
Contains estimation results and intermediate statistics, and includes
a method to return a summary table.
Statistics from intermediate calculations might be removed at a later
time.
Notes
-----
Status: Basic functionality is verified, mainly compared to R metafor
package. However, API might still change.
This computes both fixed effects and random effects estimates. The
random effects results depend on the method to estimate the RE variance.
Scale estimate
In fixed effects models and in random effects models without fully
iterated random effects variance, the model will in general not account
for all residual variance. Traditional meta-analysis uses a fixed
scale equal to 1, that might not produce test statistics and
confidence intervals with the correct size. Estimating the scale to account
for residual variance often improves the small sample properties of
inference and confidence intervals.
This adjustment to the standard errors is often referred to as HKSJ
method based attributed to Hartung and Knapp and Sidik and Jonkman.
However, this is equivalent to estimating the scale in WLS.
The results instance includes both, fixed scale and estimated scale
versions of standard errors and confidence intervals.
References
----------
Borenstein, Michael. 2009. Introduction to Meta-Analysis.
Chichester: Wiley.
Chen, Ding-Geng, and Karl E. Peace. 2013. Applied Meta-Analysis with R.
Chapman & Hall/CRC Biostatistics Series.
Boca Raton: CRC Press/Taylor & Francis Group.
"""
k = len(effect)
if row_names is None:
row_names = list(range(k))
crit = stats.norm.isf(alpha / 2)
# alias for initial version
eff = effect
var_eff = variance
sd_eff = np.sqrt(var_eff)
# fixed effects computation
weights_fe = 1 / var_eff # no bias correction ?
w_total_fe = weights_fe.sum(0)
weights_rel_fe = weights_fe / w_total_fe
eff_w_fe = weights_rel_fe * eff
mean_effect_fe = eff_w_fe.sum()
var_eff_w_fe = 1 / w_total_fe
sd_eff_w_fe = np.sqrt(var_eff_w_fe)
# random effects computation
q = (weights_fe * eff**2).sum(0)
q -= (weights_fe * eff).sum()**2 / w_total_fe
df = k - 1
if method_re.lower() in ["iterated", "pm"]:
tau2, _ = _fit_tau_iterative(eff, var_eff, **kwds)
elif method_re.lower() in ["chi2", "dl"]:
c = w_total_fe - (weights_fe**2).sum() / w_total_fe
tau2 = (q - df) / c
else:
raise ValueError('method_re should be "iterated" or "chi2"')
weights_re = 1 / (var_eff + tau2) # no bias_correction ?
w_total_re = weights_re.sum(0)
weights_rel_re = weights_re / weights_re.sum(0)
eff_w_re = weights_rel_re * eff
mean_effect_re = eff_w_re.sum()
var_eff_w_re = 1 / w_total_re
sd_eff_w_re = np.sqrt(var_eff_w_re)
# ci_low_eff_re = mean_effect_re - crit * sd_eff_w_re
# ci_upp_eff_re = mean_effect_re + crit * sd_eff_w_re
scale_hksj_re = (weights_re * (eff - mean_effect_re)**2).sum() / df
scale_hksj_fe = (weights_fe * (eff - mean_effect_fe)**2).sum() / df
var_hksj_re = (weights_rel_re * (eff - mean_effect_re)**2).sum() / df
var_hksj_fe = (weights_rel_fe * (eff - mean_effect_fe)**2).sum() / df
res = CombineResults(**locals())
return res | combining effect sizes for effect sizes using meta-analysis
This currently does not use np.asarray, all computations are possible in
pandas.
Parameters
----------
effect : array
mean of effect size measure for all samples
variance : array
variance of mean or effect size measure for all samples
method_re : {"iterated", "chi2"}
method that is use to compute the between random effects variance
"iterated" or "pm" uses Paule and Mandel method to iteratively
estimate the random effects variance. Options for the iteration can
be provided in the ``kwds``
"chi2" or "dl" uses DerSimonian and Laird one-step estimator.
row_names : list of strings (optional)
names for samples or studies, will be included in results summary and
table.
alpha : float in (0, 1)
significance level, default is 0.05, for the confidence intervals
Returns
-------
results : CombineResults
Contains estimation results and intermediate statistics, and includes
a method to return a summary table.
Statistics from intermediate calculations might be removed at a later
time.
Notes
-----
Status: Basic functionality is verified, mainly compared to R metafor
package. However, API might still change.
This computes both fixed effects and random effects estimates. The
random effects results depend on the method to estimate the RE variance.
Scale estimate
In fixed effects models and in random effects models without fully
iterated random effects variance, the model will in general not account
for all residual variance. Traditional meta-analysis uses a fixed
scale equal to 1, that might not produce test statistics and
confidence intervals with the correct size. Estimating the scale to account
for residual variance often improves the small sample properties of
inference and confidence intervals.
This adjustment to the standard errors is often referred to as HKSJ
method based attributed to Hartung and Knapp and Sidik and Jonkman.
However, this is equivalent to estimating the scale in WLS.
The results instance includes both, fixed scale and estimated scale
versions of standard errors and confidence intervals.
References
----------
Borenstein, Michael. 2009. Introduction to Meta-Analysis.
Chichester: Wiley.
Chen, Ding-Geng, and Karl E. Peace. 2013. Applied Meta-Analysis with R.
Chapman & Hall/CRC Biostatistics Series.
Boca Raton: CRC Press/Taylor & Francis Group. | combine_effects | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def _fit_tau_iterative(eff, var_eff, tau2_start=0, atol=1e-5, maxiter=50):
"""Paule-Mandel iterative estimate of between random effect variance
implementation follows DerSimonian and Kacker 2007 Appendix 8
see also Kacker 2004
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
tau2_start : float
starting value for iteration
atol : float, default: 1e-5
convergence tolerance for absolute value of estimating equation
maxiter : int
maximum number of iterations
Returns
-------
tau2 : float
estimate of random effects variance tau squared
converged : bool
True if iteration has converged.
"""
tau2 = tau2_start
k = eff.shape[0]
converged = False
for i in range(maxiter):
w = 1 / (var_eff + tau2)
m = w.dot(eff) / w.sum(0)
resid_sq = (eff - m)**2
q_w = w.dot(resid_sq)
# estimating equation
ee = q_w - (k - 1)
if ee < 0:
tau2 = 0
converged = 0
break
if np.allclose(ee, 0, atol=atol):
converged = True
break
# update tau2
delta = ee / (w**2).dot(resid_sq)
tau2 += delta
return tau2, converged | Paule-Mandel iterative estimate of between random effect variance
implementation follows DerSimonian and Kacker 2007 Appendix 8
see also Kacker 2004
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
tau2_start : float
starting value for iteration
atol : float, default: 1e-5
convergence tolerance for absolute value of estimating equation
maxiter : int
maximum number of iterations
Returns
-------
tau2 : float
estimate of random effects variance tau squared
converged : bool
True if iteration has converged. | _fit_tau_iterative | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def _fit_tau_mm(eff, var_eff, weights):
"""one-step method of moment estimate of between random effect variance
implementation follows Kacker 2004 and DerSimonian and Kacker 2007 eq. 6
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
weights : ndarray
weights for estimating overall weighted mean
Returns
-------
tau2 : float
estimate of random effects variance tau squared
"""
w = weights
m = w.dot(eff) / w.sum(0)
resid_sq = (eff - m)**2
q_w = w.dot(resid_sq)
w_t = w.sum()
expect = w.dot(var_eff) - (w**2).dot(var_eff) / w_t
denom = w_t - (w**2).sum() / w_t
# moment estimate from estimating equation
tau2 = (q_w - expect) / denom
return tau2 | one-step method of moment estimate of between random effect variance
implementation follows Kacker 2004 and DerSimonian and Kacker 2007 eq. 6
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
weights : ndarray
weights for estimating overall weighted mean
Returns
-------
tau2 : float
estimate of random effects variance tau squared | _fit_tau_mm | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def _fit_tau_iter_mm(eff, var_eff, tau2_start=0, atol=1e-5, maxiter=50):
"""iterated method of moment estimate of between random effect variance
This repeatedly estimates tau, updating weights in each iteration
see two-step estimators in DerSimonian and Kacker 2007
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
tau2_start : float
starting value for iteration
atol : float, default: 1e-5
convergence tolerance for change in tau2 estimate between iterations
maxiter : int
maximum number of iterations
Returns
-------
tau2 : float
estimate of random effects variance tau squared
converged : bool
True if iteration has converged.
"""
tau2 = tau2_start
converged = False
for _ in range(maxiter):
w = 1 / (var_eff + tau2)
tau2_new = _fit_tau_mm(eff, var_eff, w)
tau2_new = max(0, tau2_new)
delta = tau2_new - tau2
if np.allclose(delta, 0, atol=atol):
converged = True
break
tau2 = tau2_new
return tau2, converged | iterated method of moment estimate of between random effect variance
This repeatedly estimates tau, updating weights in each iteration
see two-step estimators in DerSimonian and Kacker 2007
Parameters
----------
eff : ndarray
effect sizes
var_eff : ndarray
variance of effect sizes
tau2_start : float
starting value for iteration
atol : float, default: 1e-5
convergence tolerance for change in tau2 estimate between iterations
maxiter : int
maximum number of iterations
Returns
-------
tau2 : float
estimate of random effects variance tau squared
converged : bool
True if iteration has converged. | _fit_tau_iter_mm | python | statsmodels/statsmodels | statsmodels/stats/meta_analysis.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/meta_analysis.py | BSD-3-Clause |
def anova_single(model, **kwargs):
"""
Anova table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
typ : int or str {1,2,3} or {"I","II","III"}
Type of sum of squares to use.
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead.
"""
test = kwargs.get("test", "F")
typ = kwargs.get("typ", 1)
robust = kwargs.get("robust", None)
if robust:
robust = robust.lower()
endog = model.model.endog
exog = model.model.exog
nobs = exog.shape[0]
model_spec = model.model.data.model_spec
# +1 for resids
mgr = FormulaManager()
n_rows = (len(model_spec.terms) - mgr.has_intercept(model_spec) + 1)
pr_test = "PR(>%s)" % test
names = ['df', 'sum_sq', 'mean_sq', test, pr_test]
table = DataFrame(np.zeros((n_rows, 5)), columns=names)
if typ in [1, "I"]:
return anova1_lm_single(model, endog, exog, nobs, model_spec, table,
n_rows, test, pr_test, robust)
elif typ in [2, "II"]:
return anova2_lm_single(model, model_spec, n_rows, test, pr_test,
robust)
elif typ in [3, "III"]:
return anova3_lm_single(model, model_spec, n_rows, test, pr_test,
robust)
elif typ in [4, "IV"]:
raise NotImplementedError("Type IV not yet implemented")
else: # pragma: no cover
raise ValueError("Type %s not understood" % str(typ)) | Anova table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
typ : int or str {1,2,3} or {"I","II","III"}
Type of sum of squares to use.
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead. | anova_single | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def anova1_lm_single(model, endog, exog, nobs, model_spec, table, n_rows, test,
pr_test, robust):
"""
Anova table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead.
"""
#maybe we should rethink using pinv > qr in OLS/linear models?
mgr = FormulaManager()
effects = getattr(model, 'effects', None)
if effects is None:
q,r = np.linalg.qr(exog)
effects = np.dot(q.T, endog)
arr = np.zeros((len(model_spec.terms), len(model_spec.column_names)))
slices = [
mgr.get_slice(model_spec, name) for name in mgr.get_term_names(model_spec)
]
for i, slice_ in enumerate(slices):
arr[i, slice_] = 1
sum_sq = np.dot(arr, effects**2)
#NOTE: assumes intercept is first column
mgr = FormulaManager()
idx = mgr.intercept_idx(model_spec)
sum_sq = sum_sq[~idx]
term_names = np.array(mgr.get_term_names(model_spec)) # want boolean indexing
term_names = term_names[~idx]
index = term_names.tolist()
table.index = Index(index + ['Residual'])
table.loc[index, ['df', 'sum_sq']] = np.c_[arr[~idx].sum(1), sum_sq]
# fill in residual
table.loc['Residual', ['sum_sq','df']] = model.ssr, model.df_resid
if test == 'F':
table[test] = ((table['sum_sq'] / table['df']) /
(model.ssr / model.df_resid))
table[pr_test] = stats.f.sf(table["F"], table["df"],
model.df_resid)
table.loc['Residual', [test, pr_test]] = np.nan, np.nan
table['mean_sq'] = table['sum_sq'] / table['df']
return table | Anova table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead. | anova1_lm_single | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def anova2_lm_single(model, model_spec, n_rows, test, pr_test, robust):
"""
Anova type II table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead.
Type II
Sum of Squares compares marginal contribution of terms. Thus, it is
not particularly useful for models with significant interaction terms.
"""
mgr = FormulaManager()
terms_info = model_spec.terms[:] # copy
terms_info = mgr.remove_intercept(terms_info)
names = ['sum_sq', 'df', test, pr_test]
table = DataFrame(np.zeros((n_rows, 4)), columns = names)
robust_cov = _get_covariance(model, robust)
col_order = []
index = []
for i, term in enumerate(terms_info):
# grab all variables except interaction effects that contain term
# need two hypotheses matrices L1 is most restrictive, ie., term==0
# L2 is everything except term==0
cols = mgr.get_slice(model_spec, term)
L1 = lrange(cols.start, cols.stop)
L2 = []
term_set = set(term.factors)
for t in terms_info: # for the term you have
other_set = set(t.factors)
if term_set.issubset(other_set) and not term_set == other_set:
col = mgr.get_slice(model_spec, t)
# on a higher order term containing current `term`
L1.extend(lrange(col.start, col.stop))
L2.extend(lrange(col.start, col.stop))
L1 = np.eye(model.model.exog.shape[1])[L1]
L2 = np.eye(model.model.exog.shape[1])[L2]
if L2.size:
LVL = np.dot(np.dot(L1,robust_cov),L2.T)
from scipy import linalg
orth_compl,_ = linalg.qr(LVL)
r = L1.shape[0] - L2.shape[0]
# L1|2
# use the non-unique orthogonal completion since L12 is rank r
L12 = np.dot(orth_compl[:,-r:].T, L1)
else:
L12 = L1
r = L1.shape[0]
#from IPython.core.debugger import Pdb; Pdb().set_trace()
if test == 'F':
f = model.f_test(L12, cov_p=robust_cov)
table.loc[table.index[i], test] = f.fvalue
table.loc[table.index[i], pr_test] = f.pvalue
# need to back out SSR from f_test
table.loc[table.index[i], 'df'] = r
col_order.append(cols.start)
index.append(mgr.get_term_name(term))
table.index = Index(index + ['Residual'])
table = table.iloc[np.argsort(col_order + [model.model.exog.shape[1]+1])]
# back out sum of squares from f_test
ssr = table[test] * table['df'] * model.ssr/model.df_resid
table['sum_sq'] = ssr
# fill in residual
table.loc['Residual', ['sum_sq','df', test, pr_test]] = (model.ssr,
model.df_resid,
np.nan, np.nan)
return table | Anova type II table for one fitted linear model.
Parameters
----------
model : fitted linear model results instance
A fitted linear model
**kwargs**
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
Notes
-----
Use of this function is discouraged. Use anova_lm instead.
Type II
Sum of Squares compares marginal contribution of terms. Thus, it is
not particularly useful for models with significant interaction terms. | anova2_lm_single | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def anova_lm(*args, **kwargs):
"""
Anova table for one or more fitted linear models.
Parameters
----------
args : fitted linear model results instance
One or more fitted linear models
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
typ : str or int {"I","II","III"} or {1,2,3}
The type of Anova test to perform. See notes.
robust : {None, "hc0", "hc1", "hc2", "hc3"}
Use heteroscedasticity-corrected coefficient covariance matrix.
If robust covariance is desired, it is recommended to use `hc3`.
Returns
-------
anova : DataFrame
When args is a single model, return is DataFrame with columns:
sum_sq : float64
Sum of squares for model terms.
df : float64
Degrees of freedom for model terms.
F : float64
F statistic value for significance of adding model terms.
PR(>F) : float64
P-value for significance of adding model terms.
When args is multiple models, return is DataFrame with columns:
df_resid : float64
Degrees of freedom of residuals in models.
ssr : float64
Sum of squares of residuals in models.
df_diff : float64
Degrees of freedom difference from previous model in args
ss_dff : float64
Difference in ssr from previous model in args
F : float64
F statistic comparing to previous model in args
PR(>F): float64
P-value for significance comparing to previous model in args
Notes
-----
Model statistics are given in the order of args. Models must have been fit
using the formula api.
See Also
--------
model_results.compare_f_test, model_results.compare_lm_test
Examples
--------
>>> import statsmodels.api as sm
>>> from statsmodels.formula.api import ols
>>> moore = sm.datasets.get_rdataset("Moore", "carData", cache=True) # load
>>> data = moore.data
>>> data = data.rename(columns={"partner.status" :
... "partner_status"}) # make name pythonic
>>> moore_lm = ols('conformity ~ C(fcategory, Sum)*C(partner_status, Sum)',
... data=data).fit()
>>> table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 Anova DataFrame
>>> print(table)
"""
typ = kwargs.get('typ', 1)
### Farm Out Single model Anova Type I, II, III, and IV ###
if len(args) == 1:
model = args[0]
return anova_single(model, **kwargs)
if typ not in [1, "I"]:
raise ValueError("Multiple models only supported for type I. "
"Got type %s" % str(typ))
test = kwargs.get("test", "F")
scale = kwargs.get("scale", None)
n_models = len(args)
pr_test = "Pr(>%s)" % test
names = ['df_resid', 'ssr', 'df_diff', 'ss_diff', test, pr_test]
table = DataFrame(np.zeros((n_models, 6)), columns=names)
if not scale: # assume biggest model is last
scale = args[-1].scale
table["ssr"] = [mdl.ssr for mdl in args]
table["df_resid"] = [mdl.df_resid for mdl in args]
table.loc[table.index[1:], "df_diff"] = -np.diff(table["df_resid"].values)
table["ss_diff"] = -table["ssr"].diff()
if test == "F":
table["F"] = table["ss_diff"] / table["df_diff"] / scale
table[pr_test] = stats.f.sf(table["F"], table["df_diff"],
table["df_resid"])
# for earlier scipy - stats.f.sf(np.nan, 10, 2) -> 0 not nan
table.loc[table['F'].isnull(), pr_test] = np.nan
return table | Anova table for one or more fitted linear models.
Parameters
----------
args : fitted linear model results instance
One or more fitted linear models
scale : float
Estimate of variance, If None, will be estimated from the largest
model. Default is None.
test : str {"F", "Chisq", "Cp"} or None
Test statistics to provide. Default is "F".
typ : str or int {"I","II","III"} or {1,2,3}
The type of Anova test to perform. See notes.
robust : {None, "hc0", "hc1", "hc2", "hc3"}
Use heteroscedasticity-corrected coefficient covariance matrix.
If robust covariance is desired, it is recommended to use `hc3`.
Returns
-------
anova : DataFrame
When args is a single model, return is DataFrame with columns:
sum_sq : float64
Sum of squares for model terms.
df : float64
Degrees of freedom for model terms.
F : float64
F statistic value for significance of adding model terms.
PR(>F) : float64
P-value for significance of adding model terms.
When args is multiple models, return is DataFrame with columns:
df_resid : float64
Degrees of freedom of residuals in models.
ssr : float64
Sum of squares of residuals in models.
df_diff : float64
Degrees of freedom difference from previous model in args
ss_dff : float64
Difference in ssr from previous model in args
F : float64
F statistic comparing to previous model in args
PR(>F): float64
P-value for significance comparing to previous model in args
Notes
-----
Model statistics are given in the order of args. Models must have been fit
using the formula api.
See Also
--------
model_results.compare_f_test, model_results.compare_lm_test
Examples
--------
>>> import statsmodels.api as sm
>>> from statsmodels.formula.api import ols
>>> moore = sm.datasets.get_rdataset("Moore", "carData", cache=True) # load
>>> data = moore.data
>>> data = data.rename(columns={"partner.status" :
... "partner_status"}) # make name pythonic
>>> moore_lm = ols('conformity ~ C(fcategory, Sum)*C(partner_status, Sum)',
... data=data).fit()
>>> table = sm.stats.anova_lm(moore_lm, typ=2) # Type 2 Anova DataFrame
>>> print(table) | anova_lm | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def _ssr_reduced_model(y, x, term_slices, params, keys):
"""
Residual sum of squares of OLS model excluding factors in `keys`
Assumes x matrix is orthogonal
Parameters
----------
y : array_like
dependent variable
x : array_like
independent variables
term_slices : a dict of slices
term_slices[key] is a boolean array specifies the parameters
associated with the factor `key`
params : ndarray
OLS solution of y = x * params
keys : keys for term_slices
factors to be excluded
Returns
-------
rss : float
residual sum of squares
df : int
degrees of freedom
"""
ind = _not_slice(term_slices, keys, x.shape[1])
params1 = params[ind]
ssr = np.subtract(y, x[:, ind].dot(params1))
ssr = ssr.T.dot(ssr)
df_resid = len(y) - len(params1)
return ssr, df_resid | Residual sum of squares of OLS model excluding factors in `keys`
Assumes x matrix is orthogonal
Parameters
----------
y : array_like
dependent variable
x : array_like
independent variables
term_slices : a dict of slices
term_slices[key] is a boolean array specifies the parameters
associated with the factor `key`
params : ndarray
OLS solution of y = x * params
keys : keys for term_slices
factors to be excluded
Returns
-------
rss : float
residual sum of squares
df : int
degrees of freedom | _ssr_reduced_model | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def _check_data_balanced(self):
"""raise if data is not balanced
This raises a ValueError if the data is not balanced, and
returns None if it is balance
Return might change
"""
factor_levels = 1
for wi in self.within:
factor_levels *= len(self.data[wi].unique())
cell_count = {}
for index in range(self.data.shape[0]):
key = []
for col in self.within:
key.append(self.data[col].iloc[index])
key = tuple(key)
if key in cell_count:
cell_count[key] = cell_count[key] + 1
else:
cell_count[key] = 1
error_message = "Data is unbalanced."
if len(cell_count) != factor_levels:
raise ValueError(error_message)
count = cell_count[key]
for key in cell_count:
if count != cell_count[key]:
raise ValueError(error_message)
if self.data.shape[0] > count * factor_levels:
raise ValueError('There are more than 1 element in a cell! Missing'
' factors?') | raise if data is not balanced
This raises a ValueError if the data is not balanced, and
returns None if it is balance
Return might change | _check_data_balanced | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def fit(self):
"""estimate the model and compute the Anova table
Returns
-------
AnovaResults instance
"""
y = self.data[self.depvar].values
# Construct OLS endog and exog from string using patsy
within = ['C(%s, Sum)' % i for i in self.within]
subject = 'C(%s, Sum)' % self.subject
factors = within + [subject]
mgr = FormulaManager()
x = mgr.get_matrices('*'.join(factors), data=self.data, pandas=False)
term_slices = mgr.get_term_name_slices(x)
for key in term_slices:
ind = np.array([False]*x.shape[1])
ind[term_slices[key]] = True
term_slices[key] = np.array(ind)
term_exclude = [':'.join(factors)]
ind = _not_slice(term_slices, term_exclude, x.shape[1])
x = x[:, ind]
# Fit OLS
model = OLS(y, x)
results = model.fit()
if model.rank < x.shape[1]:
raise ValueError('Independent variables are collinear.')
for i in term_exclude:
term_slices.pop(i)
for key in term_slices:
term_slices[key] = term_slices[key][ind]
params = results.params
df_resid = results.df_resid
ssr = results.ssr
columns = ['F Value', 'Num DF', 'Den DF', 'Pr > F']
anova_table = pd.DataFrame(np.zeros((0, 4)), columns=columns)
for key in term_slices:
if self.subject not in str(key) and str(key) not in ('Intercept', "1"):
# Independent variables are orthogonal
ssr1, df_resid1 = _ssr_reduced_model(
y, x, term_slices, params, [key])
df1 = df_resid1 - df_resid
msm = (ssr1 - ssr) / df1
if (str(key) == ':'.join(factors[:-1]) or
(str(key) + ':' + subject not in term_slices)):
mse = ssr / df_resid
df2 = df_resid
else:
ssr1, df_resid1 = _ssr_reduced_model(
y, x, term_slices, params,
[str(key) + ':' + subject])
df2 = df_resid1 - df_resid
mse = (ssr1 - ssr) / df2
F = msm / mse
p = stats.f.sf(F, df1, df2)
term = str(key).replace('C(', '').replace(', Sum)', '')
anova_table.loc[term, 'F Value'] = F
anova_table.loc[term, 'Num DF'] = df1
anova_table.loc[term, 'Den DF'] = df2
anova_table.loc[term, 'Pr > F'] = p
return AnovaResults(anova_table) | estimate the model and compute the Anova table
Returns
-------
AnovaResults instance | fit | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def summary(self):
"""create summary results
Returns
-------
summary : summary2.Summary instance
"""
summ = summary2.Summary()
summ.add_title('Anova')
summ.add_df(self.anova_table)
return summ | create summary results
Returns
-------
summary : summary2.Summary instance | summary | python | statsmodels/statsmodels | statsmodels/stats/anova.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/anova.py | BSD-3-Clause |
def _calc_nodewise_row(exog, idx, alpha):
"""calculates the nodewise_row values for the idxth variable, used to
estimate approx_inv_cov.
Parameters
----------
exog : array_like
The weighted design matrix for the current partition.
idx : scalar
Index of the current variable.
alpha : scalar or array_like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
Returns
-------
An array-like object of length p-1
Notes
-----
nodewise_row_i = arg min 1/(2n) ||exog_i - exog_-i gamma||_2^2
+ alpha ||gamma||_1
"""
p = exog.shape[1]
ind = list(range(p))
ind.pop(idx)
# handle array alphas
if not np.isscalar(alpha):
alpha = alpha[ind]
tmod = OLS(exog[:, idx], exog[:, ind])
nodewise_row = tmod.fit_regularized(alpha=alpha).params
return nodewise_row | calculates the nodewise_row values for the idxth variable, used to
estimate approx_inv_cov.
Parameters
----------
exog : array_like
The weighted design matrix for the current partition.
idx : scalar
Index of the current variable.
alpha : scalar or array_like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
Returns
-------
An array-like object of length p-1
Notes
-----
nodewise_row_i = arg min 1/(2n) ||exog_i - exog_-i gamma||_2^2
+ alpha ||gamma||_1 | _calc_nodewise_row | python | statsmodels/statsmodels | statsmodels/stats/regularized_covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/regularized_covariance.py | BSD-3-Clause |
def _calc_nodewise_weight(exog, nodewise_row, idx, alpha):
"""calculates the nodewise_weightvalue for the idxth variable, used to
estimate approx_inv_cov.
Parameters
----------
exog : array_like
The weighted design matrix for the current partition.
nodewise_row : array_like
The nodewise_row values for the current variable.
idx : scalar
Index of the current variable
alpha : scalar or array_like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
Returns
-------
A scalar
Notes
-----
nodewise_weight_i = sqrt(1/n ||exog,i - exog_-i nodewise_row||_2^2
+ alpha ||nodewise_row||_1)
"""
n, p = exog.shape
ind = list(range(p))
ind.pop(idx)
# handle array alphas
if not np.isscalar(alpha):
alpha = alpha[ind]
d = np.linalg.norm(exog[:, idx] - exog[:, ind].dot(nodewise_row))**2
d = np.sqrt(d / n + alpha * np.linalg.norm(nodewise_row, 1))
return d | calculates the nodewise_weightvalue for the idxth variable, used to
estimate approx_inv_cov.
Parameters
----------
exog : array_like
The weighted design matrix for the current partition.
nodewise_row : array_like
The nodewise_row values for the current variable.
idx : scalar
Index of the current variable
alpha : scalar or array_like
The penalty weight. If a scalar, the same penalty weight
applies to all variables in the model. If a vector, it
must have the same length as `params`, and contains a
penalty weight for each coefficient.
Returns
-------
A scalar
Notes
-----
nodewise_weight_i = sqrt(1/n ||exog,i - exog_-i nodewise_row||_2^2
+ alpha ||nodewise_row||_1) | _calc_nodewise_weight | python | statsmodels/statsmodels | statsmodels/stats/regularized_covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/regularized_covariance.py | BSD-3-Clause |
def _calc_approx_inv_cov(nodewise_row_l, nodewise_weight_l):
"""calculates the approximate inverse covariance matrix
Parameters
----------
nodewise_row_l : list
A list of array-like object where each object corresponds to
the nodewise_row values for the corresponding variable, should
be length p.
nodewise_weight_l : list
A list of scalars where each scalar corresponds to the nodewise_weight
value for the corresponding variable, should be length p.
Returns
------
An array-like object, p x p matrix
Notes
-----
nwr = nodewise_row
nww = nodewise_weight
approx_inv_cov_j = - 1 / nww_j [nwr_j,1,...,1,...nwr_j,p]
"""
p = len(nodewise_weight_l)
approx_inv_cov = -np.eye(p)
for idx in range(p):
ind = list(range(p))
ind.pop(idx)
approx_inv_cov[idx, ind] = nodewise_row_l[idx]
approx_inv_cov *= -1 / nodewise_weight_l[:, None]**2
return approx_inv_cov | calculates the approximate inverse covariance matrix
Parameters
----------
nodewise_row_l : list
A list of array-like object where each object corresponds to
the nodewise_row values for the corresponding variable, should
be length p.
nodewise_weight_l : list
A list of scalars where each scalar corresponds to the nodewise_weight
value for the corresponding variable, should be length p.
Returns
------
An array-like object, p x p matrix
Notes
-----
nwr = nodewise_row
nww = nodewise_weight
approx_inv_cov_j = - 1 / nww_j [nwr_j,1,...,1,...nwr_j,p] | _calc_approx_inv_cov | python | statsmodels/statsmodels | statsmodels/stats/regularized_covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/regularized_covariance.py | BSD-3-Clause |
def fit(self, alpha=0):
"""estimates the regularized inverse covariance using nodewise
regression
Parameters
----------
alpha : scalar
Regularizing constant
"""
n, p = self.exog.shape
nodewise_row_l = []
nodewise_weight_l = []
for idx in range(p):
nodewise_row = _calc_nodewise_row(self.exog, idx, alpha)
nodewise_row_l.append(nodewise_row)
nodewise_weight = _calc_nodewise_weight(self.exog, nodewise_row,
idx, alpha)
nodewise_weight_l.append(nodewise_weight)
nodewise_row_l = np.array(nodewise_row_l)
nodewise_weight_l = np.array(nodewise_weight_l)
approx_inv_cov = _calc_approx_inv_cov(nodewise_row_l,
nodewise_weight_l)
self._approx_inv_cov = approx_inv_cov | estimates the regularized inverse covariance using nodewise
regression
Parameters
----------
alpha : scalar
Regularizing constant | fit | python | statsmodels/statsmodels | statsmodels/stats/regularized_covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/regularized_covariance.py | BSD-3-Clause |
def transform_corr_normal(corr, method, return_var=False, possdef=True):
"""transform correlation matrix to be consistent at normal distribution
Parameters
----------
corr : array_like
correlation matrix, either Pearson, Gaussian-rank, Spearman, Kendall
or quadrant correlation matrix
method : string
type of covariance matrix
supported types are 'pearson', 'gauss_rank', 'kendal', 'spearman' and
'quadrant'
return_var : bool
If true, then the asymptotic variance of the normalized correlation
is also returned. The variance of the spearman correlation requires
numerical integration which is calculated with scipy's odeint.
possdef : not implemented yet
Check whether resulting correlation matrix for positive semidefinite
and return a positive semidefinite approximation if not.
Returns
-------
corr : ndarray
correlation matrix, consistent with correlation for a multivariate
normal distribution
var : ndarray (optional)
asymptotic variance of the correlation if requested by `return_var`.
Notes
-----
Pearson and Gaussian-rank correlation are consistent at the normal
distribution and will be returned without changes.
The other correlation matrices are not guaranteed to be positive
semidefinite in small sample after conversion, even if the underlying
untransformed correlation matrix is positive (semi)definite. Croux and
Dehon mention that nobs / k_vars should be larger than 3 for kendall and
larger than 2 for spearman.
References
----------
.. [1] Boudt, Kris, Jonathan Cornelissen, and Christophe Croux. “The
Gaussian Rank Correlation Estimator: Robustness Properties.”
Statistics and Computing 22, no. 2 (April 5, 2011): 471–83.
https://doi.org/10.1007/s11222-011-9237-0.
.. [2] Croux, Christophe, and Catherine Dehon. “Influence Functions of the
Spearman and Kendall Correlation Measures.”
Statistical Methods & Applications 19, no. 4 (May 12, 2010): 497–515.
https://doi.org/10.1007/s10260-010-0142-z.
"""
method = method.lower()
rho = np.asarray(corr)
var = None # initialize
if method in ['pearson', 'gauss_rank']:
corr_n = corr
if return_var:
var = (1 - rho**2)**2
elif method.startswith('kendal'):
corr_n = np.sin(np.pi / 2 * corr)
if return_var:
var = (1 - rho**2) * np.pi**2 * (
1./9 - 4 / np.pi**2 * np.arcsin(rho / 2)**2)
elif method == 'quadrant':
corr_n = np.sin(np.pi / 2 * corr)
if return_var:
var = (1 - rho**2) * (np.pi**2 / 4 - np.arcsin(rho)**2)
elif method.startswith('spearman'):
corr_n = 2 * np.sin(np.pi / 6 * corr)
# not clear which rho is in formula, should be normalized rho,
# but original corr coefficient seems to match results in articles
# rho = corr_n
if return_var:
# odeint only works if grid of rho is large, i.e. many points
# e.g. rho = np.linspace(0, 1, 101)
rho = np.atleast_1d(rho)
idx = np.argsort(rho)
rhos = rho[idx]
rhos = np.concatenate(([0], rhos))
t = np.arcsin(rhos / 2)
# drop np namespace here
sin, cos = np.sin, np.cos
var = (1 - rho**2 / 4) * pi2 / 9 # leading factor
f1 = lambda t, x: np.arcsin(sin(x) / (1 + 2 * cos(2 * x))) # noqa
f2 = lambda t, x: np.arcsin(sin(2 * x) / # noqa
np.sqrt(1 + 2 * cos(2 * x)))
f3 = lambda t, x: np.arcsin(sin(2 * x) / # noqa
(2 * np.sqrt(cos(2 * x))))
f4 = lambda t, x: np.arcsin(( 3 * sin(x) - sin(3 * x)) / # noqa
(4 * cos(2 * x)))
# todo check dimension, odeint return column (n, 1) array
hmax = 1e-1
rf1 = integrate.odeint(f1 , 0, t=t, hmax=hmax).squeeze()
rf2 = integrate.odeint(f2 , 0, t=t, hmax=hmax).squeeze()
rf3 = integrate.odeint(f3 , 0, t=t, hmax=hmax).squeeze()
rf4 = integrate.odeint(f4 , 0, t=t, hmax=hmax).squeeze()
fact = 1 + 144 * (-9 / 4. * pi2i * np.arcsin(rhos / 2)**2 +
pi2i * rf1 +
2 * pi2i * rf2 + pi2i * rf3 +
0.5 * pi2i * rf4)
# fact = 1 - 9 / 4 * pi2i * np.arcsin(rhos / 2)**2
fact2 = np.zeros_like(var) * np.nan
fact2[idx] = fact[1:]
var *= fact2
else:
raise ValueError('method not recognized')
if return_var:
return corr_n, var
else:
return corr_n | transform correlation matrix to be consistent at normal distribution
Parameters
----------
corr : array_like
correlation matrix, either Pearson, Gaussian-rank, Spearman, Kendall
or quadrant correlation matrix
method : string
type of covariance matrix
supported types are 'pearson', 'gauss_rank', 'kendal', 'spearman' and
'quadrant'
return_var : bool
If true, then the asymptotic variance of the normalized correlation
is also returned. The variance of the spearman correlation requires
numerical integration which is calculated with scipy's odeint.
possdef : not implemented yet
Check whether resulting correlation matrix for positive semidefinite
and return a positive semidefinite approximation if not.
Returns
-------
corr : ndarray
correlation matrix, consistent with correlation for a multivariate
normal distribution
var : ndarray (optional)
asymptotic variance of the correlation if requested by `return_var`.
Notes
-----
Pearson and Gaussian-rank correlation are consistent at the normal
distribution and will be returned without changes.
The other correlation matrices are not guaranteed to be positive
semidefinite in small sample after conversion, even if the underlying
untransformed correlation matrix is positive (semi)definite. Croux and
Dehon mention that nobs / k_vars should be larger than 3 for kendall and
larger than 2 for spearman.
References
----------
.. [1] Boudt, Kris, Jonathan Cornelissen, and Christophe Croux. “The
Gaussian Rank Correlation Estimator: Robustness Properties.”
Statistics and Computing 22, no. 2 (April 5, 2011): 471–83.
https://doi.org/10.1007/s11222-011-9237-0.
.. [2] Croux, Christophe, and Catherine Dehon. “Influence Functions of the
Spearman and Kendall Correlation Measures.”
Statistical Methods & Applications 19, no. 4 (May 12, 2010): 497–515.
https://doi.org/10.1007/s10260-010-0142-z. | transform_corr_normal | python | statsmodels/statsmodels | statsmodels/stats/covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/covariance.py | BSD-3-Clause |
def corr_rank(data):
"""Spearman rank correlation
simplified version of scipy.stats.spearmanr
"""
x = np.asarray(data)
axisout = 0
ar = np.apply_along_axis(stats.rankdata, axisout, x)
corr = np.corrcoef(ar, rowvar=False)
return corr | Spearman rank correlation
simplified version of scipy.stats.spearmanr | corr_rank | python | statsmodels/statsmodels | statsmodels/stats/covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/covariance.py | BSD-3-Clause |
def corr_normal_scores(data):
"""Gaussian rank (normal scores) correlation
Status: unverified, subject to change
Parameters
----------
data : array_like
2-D data with observations in rows and variables in columns
Returns
-------
corr : ndarray
correlation matrix
References
----------
.. [1] Boudt, Kris, Jonathan Cornelissen, and Christophe Croux. “The
Gaussian Rank Correlation Estimator: Robustness Properties.”
Statistics and Computing 22, no. 2 (April 5, 2011): 471–83.
https://doi.org/10.1007/s11222-011-9237-0.
"""
# TODO: a full version should be same as scipy spearmanr
# I think that's not true the croux et al articles mention different
# results
# needs verification for the p-value calculation
x = np.asarray(data)
nobs = x.shape[0]
axisout = 0
ar = np.apply_along_axis(stats.rankdata, axisout, x)
ar = stats.norm.ppf(ar / (nobs + 1))
corr = np.corrcoef(ar, rowvar=axisout)
return corr | Gaussian rank (normal scores) correlation
Status: unverified, subject to change
Parameters
----------
data : array_like
2-D data with observations in rows and variables in columns
Returns
-------
corr : ndarray
correlation matrix
References
----------
.. [1] Boudt, Kris, Jonathan Cornelissen, and Christophe Croux. “The
Gaussian Rank Correlation Estimator: Robustness Properties.”
Statistics and Computing 22, no. 2 (April 5, 2011): 471–83.
https://doi.org/10.1007/s11222-011-9237-0. | corr_normal_scores | python | statsmodels/statsmodels | statsmodels/stats/covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/covariance.py | BSD-3-Clause |
def corr_quadrant(data, transform=np.sign, normalize=False):
"""Quadrant correlation
Status: unverified, subject to change
Parameters
----------
data : array_like
2-D data with observations in rows and variables in columns
Returns
-------
corr : ndarray
correlation matrix
References
----------
.. [1] Croux, Christophe, and Catherine Dehon. “Influence Functions of the
Spearman and Kendall Correlation Measures.”
Statistical Methods & Applications 19, no. 4 (May 12, 2010): 497–515.
https://doi.org/10.1007/s10260-010-0142-z.
"""
# try also with tanh transform, a starting corr for DetXXX
# tanh produces a cov not a corr
x = np.asarray(data)
nobs = x.shape[0]
med = np.median(x, 0)
x_dm = transform(x - med)
corr = x_dm.T.dot(x_dm) / nobs
if normalize:
std = np.sqrt(np.diag(corr))
corr /= std
corr /= std[:, None]
return corr | Quadrant correlation
Status: unverified, subject to change
Parameters
----------
data : array_like
2-D data with observations in rows and variables in columns
Returns
-------
corr : ndarray
correlation matrix
References
----------
.. [1] Croux, Christophe, and Catherine Dehon. “Influence Functions of the
Spearman and Kendall Correlation Measures.”
Statistical Methods & Applications 19, no. 4 (May 12, 2010): 497–515.
https://doi.org/10.1007/s10260-010-0142-z. | corr_quadrant | python | statsmodels/statsmodels | statsmodels/stats/covariance.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/covariance.py | BSD-3-Clause |
def partial_project(endog, exog):
'''helper function to get linear projection or partialling out of variables
endog variables are projected on exog variables
Parameters
----------
endog : ndarray
array of variables where the effect of exog is partialled out.
exog : ndarray
array of variables on which the endog variables are projected.
Returns
-------
res : instance of Bunch with
- params : OLS parameter estimates from projection of endog on exog
- fittedvalues : predicted values of endog given exog
- resid : residual of the regression, values of endog with effect of
exog partialled out
Notes
-----
This is no-frills mainly for internal calculations, no error checking or
array conversion is performed, at least for now.
'''
x1, x2 = endog, exog
params = np.linalg.pinv(x2).dot(x1)
predicted = x2.dot(params)
residual = x1 - predicted
res = Bunch(params=params,
fittedvalues=predicted,
resid=residual)
return res | helper function to get linear projection or partialling out of variables
endog variables are projected on exog variables
Parameters
----------
endog : ndarray
array of variables where the effect of exog is partialled out.
exog : ndarray
array of variables on which the endog variables are projected.
Returns
-------
res : instance of Bunch with
- params : OLS parameter estimates from projection of endog on exog
- fittedvalues : predicted values of endog given exog
- resid : residual of the regression, values of endog with effect of
exog partialled out
Notes
-----
This is no-frills mainly for internal calculations, no error checking or
array conversion is performed, at least for now. | partial_project | python | statsmodels/statsmodels | statsmodels/stats/multivariate_tools.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate_tools.py | BSD-3-Clause |
def cancorr(x1, x2, demean=True, standardize=False):
'''canonical correlation coefficient beween 2 arrays
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable
standardize : bool
If standardize is true, then each variable is demeaned and divided by
its standard deviation. Rescaling does not change the canonical
correlation coefficients.
Returns
-------
ccorr : ndarray, 1d
canonical correlation coefficients, sorted from largest to smallest.
Note, that these are the square root of the eigenvalues.
Notes
-----
This is a helper function for other statistical functions. It only
calculates the canonical correlation coefficients and does not do a full
canoncial correlation analysis
The canonical correlation coefficient is calculated with the generalized
matrix inverse and does not raise an exception if one of the data arrays
have less than full column rank.
See Also
--------
cc_ranktest
cc_stats
CCA not yet
'''
#x, y = x1, x2
if demean or standardize:
x1 = (x1 - x1.mean(0))
x2 = (x2 - x2.mean(0))
if standardize:
#std does not make a difference to canonical correlation coefficients
x1 /= x1.std(0)
x2 /= x2.std(0)
t1 = np.linalg.pinv(x1).dot(x2)
t2 = np.linalg.pinv(x2).dot(x1)
m = t1.dot(t2)
cc = np.sqrt(np.linalg.eigvals(m))
cc.sort()
return cc[::-1] | canonical correlation coefficient beween 2 arrays
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable
standardize : bool
If standardize is true, then each variable is demeaned and divided by
its standard deviation. Rescaling does not change the canonical
correlation coefficients.
Returns
-------
ccorr : ndarray, 1d
canonical correlation coefficients, sorted from largest to smallest.
Note, that these are the square root of the eigenvalues.
Notes
-----
This is a helper function for other statistical functions. It only
calculates the canonical correlation coefficients and does not do a full
canoncial correlation analysis
The canonical correlation coefficient is calculated with the generalized
matrix inverse and does not raise an exception if one of the data arrays
have less than full column rank.
See Also
--------
cc_ranktest
cc_stats
CCA not yet | cancorr | python | statsmodels/statsmodels | statsmodels/stats/multivariate_tools.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate_tools.py | BSD-3-Clause |
def cc_ranktest(x1, x2, demean=True, fullrank=False):
'''rank tests based on smallest canonical correlation coefficients
Anderson canonical correlations test (LM test) and
Cragg-Donald test (Wald test)
Assumes homoskedasticity and independent observations, overrejects if
there is heteroscedasticity or autocorrelation.
The Null Hypothesis is that the rank is k - 1, the alternative hypothesis
is that the rank is at least k.
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable.
fullrank : bool
If true, then only the test that the matrix has full rank is returned.
If false, the test for all possible ranks are returned. However, no
the p-values are not corrected for the multiplicity of tests.
Returns
-------
value : float
value of the test statistic
p-value : float
p-value for the test Null Hypothesis tha the smallest canonical
correlation coefficient is zero. based on chi-square distribution
df : int
degrees of freedom for thechi-square distribution in the hypothesis test
ccorr : ndarray, 1d
All canonical correlation coefficients sorted from largest to smallest.
Notes
-----
Degrees of freedom for the distribution of the test statistic are based on
number of columns of x1 and x2 and not on their matrix rank.
(I'm not sure yet what the interpretation of the test is if x1 or x2 are of
reduced rank.)
See Also
--------
cancorr
cc_stats
'''
from scipy import stats
nobs1, k1 = x1.shape
nobs2, k2 = x2.shape
cc = cancorr(x1, x2, demean=demean)
cc2 = cc * cc
if fullrank:
df = np.abs(k1 - k2) + 1
value = nobs1 * cc2[-1]
w_value = nobs1 * (cc2[-1] / (1. - cc2[-1]))
return value, stats.chi2.sf(value, df), df, cc, w_value, stats.chi2.sf(w_value, df)
else:
r = np.arange(min(k1, k2))[::-1]
df = (k1 - r) * (k2 - r)
values = nobs1 * cc2[::-1].cumsum()
w_values = nobs1 * (cc2 / (1. - cc2))[::-1].cumsum()
return values, stats.chi2.sf(values, df), df, cc, w_values, stats.chi2.sf(w_values, df) | rank tests based on smallest canonical correlation coefficients
Anderson canonical correlations test (LM test) and
Cragg-Donald test (Wald test)
Assumes homoskedasticity and independent observations, overrejects if
there is heteroscedasticity or autocorrelation.
The Null Hypothesis is that the rank is k - 1, the alternative hypothesis
is that the rank is at least k.
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable.
fullrank : bool
If true, then only the test that the matrix has full rank is returned.
If false, the test for all possible ranks are returned. However, no
the p-values are not corrected for the multiplicity of tests.
Returns
-------
value : float
value of the test statistic
p-value : float
p-value for the test Null Hypothesis tha the smallest canonical
correlation coefficient is zero. based on chi-square distribution
df : int
degrees of freedom for thechi-square distribution in the hypothesis test
ccorr : ndarray, 1d
All canonical correlation coefficients sorted from largest to smallest.
Notes
-----
Degrees of freedom for the distribution of the test statistic are based on
number of columns of x1 and x2 and not on their matrix rank.
(I'm not sure yet what the interpretation of the test is if x1 or x2 are of
reduced rank.)
See Also
--------
cancorr
cc_stats | cc_ranktest | python | statsmodels/statsmodels | statsmodels/stats/multivariate_tools.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate_tools.py | BSD-3-Clause |
def cc_stats(x1, x2, demean=True):
'''MANOVA statistics based on canonical correlation coefficient
Calculates Pillai's Trace, Wilk's Lambda, Hotelling's Trace and
Roy's Largest Root.
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable.
Returns
-------
res : dict
Dictionary containing the test statistics.
Notes
-----
same as `canon` in Stata
missing: F-statistics and p-values
TODO: should return a results class instead
produces nans sometimes, singular, perfect correlation of x1, x2 ?
'''
nobs1, k1 = x1.shape # endogenous ?
nobs2, k2 = x2.shape
cc = cancorr(x1, x2, demean=demean)
cc2 = cc**2
lam = (cc2 / (1 - cc2)) # what if max cc2 is 1 ?
# Problem: ccr might not care if x1 or x2 are reduced rank,
# but df will depend on rank
df_model = k1 * k2 # df_hypothesis (we do not include mean in x1, x2)
df_resid = k1 * (nobs1 - k2 - demean)
m = 0.5 * (df_model - k1)
pt_value = cc2.sum() # Pillai's trace
wl_value = np.product(1 / (1 + lam)) # Wilk's Lambda
ht_value = lam.sum() # Hotelling's Trace
rm_value = lam.max() # Roy's largest root
#from scipy import stats
# what's the distribution, the test statistic ?
res = {}
res['canonical correlation coefficient'] = cc
res['eigenvalues'] = lam
res["Pillai's Trace"] = pt_value
res["Wilk's Lambda"] = wl_value
res["Hotelling's Trace"] = ht_value
res["Roy's Largest Root"] = rm_value
res['df_resid'] = df_resid
res['df_m'] = m
return res | MANOVA statistics based on canonical correlation coefficient
Calculates Pillai's Trace, Wilk's Lambda, Hotelling's Trace and
Roy's Largest Root.
Parameters
----------
x1, x2 : ndarrays, 2_D
two 2-dimensional data arrays, observations in rows, variables in columns
demean : bool
If demean is true, then the mean is subtracted from each variable.
Returns
-------
res : dict
Dictionary containing the test statistics.
Notes
-----
same as `canon` in Stata
missing: F-statistics and p-values
TODO: should return a results class instead
produces nans sometimes, singular, perfect correlation of x1, x2 ? | cc_stats | python | statsmodels/statsmodels | statsmodels/stats/multivariate_tools.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/multivariate_tools.py | BSD-3-Clause |
def test_poisson(count, nobs, value, method=None, alternative="two-sided",
dispersion=1):
"""Test for one sample poisson mean or rate
Parameters
----------
count : array_like
Observed count, number of events.
nobs : arrat_like
Currently this is total exposure time of the count variable.
This will likely change.
value : float, array_like
This is the value of poisson rate under the null hypothesis.
method : str
Method to use for confidence interval.
This is required, there is currently no default method.
See Notes for available methods.
alternative : {'two-sided', 'smaller', 'larger'}
alternative hypothesis, which can be two-sided or either one of the
one-sided tests.
dispersion : float
Dispersion scale coefficient for Poisson QMLE. Default is that the
data follows a Poisson distribution. Dispersion different from 1
correspond to excess-dispersion in Poisson quasi-likelihood (GLM).
Dispersion coeffficient different from one is currently only used in
wald and score method.
Returns
-------
HolderTuple instance with test statistic, pvalue and other attributes.
Notes
-----
The implementatio of the hypothesis test is mainly based on the references
for the confidence interval, see confint_poisson.
Available methods are:
- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
computation. This does not use continuity correction for the center of
the confidence interval.
- "exact-c" central confidence interval based on gamma distribution
- "midp-c" : based on midp correction of central exact confidence interval.
this uses numerical inversion of the test function. not vectorized.
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.
See Also
--------
confint_poisson
"""
n = nobs # short hand
rate = count / n
if method is None:
msg = "method needs to be specified, currently no default method"
raise ValueError(msg)
if dispersion != 1:
if method not in ["wald", "waldcc", "score"]:
msg = "excess dispersion only supported in wald and score methods"
raise ValueError(msg)
dist = "normal"
if method == "wald":
std = np.sqrt(dispersion * rate / n)
statistic = (rate - value) / std
elif method == "waldccv":
# WCC in Barker 2002
# add 0.5 event, not 0.5 event rate as in waldcc
# std = np.sqrt((rate + 0.5 / n) / n)
# statistic = (rate + 0.5 / n - value) / std
std = np.sqrt(dispersion * (rate + 0.5 / n) / n)
statistic = (rate - value) / std
elif method == "score":
std = np.sqrt(dispersion * value / n)
statistic = (rate - value) / std
pvalue = stats.norm.sf(statistic)
elif method.startswith("exact-c") or method.startswith("midp-c"):
pv1 = stats.poisson.cdf(count, n * value)
pv2 = stats.poisson.sf(count - 1, n * value)
if method.startswith("midp-c"):
pv1 = pv1 - 0.5 * stats.poisson.pmf(count, n * value)
pv2 = pv2 - 0.5 * stats.poisson.pmf(count, n * value)
if alternative == "two-sided":
pvalue = 2 * np.minimum(pv1, pv2)
elif alternative == "larger":
pvalue = pv2
elif alternative == "smaller":
pvalue = pv1
else:
msg = 'alternative should be "two-sided", "larger" or "smaller"'
raise ValueError(msg)
statistic = np.nan
dist = "Poisson"
elif method == "sqrt":
std = 0.5
statistic = (np.sqrt(count) - np.sqrt(n * value)) / std
elif method == "sqrt-a":
# anscombe, based on Swift 2009 (with transformation to rate)
std = 0.5
statistic = (np.sqrt(count + 3 / 8) - np.sqrt(n * value + 3 / 8)) / std
elif method == "sqrt-v":
# vandenbroucke, based on Swift 2009 (with transformation to rate)
std = 0.5
crit = stats.norm.isf(0.025)
statistic = (np.sqrt(count + (crit**2 + 2) / 12) -
# np.sqrt(n * value + (crit**2 + 2) / 12)) / std
np.sqrt(n * value)) / std
else:
raise ValueError("unknown method %s" % method)
if dist == 'normal':
statistic, pvalue = _zstat_generic2(statistic, 1, alternative)
res = HolderTuple(
statistic=statistic,
pvalue=np.clip(pvalue, 0, 1),
distribution=dist,
method=method,
alternative=alternative,
rate=rate,
nobs=n
)
return res | Test for one sample poisson mean or rate
Parameters
----------
count : array_like
Observed count, number of events.
nobs : arrat_like
Currently this is total exposure time of the count variable.
This will likely change.
value : float, array_like
This is the value of poisson rate under the null hypothesis.
method : str
Method to use for confidence interval.
This is required, there is currently no default method.
See Notes for available methods.
alternative : {'two-sided', 'smaller', 'larger'}
alternative hypothesis, which can be two-sided or either one of the
one-sided tests.
dispersion : float
Dispersion scale coefficient for Poisson QMLE. Default is that the
data follows a Poisson distribution. Dispersion different from 1
correspond to excess-dispersion in Poisson quasi-likelihood (GLM).
Dispersion coeffficient different from one is currently only used in
wald and score method.
Returns
-------
HolderTuple instance with test statistic, pvalue and other attributes.
Notes
-----
The implementatio of the hypothesis test is mainly based on the references
for the confidence interval, see confint_poisson.
Available methods are:
- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
computation. This does not use continuity correction for the center of
the confidence interval.
- "exact-c" central confidence interval based on gamma distribution
- "midp-c" : based on midp correction of central exact confidence interval.
this uses numerical inversion of the test function. not vectorized.
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.
See Also
--------
confint_poisson | test_poisson | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def confint_poisson(count, exposure, method=None, alpha=0.05,
alternative="two-sided"):
"""Confidence interval for a Poisson mean or rate
The function is vectorized for all methods except "midp-c", which uses
an iterative method to invert the hypothesis test function.
All current methods are central, that is the probability of each tail is
smaller or equal to alpha / 2.
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
This will likely change.
method : str
Method to use for confidence interval
This is required, there is currently no default method
alpha : float in (0, 1)
Significance level, nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
default: "two-sided"
Specifies whether to calculate a two-sided or one-sided confidence
interval.
Returns
-------
tuple (low, upp) : confidence limits.
When alternative is not "two-sided", lower or upper bound is set to
0 or inf respectively.
Notes
-----
Methods are mainly based on Barker (2002) [1]_ and Swift (2009) [3]_.
Available methods are:
- "exact-c" central confidence interval based on gamma distribution
- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
computation. This does not use continuity correction for the center of
the confidence interval.
- "midp-c" : based on midp correction of central exact confidence interval.
this uses numerical inversion of the test function. not vectorized.
- "jeffreys" : based on Jeffreys' prior. computed using gamma distribution
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.
- "sqrt-centcc" will likely be dropped. anscombe with continuity corrected
center.
(Similar to R survival cipoisson, but without the 3/8 right shift of
the confidence interval).
sqrt-cent is the same as sqrt-a, using a different computation, will be
deleted.
sqrt-v is a corrected square root method attributed to vandenbrouke, which
might also be deleted.
Todo:
- missing dispersion,
- maybe split nobs and exposure (? needed in NB). Exposure could be used
to standardize rate.
- modified wald, switch method if count=0.
See Also
--------
test_poisson
References
----------
.. [1] Barker, Lawrence. 2002. “A Comparison of Nine Confidence Intervals
for a Poisson Parameter When the Expected Number of Events Is ≤ 5.”
The American Statistician 56 (2): 85–89.
https://doi.org/10.1198/000313002317572736.
.. [2] Patil, VV, and HV Kulkarni. 2012. “Comparison of Confidence
Intervals for the Poisson Mean: Some New Aspects.”
REVSTAT–Statistical Journal 10(2): 211–27.
.. [3] Swift, Michael Bruce. 2009. “Comparison of Confidence Intervals for
a Poisson Mean – Further Considerations.” Communications in Statistics -
Theory and Methods 38 (5): 748–59.
https://doi.org/10.1080/03610920802255856.
"""
n = exposure # short hand
rate = count / exposure
if alternative == 'two-sided':
alpha = alpha / 2
elif alternative not in ['larger', 'smaller']:
raise NotImplementedError(
f"alternative {alternative} is not available")
if method is None:
msg = "method needs to be specified, currently no default method"
raise ValueError(msg)
if method == "wald":
whalf = stats.norm.isf(alpha) * np.sqrt(rate / n)
ci = (rate - whalf, rate + whalf)
elif method == "waldccv":
# based on WCC in Barker 2002
# add 0.5 event, not 0.5 event rate as in BARKER waldcc
whalf = stats.norm.isf(alpha) * np.sqrt((rate + 0.5 / n) / n)
ci = (rate - whalf, rate + whalf)
elif method == "score":
crit = stats.norm.isf(alpha)
center = count + crit**2 / 2
whalf = crit * np.sqrt(count + crit**2 / 4)
ci = ((center - whalf) / n, (center + whalf) / n)
elif method == "midp-c":
# note local alpha above is for one tail
ci = _invert_test_confint(count, n, alpha=2 * alpha, method="midp-c",
method_start="exact-c")
elif method == "sqrt":
# drop, wrong n
crit = stats.norm.isf(alpha)
center = rate + crit**2 / (4 * n)
whalf = crit * np.sqrt(rate / n)
ci = (center - whalf, center + whalf)
elif method == "sqrt-cent":
crit = stats.norm.isf(alpha)
center = count + crit**2 / 4
whalf = crit * np.sqrt(count + 3 / 8)
ci = ((center - whalf) / n, (center + whalf) / n)
elif method == "sqrt-centcc":
# drop with cc, does not match cipoisson in R survival
crit = stats.norm.isf(alpha)
# avoid sqrt of negative value if count=0
center_low = np.sqrt(np.maximum(count + 3 / 8 - 0.5, 0))
center_upp = np.sqrt(count + 3 / 8 + 0.5)
whalf = crit / 2
# above is for ci of count
ci = (((np.maximum(center_low - whalf, 0))**2 - 3 / 8) / n,
((center_upp + whalf)**2 - 3 / 8) / n)
# crit = stats.norm.isf(alpha)
# center = count
# whalf = crit * np.sqrt((count + 3 / 8 + 0.5))
# ci = ((center - whalf - 0.5) / n, (center + whalf + 0.5) / n)
elif method == "sqrt-a":
# anscombe, based on Swift 2009 (with transformation to rate)
crit = stats.norm.isf(alpha)
center = np.sqrt(count + 3 / 8)
whalf = crit / 2
# above is for ci of count
ci = (((np.maximum(center - whalf, 0))**2 - 3 / 8) / n,
((center + whalf)**2 - 3 / 8) / n)
elif method == "sqrt-v":
# vandenbroucke, based on Swift 2009 (with transformation to rate)
crit = stats.norm.isf(alpha)
center = np.sqrt(count + (crit**2 + 2) / 12)
whalf = crit / 2
# above is for ci of count
ci = (np.maximum(center - whalf, 0))**2 / n, (center + whalf)**2 / n
elif method in ["gamma", "exact-c"]:
# garwood exact, gamma
low = stats.gamma.ppf(alpha, count) / exposure
upp = stats.gamma.isf(alpha, count+1) / exposure
if np.isnan(low).any():
# case with count = 0
if np.size(low) == 1:
low = 0.0
else:
low[np.isnan(low)] = 0.0
ci = (low, upp)
elif method.startswith("jeff"):
# jeffreys, gamma
countc = count + 0.5
ci = (stats.gamma.ppf(alpha, countc) / exposure,
stats.gamma.isf(alpha, countc) / exposure)
else:
raise ValueError("unknown method %s" % method)
if alternative == "larger":
ci = (0, ci[1])
elif alternative == "smaller":
ci = (ci[0], np.inf)
ci = (np.maximum(ci[0], 0), ci[1])
return ci | Confidence interval for a Poisson mean or rate
The function is vectorized for all methods except "midp-c", which uses
an iterative method to invert the hypothesis test function.
All current methods are central, that is the probability of each tail is
smaller or equal to alpha / 2.
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
This will likely change.
method : str
Method to use for confidence interval
This is required, there is currently no default method
alpha : float in (0, 1)
Significance level, nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
default: "two-sided"
Specifies whether to calculate a two-sided or one-sided confidence
interval.
Returns
-------
tuple (low, upp) : confidence limits.
When alternative is not "two-sided", lower or upper bound is set to
0 or inf respectively.
Notes
-----
Methods are mainly based on Barker (2002) [1]_ and Swift (2009) [3]_.
Available methods are:
- "exact-c" central confidence interval based on gamma distribution
- "score" : based on score test, uses variance under null value
- "wald" : based on wald test, uses variance base on estimated rate.
- "waldccv" : based on wald test with 0.5 count added to variance
computation. This does not use continuity correction for the center of
the confidence interval.
- "midp-c" : based on midp correction of central exact confidence interval.
this uses numerical inversion of the test function. not vectorized.
- "jeffreys" : based on Jeffreys' prior. computed using gamma distribution
- "sqrt" : based on square root transformed counts
- "sqrt-a" based on Anscombe square root transformation of counts + 3/8.
- "sqrt-centcc" will likely be dropped. anscombe with continuity corrected
center.
(Similar to R survival cipoisson, but without the 3/8 right shift of
the confidence interval).
sqrt-cent is the same as sqrt-a, using a different computation, will be
deleted.
sqrt-v is a corrected square root method attributed to vandenbrouke, which
might also be deleted.
Todo:
- missing dispersion,
- maybe split nobs and exposure (? needed in NB). Exposure could be used
to standardize rate.
- modified wald, switch method if count=0.
See Also
--------
test_poisson
References
----------
.. [1] Barker, Lawrence. 2002. “A Comparison of Nine Confidence Intervals
for a Poisson Parameter When the Expected Number of Events Is ≤ 5.”
The American Statistician 56 (2): 85–89.
https://doi.org/10.1198/000313002317572736.
.. [2] Patil, VV, and HV Kulkarni. 2012. “Comparison of Confidence
Intervals for the Poisson Mean: Some New Aspects.”
REVSTAT–Statistical Journal 10(2): 211–27.
.. [3] Swift, Michael Bruce. 2009. “Comparison of Confidence Intervals for
a Poisson Mean – Further Considerations.” Communications in Statistics -
Theory and Methods 38 (5): 748–59.
https://doi.org/10.1080/03610920802255856. | confint_poisson | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def tolerance_int_poisson(count, exposure, prob=0.95, exposure_new=1.,
method=None, alpha=0.05,
alternative="two-sided"):
"""tolerance interval for a poisson observation
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
prob : float in (0, 1)
Probability of poisson interval, often called "content".
With known parameters, each tail would have at most probability
``1 - prob / 2`` in the two-sided interval.
exposure_new : float
Exposure of the new or predicted observation.
method : str
Method to used for confidence interval of the estimate of the
poisson rate, used in `confint_poisson`.
This is required, there is currently no default method.
alpha : float in (0, 1)
Significance level for the confidence interval of the estimate of the
Poisson rate. Nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
The tolerance interval can be two-sided or one-sided.
Alternative "larger" provides the upper bound of the confidence
interval, larger counts are outside the interval.
Returns
-------
tuple (low, upp) of limits of tolerance interval.
The tolerance interval is a closed interval, that is both ``low`` and
``upp`` are in the interval.
Notes
-----
verified against R package tolerance `poistol.int`
See Also
--------
confint_poisson
confint_quantile_poisson
References
----------
.. [1] Hahn, Gerald J., and William Q. Meeker. 1991. Statistical Intervals:
A Guide for Practitioners. 1st ed. Wiley Series in Probability and
Statistics. Wiley. https://doi.org/10.1002/9780470316771.
.. [2] Hahn, Gerald J., and Ramesh Chandra. 1981. “Tolerance Intervals for
Poisson and Binomial Variables.” Journal of Quality Technology 13 (2):
100–110. https://doi.org/10.1080/00224065.1981.11980998.
"""
prob_tail = 1 - prob
alpha_ = alpha
if alternative != "two-sided":
# confint_poisson does not have one-sided alternatives
alpha_ = alpha * 2
low, upp = confint_poisson(count, exposure, method=method, alpha=alpha_)
if exposure_new != 1:
low *= exposure_new
upp *= exposure_new
if alternative == "two-sided":
low_pred = stats.poisson.ppf(prob_tail / 2, low)
upp_pred = stats.poisson.ppf(1 - prob_tail / 2, upp)
elif alternative == "larger":
low_pred = 0
upp_pred = stats.poisson.ppf(1 - prob_tail, upp)
elif alternative == "smaller":
low_pred = stats.poisson.ppf(prob_tail, low)
upp_pred = np.inf
# clip -1 of ppf(0)
low_pred = np.maximum(low_pred, 0)
return low_pred, upp_pred | tolerance interval for a poisson observation
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
prob : float in (0, 1)
Probability of poisson interval, often called "content".
With known parameters, each tail would have at most probability
``1 - prob / 2`` in the two-sided interval.
exposure_new : float
Exposure of the new or predicted observation.
method : str
Method to used for confidence interval of the estimate of the
poisson rate, used in `confint_poisson`.
This is required, there is currently no default method.
alpha : float in (0, 1)
Significance level for the confidence interval of the estimate of the
Poisson rate. Nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
The tolerance interval can be two-sided or one-sided.
Alternative "larger" provides the upper bound of the confidence
interval, larger counts are outside the interval.
Returns
-------
tuple (low, upp) of limits of tolerance interval.
The tolerance interval is a closed interval, that is both ``low`` and
``upp`` are in the interval.
Notes
-----
verified against R package tolerance `poistol.int`
See Also
--------
confint_poisson
confint_quantile_poisson
References
----------
.. [1] Hahn, Gerald J., and William Q. Meeker. 1991. Statistical Intervals:
A Guide for Practitioners. 1st ed. Wiley Series in Probability and
Statistics. Wiley. https://doi.org/10.1002/9780470316771.
.. [2] Hahn, Gerald J., and Ramesh Chandra. 1981. “Tolerance Intervals for
Poisson and Binomial Variables.” Journal of Quality Technology 13 (2):
100–110. https://doi.org/10.1080/00224065.1981.11980998. | tolerance_int_poisson | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def confint_quantile_poisson(count, exposure, prob, exposure_new=1.,
method=None, alpha=0.05,
alternative="two-sided"):
"""confidence interval for quantile of poisson random variable
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
prob : float in (0, 1)
Probability for the quantile, e.g. 0.95 to get the upper 95% quantile.
With known mean mu, the quantile would be poisson.ppf(prob, mu).
exposure_new : float
Exposure of the new or predicted observation.
method : str
Method to used for confidence interval of the estimate of the
poisson rate, used in `confint_poisson`.
This is required, there is currently no default method.
alpha : float in (0, 1)
Significance level for the confidence interval of the estimate of the
Poisson rate. Nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
The tolerance interval can be two-sided or one-sided.
Alternative "larger" provides the upper bound of the confidence
interval, larger counts are outside the interval.
Returns
-------
tuple (low, upp) of limits of tolerance interval.
The confidence interval is a closed interval, that is both ``low`` and
``upp`` are in the interval.
See Also
--------
confint_poisson
tolerance_int_poisson
References
----------
Hahn, Gerald J, and William Q Meeker. 2010. Statistical Intervals: A Guide
for Practitioners.
"""
alpha_ = alpha
if alternative != "two-sided":
# confint_poisson does not have one-sided alternatives
alpha_ = alpha * 2
low, upp = confint_poisson(count, exposure, method=method, alpha=alpha_)
if exposure_new != 1:
low *= exposure_new
upp *= exposure_new
if alternative == "two-sided":
low_pred = stats.poisson.ppf(prob, low)
upp_pred = stats.poisson.ppf(prob, upp)
elif alternative == "larger":
low_pred = 0
upp_pred = stats.poisson.ppf(prob, upp)
elif alternative == "smaller":
low_pred = stats.poisson.ppf(prob, low)
upp_pred = np.inf
# clip -1 of ppf(0)
low_pred = np.maximum(low_pred, 0)
return low_pred, upp_pred | confidence interval for quantile of poisson random variable
Parameters
----------
count : array_like
Observed count, number of events.
exposure : arrat_like
Currently this is total exposure time of the count variable.
prob : float in (0, 1)
Probability for the quantile, e.g. 0.95 to get the upper 95% quantile.
With known mean mu, the quantile would be poisson.ppf(prob, mu).
exposure_new : float
Exposure of the new or predicted observation.
method : str
Method to used for confidence interval of the estimate of the
poisson rate, used in `confint_poisson`.
This is required, there is currently no default method.
alpha : float in (0, 1)
Significance level for the confidence interval of the estimate of the
Poisson rate. Nominal coverage of the confidence interval is
1 - alpha.
alternative : {"two-sider", "larger", "smaller")
The tolerance interval can be two-sided or one-sided.
Alternative "larger" provides the upper bound of the confidence
interval, larger counts are outside the interval.
Returns
-------
tuple (low, upp) of limits of tolerance interval.
The confidence interval is a closed interval, that is both ``low`` and
``upp`` are in the interval.
See Also
--------
confint_poisson
tolerance_int_poisson
References
----------
Hahn, Gerald J, and William Q Meeker. 2010. Statistical Intervals: A Guide
for Practitioners. | confint_quantile_poisson | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def _invert_test_confint(count, nobs, alpha=0.05, method="midp-c",
method_start="exact-c"):
"""invert hypothesis test to get confidence interval
"""
def func(r):
v = (test_poisson(count, nobs, value=r, method=method)[1] -
alpha)**2
return v
ci = confint_poisson(count, nobs, method=method_start)
low = optimize.fmin(func, ci[0], xtol=1e-8, disp=False)
upp = optimize.fmin(func, ci[1], xtol=1e-8, disp=False)
assert np.size(low) == 1
return low[0], upp[0] | invert hypothesis test to get confidence interval | _invert_test_confint | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def _invert_test_confint_2indep(
count1, exposure1, count2, exposure2,
alpha=0.05,
method="score",
compare="diff",
method_start="wald"
):
"""invert hypothesis test to get confidence interval for 2indep
"""
def func(r):
v = (test_poisson_2indep(
count1, exposure1, count2, exposure2,
value=r, method=method, compare=compare
)[1] - alpha)**2
return v
ci = confint_poisson_2indep(count1, exposure1, count2, exposure2,
method=method_start, compare=compare)
low = optimize.fmin(func, ci[0], xtol=1e-8, disp=False)
upp = optimize.fmin(func, ci[1], xtol=1e-8, disp=False)
assert np.size(low) == 1
return low[0], upp[0] | invert hypothesis test to get confidence interval for 2indep | _invert_test_confint_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def test_poisson_2indep(count1, exposure1, count2, exposure2, value=None,
ratio_null=None,
method=None, compare='ratio',
alternative='two-sided', etest_kwds=None):
'''Test for comparing two sample Poisson intensity rates.
Rates are defined as expected count divided by exposure.
The Null and alternative hypothesis for the rates, rate1 and rate2, of two
independent Poisson samples are
for compare = 'diff'
- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0 if alternative = 'larger'
- H1: rate1 - rate2 - value < 0 if alternative = 'smaller'
for compare = 'ratio'
- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0 if alternative = 'larger'
- H1: rate1 / rate2 - value < 0 if alternative = 'smaller'
Parameters
----------
count1 : int
Number of events in first sample, treatment group.
exposure1 : float
Total exposure (time * subjects) in first sample.
count2 : int
Number of events in second sample, control group.
exposure2 : float
Total exposure (time * subjects) in second sample.
ratio_null: float
Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
Deprecated, use ``value`` instead.
.. deprecated:: 0.14.0
Use ``value`` instead.
value : float
Value of the ratio or difference of 2 independent rates under the null
hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.
.. versionadded:: 0.14.0
Replacement for ``ratio_null``.
method : string
Method for the test statistic and the p-value. Defaults to `'score'`.
see Notes.
ratio:
- 'wald': method W1A, wald test, variance based on observed rates
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest' or 'etest-score: etest with score test statistic
- 'etest-wald': etest with wald test statistic
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'etest-score' or 'etest: etest with score test statistic
- 'etest-wald': etest with wald test statistic
compare : {'diff', 'ratio'}
Default is "ratio".
If compare is `ratio`, then the hypothesis test is for the
rate ratio defined by ratio = rate1 / rate2.
If compare is `diff`, then the hypothesis test is for
diff = rate1 - rate2.
alternative : {"two-sided" (default), "larger", smaller}
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio, or diff, of rates is not equal to value
- 'larger' : H1: ratio, or diff, of rates is larger than value
- 'smaller' : H1: ratio, or diff, of rates is smaller than value
etest_kwds: dictionary
Additional optional parameters to be passed to the etest_poisson_2indep
function, namely y_grid.
Returns
-------
results : instance of HolderTuple class
The two main attributes are test statistic `statistic` and p-value
`pvalue`.
See Also
--------
tost_poisson_2indep
etest_poisson_2indep
Notes
-----
The hypothesis tests for compare="ratio" are based on Gu et al 2018.
The e-tests are also based on ...
- 'wald': method W1A, wald test, variance based on separate estimates
- 'score': method W2A, score test, variance based on estimate under Null
- 'wald-log': W3A, wald test for log transformed ratio
- 'score-log' W4A, score test for log transformed ratio
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest': etest with score test statistic
- 'etest-wald': etest with wald test statistic
The hypothesis test for compare="diff" are mainly based on Ng et al 2007
and ...
- wald
- score
- etest-score
- etest-wald
Note the etests use the constraint maximum likelihood estimate (cmle) as
parameters for the underlying Poisson probabilities. The constraint cmle
parameters are the same as in the score test.
The E-test in Krishnamoorty and Thomson uses a moment estimator instead of
the score estimator.
References
----------
.. [1] Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
.. [2] Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of
Tests for the Difference of Two Poisson Means.”
Computational Statistics & Data Analysis 51 (6): 3085–99.
https://doi.org/10.1016/j.csda.2006.02.004.
'''
# shortcut names
y1, n1, y2, n2 = map(np.asarray, [count1, exposure1, count2, exposure2])
d = n2 / n1
rate1, rate2 = y1 / n1, y2 / n2
rates_cmle = None
if compare == 'ratio':
if method is None:
# default method
method = 'score'
if ratio_null is not None:
warnings.warn("'ratio_null' is deprecated, use 'value' keyword",
FutureWarning)
value = ratio_null
if ratio_null is None and value is None:
# default value
value = ratio_null = 1
else:
# for results holder instance, it still contains ratio_null
ratio_null = value
r = value
r_d = r / d # r1 * n1 / (r2 * n2)
if method in ['score']:
stat = (y1 - y2 * r_d) / np.sqrt((y1 + y2) * r_d)
dist = 'normal'
elif method in ['wald']:
stat = (y1 - y2 * r_d) / np.sqrt(y1 + y2 * r_d**2)
dist = 'normal'
elif method in ['score-log']:
stat = (np.log(y1 / y2) - np.log(r_d))
stat /= np.sqrt((2 + 1 / r_d + r_d) / (y1 + y2))
dist = 'normal'
elif method in ['wald-log']:
stat = (np.log(y1 / y2) - np.log(r_d)) / np.sqrt(1 / y1 + 1 / y2)
dist = 'normal'
elif method in ['sqrt']:
stat = 2 * (np.sqrt(y1 + 3 / 8.) - np.sqrt((y2 + 3 / 8.) * r_d))
stat /= np.sqrt(1 + r_d)
dist = 'normal'
elif method in ['exact-cond', 'cond-midp']:
from statsmodels.stats import proportion
bp = r_d / (1 + r_d)
y_total = y1 + y2
stat = np.nan
# TODO: why y2 in here and not y1, check definition of H1 "larger"
pvalue = proportion.binom_test(y1, y_total, prop=bp,
alternative=alternative)
if method in ['cond-midp']:
# not inplace in case we still want binom pvalue
pvalue = pvalue - 0.5 * stats.binom.pmf(y1, y_total, bp)
dist = 'binomial'
elif method.startswith('etest'):
if method.endswith('wald'):
method_etest = 'wald'
else:
method_etest = 'score'
if etest_kwds is None:
etest_kwds = {}
stat, pvalue = etest_poisson_2indep(
count1, exposure1, count2, exposure2, value=value,
method=method_etest, alternative=alternative, **etest_kwds)
dist = 'poisson'
else:
raise ValueError(f'method "{method}" not recognized')
elif compare == "diff":
if value is None:
value = 0
if method in ['wald']:
stat = (rate1 - rate2 - value) / np.sqrt(rate1 / n1 + rate2 / n2)
dist = 'normal'
"waldccv"
elif method in ['waldccv']:
stat = (rate1 - rate2 - value)
stat /= np.sqrt((count1 + 0.5) / n1**2 + (count2 + 0.5) / n2**2)
dist = 'normal'
elif method in ['score']:
# estimate rates with constraint MLE
count_pooled = y1 + y2
rate_pooled = count_pooled / (n1 + n2)
dt = rate_pooled - value
r2_cmle = 0.5 * (dt + np.sqrt(dt**2 + 4 * value * y2 / (n1 + n2)))
r1_cmle = r2_cmle + value
stat = ((rate1 - rate2 - value) /
np.sqrt(r1_cmle / n1 + r2_cmle / n2))
rates_cmle = (r1_cmle, r2_cmle)
dist = 'normal'
elif method.startswith('etest'):
if method.endswith('wald'):
method_etest = 'wald'
else:
method_etest = 'score'
if method == "etest":
method = method + "-score"
if etest_kwds is None:
etest_kwds = {}
stat, pvalue = etest_poisson_2indep(
count1, exposure1, count2, exposure2, value=value,
method=method_etest, compare="diff",
alternative=alternative, **etest_kwds)
dist = 'poisson'
else:
raise ValueError(f'method "{method}" not recognized')
else:
raise NotImplementedError('"compare" needs to be ratio or diff')
if dist == 'normal':
stat, pvalue = _zstat_generic2(stat, 1, alternative)
rates = (rate1, rate2)
ratio = rate1 / rate2
diff = rate1 - rate2
res = HolderTuple(statistic=stat,
pvalue=pvalue,
distribution=dist,
compare=compare,
method=method,
alternative=alternative,
rates=rates,
ratio=ratio,
diff=diff,
value=value,
rates_cmle=rates_cmle,
ratio_null=ratio_null,
)
return res | Test for comparing two sample Poisson intensity rates.
Rates are defined as expected count divided by exposure.
The Null and alternative hypothesis for the rates, rate1 and rate2, of two
independent Poisson samples are
for compare = 'diff'
- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0 if alternative = 'larger'
- H1: rate1 - rate2 - value < 0 if alternative = 'smaller'
for compare = 'ratio'
- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0 if alternative = 'larger'
- H1: rate1 / rate2 - value < 0 if alternative = 'smaller'
Parameters
----------
count1 : int
Number of events in first sample, treatment group.
exposure1 : float
Total exposure (time * subjects) in first sample.
count2 : int
Number of events in second sample, control group.
exposure2 : float
Total exposure (time * subjects) in second sample.
ratio_null: float
Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
Deprecated, use ``value`` instead.
.. deprecated:: 0.14.0
Use ``value`` instead.
value : float
Value of the ratio or difference of 2 independent rates under the null
hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.
.. versionadded:: 0.14.0
Replacement for ``ratio_null``.
method : string
Method for the test statistic and the p-value. Defaults to `'score'`.
see Notes.
ratio:
- 'wald': method W1A, wald test, variance based on observed rates
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest' or 'etest-score: etest with score test statistic
- 'etest-wald': etest with wald test statistic
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'etest-score' or 'etest: etest with score test statistic
- 'etest-wald': etest with wald test statistic
compare : {'diff', 'ratio'}
Default is "ratio".
If compare is `ratio`, then the hypothesis test is for the
rate ratio defined by ratio = rate1 / rate2.
If compare is `diff`, then the hypothesis test is for
diff = rate1 - rate2.
alternative : {"two-sided" (default), "larger", smaller}
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio, or diff, of rates is not equal to value
- 'larger' : H1: ratio, or diff, of rates is larger than value
- 'smaller' : H1: ratio, or diff, of rates is smaller than value
etest_kwds: dictionary
Additional optional parameters to be passed to the etest_poisson_2indep
function, namely y_grid.
Returns
-------
results : instance of HolderTuple class
The two main attributes are test statistic `statistic` and p-value
`pvalue`.
See Also
--------
tost_poisson_2indep
etest_poisson_2indep
Notes
-----
The hypothesis tests for compare="ratio" are based on Gu et al 2018.
The e-tests are also based on ...
- 'wald': method W1A, wald test, variance based on separate estimates
- 'score': method W2A, score test, variance based on estimate under Null
- 'wald-log': W3A, wald test for log transformed ratio
- 'score-log' W4A, score test for log transformed ratio
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest': etest with score test statistic
- 'etest-wald': etest with wald test statistic
The hypothesis test for compare="diff" are mainly based on Ng et al 2007
and ...
- wald
- score
- etest-score
- etest-wald
Note the etests use the constraint maximum likelihood estimate (cmle) as
parameters for the underlying Poisson probabilities. The constraint cmle
parameters are the same as in the score test.
The E-test in Krishnamoorty and Thomson uses a moment estimator instead of
the score estimator.
References
----------
.. [1] Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
.. [2] Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of
Tests for the Difference of Two Poisson Means.”
Computational Statistics & Data Analysis 51 (6): 3085–99.
https://doi.org/10.1016/j.csda.2006.02.004. | test_poisson_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def _score_diff(y1, n1, y2, n2, value=0, return_cmle=False):
"""score test and cmle for difference of 2 independent poisson rates
"""
count_pooled = y1 + y2
rate1, rate2 = y1 / n1, y2 / n2
rate_pooled = count_pooled / (n1 + n2)
dt = rate_pooled - value
r2_cmle = 0.5 * (dt + np.sqrt(dt**2 + 4 * value * y2 / (n1 + n2)))
r1_cmle = r2_cmle + value
eps = 1e-20 # avoid zero division in stat_func
v = r1_cmle / n1 + r2_cmle / n2
stat = (rate1 - rate2 - value) / np.sqrt(v + eps)
if return_cmle:
return stat, r1_cmle, r2_cmle
else:
return stat | score test and cmle for difference of 2 independent poisson rates | _score_diff | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def etest_poisson_2indep(count1, exposure1, count2, exposure2, ratio_null=None,
value=None, method='score', compare="ratio",
alternative='two-sided', ygrid=None,
y_grid=None):
"""
E-test for ratio of two sample Poisson rates.
Rates are defined as expected count divided by exposure. The Null and
alternative hypothesis for the rates, rate1 and rate2, of two independent
Poisson samples are:
for compare = 'diff'
- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0 if alternative = 'larger'
- H1: rate1 - rate2 - value < 0 if alternative = 'smaller'
for compare = 'ratio'
- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0 if alternative = 'larger'
- H1: rate1 / rate2 - value < 0 if alternative = 'smaller'
Parameters
----------
count1 : int
Number of events in first sample
exposure1 : float
Total exposure (time * subjects) in first sample
count2 : int
Number of events in first sample
exposure2 : float
Total exposure (time * subjects) in first sample
ratio_null: float
Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
Deprecated, use ``value`` instead.
.. deprecated:: 0.14.0
Use ``value`` instead.
value : float
Value of the ratio or diff of 2 independent rates under the null
hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.
.. versionadded:: 0.14.0
Replacement for ``ratio_null``.
method : {"score", "wald"}
Method for the test statistic that defines the rejection region.
alternative : string
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
- 'larger' : H1: ratio of rates is larger than ratio_null
- 'smaller' : H1: ratio of rates is smaller than ratio_null
y_grid : None or 1-D ndarray
Grid values for counts of the Poisson distribution used for computing
the pvalue. By default truncation is based on an upper tail Poisson
quantiles.
ygrid : None or 1-D ndarray
Same as y_grid. Deprecated. If both y_grid and ygrid are provided,
ygrid will be ignored.
.. deprecated:: 0.14.0
Use ``y_grid`` instead.
Returns
-------
stat_sample : float
test statistic for the sample
pvalue : float
References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of Tests
for the Difference of Two Poisson Means.” Computational Statistics & Data
Analysis 51 (6): 3085–99. https://doi.org/10.1016/j.csda.2006.02.004.
"""
y1, n1, y2, n2 = map(np.asarray, [count1, exposure1, count2, exposure2])
d = n2 / n1
eps = 1e-20 # avoid zero division in stat_func
if compare == "ratio":
if ratio_null is None and value is None:
# default value
value = 1
elif ratio_null is not None:
warnings.warn("'ratio_null' is deprecated, use 'value' keyword",
FutureWarning)
value = ratio_null
r = value # rate1 / rate2
r_d = r / d
rate2_cmle = (y1 + y2) / n2 / (1 + r_d)
rate1_cmle = rate2_cmle * r
if method in ['score']:
def stat_func(x1, x2):
return (x1 - x2 * r_d) / np.sqrt((x1 + x2) * r_d + eps)
# TODO: do I need these? return_results ?
# rate2_cmle = (y1 + y2) / n2 / (1 + r_d)
# rate1_cmle = rate2_cmle * r
# rate1 = rate1_cmle
# rate2 = rate2_cmle
elif method in ['wald']:
def stat_func(x1, x2):
return (x1 - x2 * r_d) / np.sqrt(x1 + x2 * r_d**2 + eps)
# rate2_mle = y2 / n2
# rate1_mle = y1 / n1
# rate1 = rate1_mle
# rate2 = rate2_mle
else:
raise ValueError('method not recognized')
elif compare == "diff":
if value is None:
value = 0
tmp = _score_diff(y1, n1, y2, n2, value=value, return_cmle=True)
_, rate1_cmle, rate2_cmle = tmp
if method in ['score']:
def stat_func(x1, x2):
return _score_diff(x1, n1, x2, n2, value=value)
elif method in ['wald']:
def stat_func(x1, x2):
rate1, rate2 = x1 / n1, x2 / n2
stat = (rate1 - rate2 - value)
stat /= np.sqrt(rate1 / n1 + rate2 / n2 + eps)
return stat
else:
raise ValueError('method not recognized')
# The sampling distribution needs to be based on the null hypotheis
# use constrained MLE from 'score' calculation
rate1 = rate1_cmle
rate2 = rate2_cmle
mean1 = n1 * rate1
mean2 = n2 * rate2
stat_sample = stat_func(y1, y2)
if ygrid is not None:
warnings.warn("ygrid is deprecated, use y_grid", FutureWarning)
y_grid = y_grid if y_grid is not None else ygrid
# The following uses a fixed truncation for evaluating the probabilities
# It will currently only work for small counts, so that sf at truncation
# point is small
# We can make it depend on the amount of truncated sf.
# Some numerical optimization or checks for large means need to be added.
if y_grid is None:
threshold = stats.poisson.isf(1e-13, max(mean1, mean2))
threshold = max(threshold, 100) # keep at least 100
y_grid = np.arange(threshold + 1)
else:
y_grid = np.asarray(y_grid)
if y_grid.ndim != 1:
raise ValueError("y_grid needs to be None or 1-dimensional array")
pdf1 = stats.poisson.pmf(y_grid, mean1)
pdf2 = stats.poisson.pmf(y_grid, mean2)
stat_space = stat_func(y_grid[:, None], y_grid[None, :]) # broadcasting
eps = 1e-15 # correction for strict inequality check
if alternative in ['two-sided', '2-sided', '2s']:
mask = np.abs(stat_space) >= (np.abs(stat_sample) - eps)
elif alternative in ['larger', 'l']:
mask = stat_space >= (stat_sample - eps)
elif alternative in ['smaller', 's']:
mask = stat_space <= (stat_sample + eps)
else:
raise ValueError('invalid alternative')
pvalue = ((pdf1[:, None] * pdf2[None, :])[mask]).sum()
return stat_sample, pvalue | E-test for ratio of two sample Poisson rates.
Rates are defined as expected count divided by exposure. The Null and
alternative hypothesis for the rates, rate1 and rate2, of two independent
Poisson samples are:
for compare = 'diff'
- H0: rate1 - rate2 - value = 0
- H1: rate1 - rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 - rate2 - value > 0 if alternative = 'larger'
- H1: rate1 - rate2 - value < 0 if alternative = 'smaller'
for compare = 'ratio'
- H0: rate1 / rate2 - value = 0
- H1: rate1 / rate2 - value != 0 if alternative = 'two-sided'
- H1: rate1 / rate2 - value > 0 if alternative = 'larger'
- H1: rate1 / rate2 - value < 0 if alternative = 'smaller'
Parameters
----------
count1 : int
Number of events in first sample
exposure1 : float
Total exposure (time * subjects) in first sample
count2 : int
Number of events in first sample
exposure2 : float
Total exposure (time * subjects) in first sample
ratio_null: float
Ratio of the two Poisson rates under the Null hypothesis. Default is 1.
Deprecated, use ``value`` instead.
.. deprecated:: 0.14.0
Use ``value`` instead.
value : float
Value of the ratio or diff of 2 independent rates under the null
hypothesis. Default is equal rates, i.e. 1 for ratio and 0 for diff.
.. versionadded:: 0.14.0
Replacement for ``ratio_null``.
method : {"score", "wald"}
Method for the test statistic that defines the rejection region.
alternative : string
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
- 'larger' : H1: ratio of rates is larger than ratio_null
- 'smaller' : H1: ratio of rates is smaller than ratio_null
y_grid : None or 1-D ndarray
Grid values for counts of the Poisson distribution used for computing
the pvalue. By default truncation is based on an upper tail Poisson
quantiles.
ygrid : None or 1-D ndarray
Same as y_grid. Deprecated. If both y_grid and ygrid are provided,
ygrid will be ignored.
.. deprecated:: 0.14.0
Use ``y_grid`` instead.
Returns
-------
stat_sample : float
test statistic for the sample
pvalue : float
References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
Ng, H. K. T., K. Gu, and M. L. Tang. 2007. “A Comparative Study of Tests
for the Difference of Two Poisson Means.” Computational Statistics & Data
Analysis 51 (6): 3085–99. https://doi.org/10.1016/j.csda.2006.02.004. | etest_poisson_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def tost_poisson_2indep(count1, exposure1, count2, exposure2, low, upp,
method='score', compare='ratio'):
'''Equivalence test based on two one-sided `test_proportions_2indep`
This assumes that we have two independent poisson samples.
The Null and alternative hypothesis for equivalence testing are
for compare = 'ratio'
- H0: rate1 / rate2 <= low or upp <= rate1 / rate2
- H1: low < rate1 / rate2 < upp
for compare = 'diff'
- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp
Parameters
----------
count1 : int
Number of events in first sample
exposure1 : float
Total exposure (time * subjects) in first sample
count2 : int
Number of events in second sample
exposure2 : float
Total exposure (time * subjects) in second sample
low, upp :
equivalence margin for the ratio or difference of Poisson rates
method: string
TOST uses ``test_poisson_2indep`` and has the same methods.
ratio:
- 'wald': method W1A, wald test, variance based on observed rates
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest' or 'etest-score: etest with score test statistic
- 'etest-wald': etest with wald test statistic
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'etest-score' or 'etest: etest with score test statistic
- 'etest-wald': etest with wald test statistic
Returns
-------
results : instance of HolderTuple class
The two main attributes are test statistic `statistic` and p-value
`pvalue`.
References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
See Also
--------
test_poisson_2indep
confint_poisson_2indep
'''
tt1 = test_poisson_2indep(count1, exposure1, count2, exposure2,
value=low, method=method,
compare=compare,
alternative='larger')
tt2 = test_poisson_2indep(count1, exposure1, count2, exposure2,
value=upp, method=method,
compare=compare,
alternative='smaller')
# idx_max = 1 if t1.pvalue < t2.pvalue else 0
idx_max = np.asarray(tt1.pvalue < tt2.pvalue, int)
statistic = np.choose(idx_max, [tt1.statistic, tt2.statistic])
pvalue = np.choose(idx_max, [tt1.pvalue, tt2.pvalue])
res = HolderTuple(statistic=statistic,
pvalue=pvalue,
method=method,
compare=compare,
equiv_limits=(low, upp),
results_larger=tt1,
results_smaller=tt2,
title="Equivalence test for 2 independent Poisson rates"
)
return res | Equivalence test based on two one-sided `test_proportions_2indep`
This assumes that we have two independent poisson samples.
The Null and alternative hypothesis for equivalence testing are
for compare = 'ratio'
- H0: rate1 / rate2 <= low or upp <= rate1 / rate2
- H1: low < rate1 / rate2 < upp
for compare = 'diff'
- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp
Parameters
----------
count1 : int
Number of events in first sample
exposure1 : float
Total exposure (time * subjects) in first sample
count2 : int
Number of events in second sample
exposure2 : float
Total exposure (time * subjects) in second sample
low, upp :
equivalence margin for the ratio or difference of Poisson rates
method: string
TOST uses ``test_poisson_2indep`` and has the same methods.
ratio:
- 'wald': method W1A, wald test, variance based on observed rates
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'exact-cond': exact conditional test based on binomial distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': midpoint-pvalue of exact conditional test
- 'etest' or 'etest-score: etest with score test statistic
- 'etest-wald': etest with wald test statistic
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'etest-score' or 'etest: etest with score test statistic
- 'etest-wald': etest with wald test statistic
Returns
-------
results : instance of HolderTuple class
The two main attributes are test statistic `statistic` and p-value
`pvalue`.
References
----------
Gu, Ng, Tang, Schucany 2008: Testing the Ratio of Two Poisson Rates,
Biometrical Journal 50 (2008) 2, 2008
See Also
--------
test_poisson_2indep
confint_poisson_2indep | tost_poisson_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def nonequivalence_poisson_2indep(count1, exposure1, count2, exposure2,
low, upp, method='score', compare="ratio"):
"""Test for non-equivalence, minimum effect for poisson.
This reverses null and alternative hypothesis compared to equivalence
testing. The null hypothesis is that the effect, ratio (or diff), is in
an interval that specifies a range of irrelevant or unimportant
differences between the two samples.
The Null and alternative hypothesis comparing the ratio of rates are
for compare = 'ratio':
- H0: low < rate1 / rate2 < upp
- H1: rate1 / rate2 <= low or upp <= rate1 / rate2
for compare = 'diff':
- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp
Notes
-----
This is implemented as two one-sided tests at the minimum effect boundaries
(low, upp) with (nominal) size alpha / 2 each.
The size of the test is the sum of the two one-tailed tests, which
corresponds to an equal-tailed two-sided test.
If low and upp are equal, then the result is the same as the standard
two-sided test.
The p-value is computed as `2 * min(pvalue_low, pvalue_upp)` in analogy to
two-sided equal-tail tests.
In large samples the nominal size of the test will be below alpha.
References
----------
.. [1] Hodges, J. L., Jr., and E. L. Lehmann. 1954. Testing the Approximate
Validity of Statistical Hypotheses. Journal of the Royal Statistical
Society, Series B (Methodological) 16: 261–68.
.. [2] Kim, Jae H., and Andrew P. Robinson. 2019. “Interval-Based
Hypothesis Testing and Its Applications to Economics and Finance.”
Econometrics 7 (2): 21. https://doi.org/10.3390/econometrics7020021.
"""
tt1 = test_poisson_2indep(count1, exposure1, count2, exposure2,
value=low, method=method, compare=compare,
alternative='smaller')
tt2 = test_poisson_2indep(count1, exposure1, count2, exposure2,
value=upp, method=method, compare=compare,
alternative='larger')
# idx_min = 0 if tt1.pvalue < tt2.pvalue else 1
idx_min = np.asarray(tt1.pvalue < tt2.pvalue, int)
pvalue = 2 * np.minimum(tt1.pvalue, tt2.pvalue)
statistic = np.choose(idx_min, [tt1.statistic, tt2.statistic])
res = HolderTuple(statistic=statistic,
pvalue=pvalue,
method=method,
results_larger=tt1,
results_smaller=tt2,
title="Equivalence test for 2 independent Poisson rates"
)
return res | Test for non-equivalence, minimum effect for poisson.
This reverses null and alternative hypothesis compared to equivalence
testing. The null hypothesis is that the effect, ratio (or diff), is in
an interval that specifies a range of irrelevant or unimportant
differences between the two samples.
The Null and alternative hypothesis comparing the ratio of rates are
for compare = 'ratio':
- H0: low < rate1 / rate2 < upp
- H1: rate1 / rate2 <= low or upp <= rate1 / rate2
for compare = 'diff':
- H0: rate1 - rate2 <= low or upp <= rate1 - rate2
- H1: low < rate - rate < upp
Notes
-----
This is implemented as two one-sided tests at the minimum effect boundaries
(low, upp) with (nominal) size alpha / 2 each.
The size of the test is the sum of the two one-tailed tests, which
corresponds to an equal-tailed two-sided test.
If low and upp are equal, then the result is the same as the standard
two-sided test.
The p-value is computed as `2 * min(pvalue_low, pvalue_upp)` in analogy to
two-sided equal-tail tests.
In large samples the nominal size of the test will be below alpha.
References
----------
.. [1] Hodges, J. L., Jr., and E. L. Lehmann. 1954. Testing the Approximate
Validity of Statistical Hypotheses. Journal of the Royal Statistical
Society, Series B (Methodological) 16: 261–68.
.. [2] Kim, Jae H., and Andrew P. Robinson. 2019. “Interval-Based
Hypothesis Testing and Its Applications to Economics and Finance.”
Econometrics 7 (2): 21. https://doi.org/10.3390/econometrics7020021. | nonequivalence_poisson_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def confint_poisson_2indep(count1, exposure1, count2, exposure2,
method='score', compare='ratio', alpha=0.05,
method_mover="score",
):
"""Confidence interval for ratio or difference of 2 indep poisson rates.
Parameters
----------
count1 : int
Number of events in first sample.
exposure1 : float
Total exposure (time * subjects) in first sample.
count2 : int
Number of events in second sample.
exposure2 : float
Total exposure (time * subjects) in second sample.
method : string
Method for the test statistic and the p-value. Defaults to `'score'`.
see Notes.
ratio:
- 'wald': NOT YET, method W1A, wald test, variance based on observed
rates
- 'waldcc' :
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'sqrtcc' :
- 'exact-cond': NOT YET, exact conditional test based on binomial
distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': NOT YET, midpoint-pvalue of exact conditional test
- 'mover' :
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'mover'
compare : {'diff', 'ratio'}
Default is "ratio".
If compare is `diff`, then the hypothesis test is for
diff = rate1 - rate2.
If compare is `ratio`, then the hypothesis test is for the
rate ratio defined by ratio = rate1 / rate2.
alternative : string
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
- 'larger' : H1: ratio of rates is larger than ratio_null
- 'smaller' : H1: ratio of rates is smaller than ratio_null
alpha : float in (0, 1)
Significance level, nominal coverage of the confidence interval is
1 - alpha.
Returns
-------
tuple (low, upp) : confidence limits.
"""
# shortcut names
y1, n1, y2, n2 = map(np.asarray, [count1, exposure1, count2, exposure2])
rate1, rate2 = y1 / n1, y2 / n2
alpha = alpha / 2 # two-sided only
if compare == "ratio":
if method == "score":
low, upp = _invert_test_confint_2indep(
count1, exposure1, count2, exposure2,
alpha=alpha * 2, # check how alpha is defined
method="score",
compare="ratio",
method_start="waldcc"
)
ci = (low, upp)
elif method == "wald-log":
crit = stats.norm.isf(alpha)
c = 0
center = (count1 + c) / (count2 + c) * n2 / n1
std = np.sqrt(1 / (count1 + c) + 1 / (count2 + c))
ci = (center * np.exp(- crit * std), center * np.exp(crit * std))
elif method == "score-log":
low, upp = _invert_test_confint_2indep(
count1, exposure1, count2, exposure2,
alpha=alpha * 2, # check how alpha is defined
method="score-log",
compare="ratio",
method_start="waldcc"
)
ci = (low, upp)
elif method == "waldcc":
crit = stats.norm.isf(alpha)
center = (count1 + 0.5) / (count2 + 0.5) * n2 / n1
std = np.sqrt(1 / (count1 + 0.5) + 1 / (count2 + 0.5))
ci = (center * np.exp(- crit * std), center * np.exp(crit * std))
elif method == "sqrtcc":
# coded based on Price, Bonett 2000 equ (2.4)
crit = stats.norm.isf(alpha)
center = np.sqrt((count1 + 0.5) * (count2 + 0.5))
std = 0.5 * np.sqrt(count1 + 0.5 + count2 + 0.5 - 0.25 * crit)
denom = (count2 + 0.5 - 0.25 * crit**2)
low_sqrt = (center - crit * std) / denom
upp_sqrt = (center + crit * std) / denom
ci = (low_sqrt**2, upp_sqrt**2)
elif method == "mover":
method_p = method_mover
ci1 = confint_poisson(y1, n1, method=method_p, alpha=2*alpha)
ci2 = confint_poisson(y2, n2, method=method_p, alpha=2*alpha)
ci = _mover_confint(rate1, rate2, ci1, ci2, contrast="ratio")
else:
raise ValueError(f'method "{method}" not recognized')
ci = (np.maximum(ci[0], 0), ci[1])
elif compare == "diff":
if method in ['wald']:
crit = stats.norm.isf(alpha)
center = rate1 - rate2
half = crit * np.sqrt(rate1 / n1 + rate2 / n2)
ci = center - half, center + half
elif method in ['waldccv']:
crit = stats.norm.isf(alpha)
center = rate1 - rate2
std = np.sqrt((count1 + 0.5) / n1**2 + (count2 + 0.5) / n2**2)
half = crit * std
ci = center - half, center + half
elif method == "score":
low, upp = _invert_test_confint_2indep(
count1, exposure1, count2, exposure2,
alpha=alpha * 2, # check how alpha is defined
method="score",
compare="diff",
method_start="waldccv"
)
ci = (low, upp)
elif method == "mover":
method_p = method_mover
ci1 = confint_poisson(y1, n1, method=method_p, alpha=2*alpha)
ci2 = confint_poisson(y2, n2, method=method_p, alpha=2*alpha)
ci = _mover_confint(rate1, rate2, ci1, ci2, contrast="diff")
else:
raise ValueError(f'method "{method}" not recognized')
else:
raise NotImplementedError('"compare" needs to be ratio or diff')
return ci | Confidence interval for ratio or difference of 2 indep poisson rates.
Parameters
----------
count1 : int
Number of events in first sample.
exposure1 : float
Total exposure (time * subjects) in first sample.
count2 : int
Number of events in second sample.
exposure2 : float
Total exposure (time * subjects) in second sample.
method : string
Method for the test statistic and the p-value. Defaults to `'score'`.
see Notes.
ratio:
- 'wald': NOT YET, method W1A, wald test, variance based on observed
rates
- 'waldcc' :
- 'score': method W2A, score test, variance based on estimate under
the Null hypothesis
- 'wald-log': W3A, uses log-ratio, variance based on observed rates
- 'score-log' W4A, uses log-ratio, variance based on estimate under
the Null hypothesis
- 'sqrt': W5A, based on variance stabilizing square root transformation
- 'sqrtcc' :
- 'exact-cond': NOT YET, exact conditional test based on binomial
distribution
This uses ``binom_test`` which is minlike in the two-sided case.
- 'cond-midp': NOT YET, midpoint-pvalue of exact conditional test
- 'mover' :
diff:
- 'wald',
- 'waldccv'
- 'score'
- 'mover'
compare : {'diff', 'ratio'}
Default is "ratio".
If compare is `diff`, then the hypothesis test is for
diff = rate1 - rate2.
If compare is `ratio`, then the hypothesis test is for the
rate ratio defined by ratio = rate1 / rate2.
alternative : string
The alternative hypothesis, H1, has to be one of the following
- 'two-sided': H1: ratio of rates is not equal to ratio_null (default)
- 'larger' : H1: ratio of rates is larger than ratio_null
- 'smaller' : H1: ratio of rates is smaller than ratio_null
alpha : float in (0, 1)
Significance level, nominal coverage of the confidence interval is
1 - alpha.
Returns
-------
tuple (low, upp) : confidence limits. | confint_poisson_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
def power_poisson_ratio_2indep(
rate1, rate2, nobs1,
nobs_ratio=1,
exposure=1,
value=0,
alpha=0.05,
dispersion=1,
alternative="smaller",
method_var="alt",
return_results=True,
):
"""Power of test of ratio of 2 independent poisson rates.
This is based on Zhu and Zhu and Lakkis. It does not directly correspond
to `test_poisson_2indep`.
Parameters
----------
rate1 : float
Poisson rate for the first sample, treatment group, under the
alternative hypothesis.
rate2 : float
Poisson rate for the second sample, reference group, under the
alternative hypothesis.
nobs1 : float or int
Number of observations in sample 1.
nobs_ratio : float
Sample size ratio, nobs2 = nobs_ratio * nobs1.
exposure : float
Exposure for each observation. Total exposure is nobs1 * exposure
and nobs2 * exposure.
alpha : float in interval (0,1)
Significance level, e.g. 0.05, is the probability of a type I
error, that is wrong rejections if the Null Hypothesis is true.
value : float
Rate ratio, rate1 / rate2, under the null hypothesis.
dispersion : float
Dispersion coefficient for quasi-Poisson. Dispersion different from
one can capture over or under dispersion relative to Poisson
distribution.
method_var : {"score", "alt"}
The variance of the test statistic for the null hypothesis given the
rates under the alternative can be either equal to the rates under the
alternative ``method_var="alt"``, or estimated under the constrained
of the null hypothesis, ``method_var="score"``.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
Alternative hypothesis whether the power is calculated for a
two-sided (default) or one sided test. The one-sided test can be
either 'larger', 'smaller'.
return_results : bool
If true, then a results instance with extra information is returned,
otherwise only the computed power is returned.
Returns
-------
results : results instance or float
If return_results is False, then only the power is returned.
If return_results is True, then a results instance with the
information in attributes is returned.
power : float
Power of the test, e.g. 0.8, is one minus the probability of a
type II error. Power is the probability that the test correctly
rejects the Null Hypothesis if the Alternative Hypothesis is true.
Other attributes in results instance include :
std_null
standard error of difference under the null hypothesis (without
sqrt(nobs1))
std_alt
standard error of difference under the alternative hypothesis
(without sqrt(nobs1))
References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
Poisson or Negative Binomial Rates in Noninferiority or Equivalence
Trials.” Statistics in Biopharmaceutical Research, March.
https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation
"""
# TODO: avoid possible circular import, check if needed
from statsmodels.stats.power import normal_power_het
rate1, rate2, nobs1 = map(np.asarray, [rate1, rate2, nobs1])
nobs2 = nobs_ratio * nobs1
v1 = dispersion / exposure * (1 / rate1 + 1 / (nobs_ratio * rate2))
if method_var == "alt":
v0 = v1
elif method_var == "score":
# nobs_ratio = 1 / nobs_ratio
v0 = dispersion / exposure * (1 + value / nobs_ratio)**2
v0 /= value / nobs_ratio * (rate1 + (nobs_ratio * rate2))
else:
raise NotImplementedError(f"method_var {method_var} not recognized")
std_null = np.sqrt(v0)
std_alt = np.sqrt(v1)
es = np.log(rate1 / rate2) - np.log(value)
pow_ = normal_power_het(es, nobs1, alpha, std_null=std_null,
std_alternative=std_alt,
alternative=alternative)
p_pooled = None # TODO: replace or remove
if return_results:
res = HolderTuple(
power=pow_,
p_pooled=p_pooled,
std_null=std_null,
std_alt=std_alt,
nobs1=nobs1,
nobs2=nobs2,
nobs_ratio=nobs_ratio,
alpha=alpha,
tuple_=("power",), # override default
)
return res
return pow_ | Power of test of ratio of 2 independent poisson rates.
This is based on Zhu and Zhu and Lakkis. It does not directly correspond
to `test_poisson_2indep`.
Parameters
----------
rate1 : float
Poisson rate for the first sample, treatment group, under the
alternative hypothesis.
rate2 : float
Poisson rate for the second sample, reference group, under the
alternative hypothesis.
nobs1 : float or int
Number of observations in sample 1.
nobs_ratio : float
Sample size ratio, nobs2 = nobs_ratio * nobs1.
exposure : float
Exposure for each observation. Total exposure is nobs1 * exposure
and nobs2 * exposure.
alpha : float in interval (0,1)
Significance level, e.g. 0.05, is the probability of a type I
error, that is wrong rejections if the Null Hypothesis is true.
value : float
Rate ratio, rate1 / rate2, under the null hypothesis.
dispersion : float
Dispersion coefficient for quasi-Poisson. Dispersion different from
one can capture over or under dispersion relative to Poisson
distribution.
method_var : {"score", "alt"}
The variance of the test statistic for the null hypothesis given the
rates under the alternative can be either equal to the rates under the
alternative ``method_var="alt"``, or estimated under the constrained
of the null hypothesis, ``method_var="score"``.
alternative : string, 'two-sided' (default), 'larger', 'smaller'
Alternative hypothesis whether the power is calculated for a
two-sided (default) or one sided test. The one-sided test can be
either 'larger', 'smaller'.
return_results : bool
If true, then a results instance with extra information is returned,
otherwise only the computed power is returned.
Returns
-------
results : results instance or float
If return_results is False, then only the power is returned.
If return_results is True, then a results instance with the
information in attributes is returned.
power : float
Power of the test, e.g. 0.8, is one minus the probability of a
type II error. Power is the probability that the test correctly
rejects the Null Hypothesis if the Alternative Hypothesis is true.
Other attributes in results instance include :
std_null
standard error of difference under the null hypothesis (without
sqrt(nobs1))
std_alt
standard error of difference under the alternative hypothesis
(without sqrt(nobs1))
References
----------
.. [1] Zhu, Haiyuan. 2017. “Sample Size Calculation for Comparing Two
Poisson or Negative Binomial Rates in Noninferiority or Equivalence
Trials.” Statistics in Biopharmaceutical Research, March.
https://doi.org/10.1080/19466315.2016.1225594
.. [2] Zhu, Haiyuan, and Hassan Lakkis. 2014. “Sample Size Calculation for
Comparing Two Negative Binomial Rates.” Statistics in Medicine 33 (3):
376–87. https://doi.org/10.1002/sim.5947.
.. [3] PASS documentation | power_poisson_ratio_2indep | python | statsmodels/statsmodels | statsmodels/stats/rates.py | https://github.com/statsmodels/statsmodels/blob/master/statsmodels/stats/rates.py | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.