You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
SUMM/ENH: hypothesis tests for covariance/correlation matrices #2765
Ledoit, Olivier, and Michael Wolf. "Some hypothesis tests for the covariance matrix when the dimension is large compared to the sample size." Annals of Statistics (2002): 1081-1102.
improved performance and asymptotics when data has large k_vars relative to nobs
#3842 adds sphericity_bartlett for test of spherical correlation or diagonal covariance
parking here some quickly written code based on Stata mvtest covariance documentation, not all yet
I haven't run this yet, no examples no test cases. Just checking how easy it is and thinking about design.
E.g, Stata uses Bartlett corrected pvalues. update I replaced it with a new version that runs, but no unit tests, high probability of typos
Also I looked at some references. update2 replaced again with newer version
other variations that I have seen in articles or books either use a different asymptotic expansion or use a kurtosis correction for heavier tails in elliptical distributions.
i.e. we need a method argument and possibly bootstrap or permutation. In general second moment, variance, covariance tests are very sensitive to deviations from normality.
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 7 13:22:44 2017
Author: Josef Perktold
References
----------
Stata manual for mvtest covariances
Rencher and Christensen 2012
Bartlett 1954
Stata refers to Rencher and Christensen for the formulas. Those correspond
to the formula collection in Bartlett 1954 for several of them.
"""
from __future__ import division
import numpy as np
from scipy import stats
from statsmodels.stats.moment_helpers import cov2corr
# shortcut function
logdet = lambda x: np.linalg.slogdet(x)[1]
# another copy of this
class Results(object):
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def cov_test(cov, cov_null, nobs):
# 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 statistic, pvalue
def cov_test_spherical(cov, nobs):
# unchanged Stata formula, but denom is cov cancels, AFAICS
# Bartlett 1954 correction factor in IIIc
cov = np.asarray(cov)
k = cov.shape[0]
statistic = nobs - 1 - (2 * k + k + 2) / (6 * k)
statistic *= k * np.log(np.trace(cov)) - logdet(cov) - k * np.log(k)
df = k * (k + 1) / 2 - 1
pvalue = stats.chi2.sf(statistic, df)
return statistic, pvalue
def cov_test_diagonal(cov, nobs):
cov = np.asarray(cov)
k = cov.shape[0]
R = cov2corr(cov)
statistic = -(nobs - 1 - (2 * k + 5)/ 6) * logdet(R)
df = k * (k - 1) / 2
pvalue = stats.chi2.sf(statistic, df)
return statistic, pvalue
def cov_test_blockdiagonal(cov, cov_blocks, nobs):
cov = np.asarray(cov)
cov_blocks = list(map(np.asarray, cov_blocks))
k = cov.shape[0]
k_blocks = [c.shape[0] for c in cov_blocks]
if k != sum(k_blocks):
msg = "sample covariances and blocks do not have matching shape"
raise ValueError(msg)
logdet_blocks = sum(logdet(c) for c in cov_blocks)
a2 = k**2 - sum(ki**2 for ki in k_blocks)
a3 = k**3 - sum(ki**3 for ki in k_blocks)
statistic = (nobs - 1 - (2 * a3 + 3 * a2) / (6. * a2))
statistic *= logdet_blocks - logdet(cov)
df = a2 / 2
pvalue = stats.chi2.sf(statistic, df)
return statistic, pvalue
def cov_test_indep(cov_list, nobs_list):
"""
approximations to distribution of test statistic is by Box
"""
# TODO: name is misleading with independent cov structure
# Note stata uses nobs in cov, this uses nobs - 1
cov_list = list(map(np.asarray, cov_list))
m = len(cov_list)
nobs = sum(nobs_list) # total number of observations
k = cov_list[0].shape[0]
cov_pooled = sum((n - 1) * c for (n, c) in zip(nobs_list, cov_list))
cov_pooled /= (nobs - m)
stat0 = (nobs - m) * logdet(cov_pooled)
stat0 -= sum((n - 1) * logdet(c) for (n, c) in zip(nobs_list, cov_list))
# Box's chi2
c1 = sum(1 / (n - 1) for n in nobs_list) - 1 / (nobs - m)
c1 *= (2 * k*k + 3 * k - 1) / (6 * (k + 1) * (m - 1))
df_chi2 = (m - 1) * k * (k + 1) / 2
statistic_chi2 = ( 1 - c1) * stat0
pvalue_chi2 = stats.chi2.sf(statistic_chi2, df_chi2)
c2 = sum(1 / (n - 1)**2 for n in nobs_list) - 1 / (nobs - m)**2
c2 *= (k - 1) * ( k + 2) / (6 * (m - 1))
a1 = df_chi2
a2 = (a1 + 2) / abs(c2 - c1**2)
b1 = (1 - c1 - a1 / a2) / a1
b2 = (1 - c1 + 2 / a2) / a2
if c2 > c1**2:
statistic_f = b1 * stat0
else:
tmp = b2 * stat0
statistic_f = a2 / a1 * tmp / (1 + tmp)
df_f = (a1, a2)
pvalue_f = stats.f.sf(statistic_f, *df_f)
return Results(statistic_base=stat0,
statistic_chi2=statistic_chi2,
pvalue_chi2=pvalue_chi2,
df_chi2=df_chi2,
distr_chi2='chi2',
statistic_f=statistic_f,
pvalue_f=pvalue_f,
df_f=df_f,
distr_f='F')
np.random.seed(987125)
nobs, k_vars = 750, 4
x = np.random.randn(nobs, k_vars)
x *= 1 + 0.05 * np.arange(k_vars)
cov = np.cov(x, rowvar=0, ddof=1)
res0 = cov_test(cov, np.eye(k_vars), nobs)
print(res0)
res1 = cov_test_diagonal(cov, nobs)
print(res1)
res2 = cov_test_spherical(cov, nobs)
print(res2)
ni = 250
m = nobs // ni
cov_list = [np.cov(x[i*ni : (i+1)*250], rowvar=0, ddof=1) for i in range(m)]
nobs_list = [ni] * len(cov_list)
res_m = cov_test_indep(cov_list, nobs_list)
print()
print(vars(res_m))
x2 = x.copy()
x2[:nobs // 2] *= 1.2
cov_list2 = [np.cov(x2[i*ni : (i+1)*250], rowvar=0, ddof=1) for i in range(m)]
nobs_list = [ni] * len(cov_list2)
res_m = cov_test_indep(cov_list2, nobs_list)
print()
print(vars(res_m))
import statsmodels.datasets.macrodata as md
df = md.load_pandas().data
df1 = df[['realcons', 'realinv', 'realgovt']]
td = cov_test_diagonal(df1.cov(), df1.shape[0])
print()
print(td)
# a quick Monte Carlo for size of tests
import time
nobs = 500
k_vars = 4
cov_test_ = cov_test_diagonal
cov_test_ = cov_test_spherical
# normal
t0 = time.time()
res_mc = [cov_test_(np.cov(np.random.randn(nobs, k_vars), rowvar=0), nobs)
for _ in range(10000)]
t1 = time.time()
print()
print('time', t1 - t0)
res_mc = np.array(res_mc)
alphas = [0.01, 0.05, 0.1, 0.2]
prop_reject = (res_mc[:,1:] <= alphas).mean(0)
print(alphas)
print(prop_reject)
# t
df = 4
# at df=2 overrejection, but higher moments don't exist
# at df=4 then overrects at alpha=0.01, but not bad at 0.05 (reject 0.0615)
t0 = time.time()
res_mc_t = [cov_test_(np.cov(np.random.standard_t(df, size=(nobs, k_vars)), rowvar=0), nobs)
for _ in range(10000)]
t1 = time.time()
print()
print('time', t1 - t0)
res_mc_t = np.array(res_mc_t)
prop_reject = (res_mc_t[:,1:] <= alphas).mean(0)
print(alphas)
print(prop_reject)
# lognormal
t0 = time.time()
res_mc_ln = [cov_test_(np.cov(np.exp(np.random.randn(nobs, k_vars)), rowvar=0), nobs)
for _ in range(10000)]
t1 = time.time()
print()
print('time', t1 - t0)
res_mc_ln = np.array(res_mc_ln)
prop_reject = (res_mc_ln[:,1:] <= alphas).mean(0)
print(alphas)
print(prop_reject)
cov_test_diagonal (or corr_test_spherical) is pretty robust and well sized at independently t distributed sample with df >= 4. So, some heavy tails don't have much affect in this case. It overrejects at df=2, but there we don't have higher moments.
At log-normal sample, the test overrejects.
cov_test_spherical only has good size for normal with large nobs / k_vars.
(still no unit test examples against Stata or book)
reference:
Johnson and Wichern have test for equality of covariance matrices in section 6.6 p.310 (chapter on comparisons of means)
test for equicorrelated covariance/correlation p.457f in section 8.5 (Lawley)
related: page 501 test for number of common factors with Bartlett correction (chisquare based)
otherwise I don't see any tests for covariance or correlation structure like sphericity, except e.g in excercises of chapter 8 p.472 (referring just to Bartlett 1954, "A Note ..."
I didn't put my filename in the issue :( scripts/try_multivariate_cov.py last modified Thursday, November 9, 2017, 11:00:09 PM
One possibility would be to create a single function test_cov_structure with structure keyword.
However, the extra information needed for the null hypothesis differs across structures
cov_test_indep is most likely the multiple-sample test in Stata, i.e. Box-M test for k independent samples.
rename oneway_cov ? or cov_oneway (oneway as postfix like "2indep" ?
need a helper function or more convenient interface for splitting cov into diag block
(in one (?) of the PRs, I wrote a helper function to split in two or 3 blocks for that special case)
I will need kurtosis correction again for distributions with heavy tails. #3280 and/or more tests based on correlation matrix.
I don't remember if I have other scripts and example code with kurtosis besides cov matrix tools PR #6696
Activity
josef-pkt commentedon Nov 8, 2017
#3842 adds sphericity_bartlett for test of spherical correlation or diagonal covariance
parking here some quickly written code based on Stata mvtest covariance documentation, not all yet
I haven't run this yet, no examples no test cases. Just checking how easy it is and thinking about design.
E.g, Stata uses Bartlett corrected pvalues.
update I replaced it with a new version that runs, but no unit tests, high probability of typos
Also I looked at some references.
update2 replaced again with newer version
other variations that I have seen in articles or books either use a different asymptotic expansion or use a kurtosis correction for heavier tails in elliptical distributions.
i.e. we need a method argument and possibly bootstrap or permutation. In general second moment, variance, covariance tests are very sensitive to deviations from normality.
josef-pkt commentedon Nov 9, 2017
The latest version includes a quick Monte Carlo:
cov_test_diagonal (or corr_test_spherical) is pretty robust and well sized at independently t distributed sample with df >= 4. So, some heavy tails don't have much affect in this case. It overrejects at df=2, but there we don't have higher moments.
At log-normal sample, the test overrejects.
cov_test_spherical only has good size for normal with large nobs / k_vars.
(still no unit test examples against Stata or book)
josef-pkt commentedon Nov 11, 2017
reference:
Johnson and Wichern have test for equality of covariance matrices in section 6.6 p.310 (chapter on comparisons of means)
test for equicorrelated covariance/correlation p.457f in section 8.5 (Lawley)
related: page 501 test for number of common factors with Bartlett correction (chisquare based)
otherwise I don't see any tests for covariance or correlation structure like sphericity, except e.g in excercises of chapter 8 p.472 (referring just to Bartlett 1954, "A Note ..."
josef-pkt commentedon Dec 3, 2017
see also Stata's SEM manual
e.g. chapter Methods and formulas for sem page 572 Stata 15
and similar for gsem
josef-pkt commentedon Jan 9, 2020
https://stackoverflow.com/questions/59667408/box-m-test-in-python
comment has link to https://www.quantopian.com/posts/box-m-test-to-compare-covariance-matrices-across-time which uses https://www.ncss.com/wp-content/themes/ncss/pdf/Procedures/NCSS/Equality_of_Covariance.pdf
it's not obvious if that is the same as
cov_test_indepin my code above(I remember I looked also at the Box-M test in the SPSS algorithm docs)
josef-pkt commentedon May 7, 2020
I didn't put my filename in the issue :(
scripts/try_multivariate_cov.pylast modified Thursday, November 9, 2017, 11:00:09 PMOne possibility would be to create a single function
test_cov_structurewith structure keyword.However, the extra information needed for the null hypothesis differs across structures
cov_test_indepis most likely the multiple-sample test in Stata, i.e. Box-M test for k independent samples.rename
oneway_cov? or cov_oneway (oneway as postfix like "2indep" ?josef-pkt commentedon May 7, 2020
need a helper function or more convenient interface for splitting cov into diag block
(in one (?) of the PRs, I wrote a helper function to split in two or 3 blocks for that special case)
data uses var names to allow specifying which variables are in the same block,
In that case, cov doesn't have to be sorted by blocks
However, the implementation of the cov_test_blockdiagonal is that cov is really arranged so it's consistent with the blockdiag form
josef-pkt commentedon May 9, 2020
I'm running the Monte Carlo from the script above (after the 6693 merge)
data is iid, i.e. cov = eye
nobs=500, n replications=10000 as in above script
results cov_test_diagonal using corrcoef
josef-pkt commentedon May 9, 2020
I will need kurtosis correction again for distributions with heavy tails. #3280 and/or more tests based on correlation matrix.
I don't remember if I have other scripts and example code with kurtosis besides cov matrix tools PR #6696