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
ENH: add penalized covariance/correlation and precision estimate #3197
There are many cases where an estimated covariance does not have good small sample properties.
We need some regularization methods (beyond what scikit-learn has)
One of the main tasks will be to provide different covariance or correlation patterns as shrinkage targets.
e.g. correlation_tools has functions to force covariance matrices to be positive definite or have a factor structure..
In other cases we want to shrink for example towards one of the GEE covariance patterns.
related #2942 regularized cov_params/weights or covariance in GEE/GMM
(opened for now so I can park a script in the comments.)
I thought the following is a quick getting-started job, but k-fold likelihood cross-validation doesn't seem to work.
"""Penalized Estimation of Covariance or Precision Matrix
Author: Josef Perktold
just to get started, and the main algorithm looked easy
KFold cross-validation has a problem because the resulting CV likelihood
is monotonic in the penalization weight in the example.
"""
import numpy as np
def _matrixhalf(m, power=0.5):
evals, evecs = np.linalg.eigh(m)
return (evecs * evals**power).dot(evecs.T)
def cov(data, mean=None, ddof=1):
if mean is None:
mean = data.mean()
if np.size(mean) == 1 and mean == 0:
data_dm = data
else:
data_dm = data - mean
return data_dm.T.dot(data_dm) / (data.shape[0] - ddof)
def cov_ridge(cov, prec_target=None, pen_weight=None, method='ridge',
return_cov=True):
"""compute ridge penalized covariance or precision matrix
Parameter
---------
cov : array_like
sample covariance matrix
prec_target : array_like (optional)
target precision matrix. Default is a diagonal matrix with
inverse variances on the diagonal.
pen_weight : float, currently required
weight for Ridge penalization
method : string
only ridge available
return_cov : bool
If True, then the covariance, otherwise the precision matrix,
i.e. the inverse of the covariance matrix, is returned.
Return
------
cov_prec : ndarray
penalized covariance or precision matrix, return depends on
return_cov keyword.
Notes
-----
This currently just implements van Wieringen and Peeters 2016 estimator.
This also adjusts the variances, i.e. the diagonal of the covariance or
precision matrix, even if precision target is based on the sample
variances.
References
----------
van Wieringen, Wessel N., and Carel F. W. Peeters. 2016. “Ridge
Estimation of Inverse Covariance Matrices from High-Dimensional Data.”
Computational Statistics & Data Analysis 103 (November): 284–303.
doi:10.1016/j.csda.2016.05.012.
"""
cov = np.asarray(cov)
k_vars, k = cov.shape
if k_vars != k:
raise ValueError('cov must be square')
if prec_target is None:
# default to diagonal of sample covariance
target = np.diag(1. / np.diag(cov_sample).copy())
else:
target = np.asarray(prec_target)
if method == 'ridge':
tmp = cov_sample - pen_weight * target
term1 = pen_weight * np.eye(k_vars) + 0.25 * tmp.T.dot(tmp)
term = _matrixhalf(term1)
if return_cov:
return term + 0.5 * tmp
else:
return (term - 0.5 * tmp) / pen_weight
elif method == 'avg':
# renormalize penweight
target = np.linalg.inv(target)
pw = pen_weight / (1. + pen_weight)
c = (1 - pw) * cov_sample + pw * target
if return_cov:
return c
else:
return np.linalg.inv(c)
def _normal_loglike(prec_est, cov_sample, nobs, all_terms=False):
s, ldet = np.linalg.slogdet(prec_est)
llf = ldet - (prec_est * cov_sample).sum()
if all_terms:
raise ValueError('not yet')
# find constant term and correct scaling of llf
llf -= 2* np.log(np.pi )
return llf
def _cross_val_cov_ridge(kfolds, endog,
pen_weights=np.logspace(-1, 3, 11),
target=None):
"""cross-validation of a penalized covariance and precision estimator
this doesn't seem to work, CV-score is monotonic, no penalization
???
currently uses cov_ridge as penalized estimator
current version assumes zero mean, (but that didn't help either)
i.e. cross-product is used and not covariance.
Parameters
----------
kfolds : int
number of folds in K-Fold cross validation
endog : ndarray
data with observation in rows and variables in columns
pen_weight : list or iterable
penalizatio weights for which the CV-score is computed
target : ndarray
target for the precision matrix, see cov_ridge
Returns
-------
res : 2-D array
results of the cross-validation, with penalization weights in first
and Leave-K-Out negative loglikelihood value in the second column.
"""
from statsmodels.sandbox.tools.cross_val import KFold, split
nobs, k_vars = endog.shape
if target is None:
target = np.eye(k_vars)
it = KFold(nobs, kfolds)
res = []
for pw in pen_weights:
llfi = 0
for train_index, test_index in it:
ni = len(train_index)
y_train, y_test = split(train_index, test_index, endog)
y_test = np.atleast_2d(y_test)
ne = len(y_test)
#print(y_train.shape, y_test.shape)
cov_train = cov(y_train, ddof=1, mean=0)
#target = np.diag(1. / np.diag(cov_train).copy())
prec_train = cov_ridge(cov_train, prec_target=target,
pen_weight=pw, return_cov=False,
method='avg')
cov_test = cov(y_test, ddof=1, mean=0)
resi = -_normal_loglike(prec_train, cov_test, nobs, all_terms=False)
llfi += ne * resi
res.append([pw, llfi])
return np.array(res)
use_correlated = False
nobs, k_vars = 50, 40
np.random.seed(987128)
if not use_correlated:
x = np.random.randn(nobs, k_vars)
else:
cov_true = 0.2 * np.ones((k_vars, k_vars)) + 0.8 * np.eye(k_vars)
x = np.random.multivariate_normal(np.zeros(k_vars), cov_true, size=nobs)
x -= x.mean(0)
target = np.eye(k_vars)
pen_weight = 0.1 #1e-10
cov_sample = np.cov(x.T, ddof=0)
target = np.diag(1. / np.diag(cov_sample).copy())
tmp = cov_sample - pen_weight * target
term1 = pen_weight * np.eye(k_vars) + 0.25 * tmp.T.dot(tmp)
cov_pen = _matrixhalf(term1) + 0.5 * tmp
skip_print = True
if not skip_print:
print(cov_sample)
print()
print(cov_pen)
c = cov_ridge(cov_sample, prec_target=None, pen_weight=pen_weight, return_cov=True)
if not skip_print:
print(c)
Ikeda, Yuki, Tatsuya Kubokawa, and Muni S. Srivastava. 2016. “Comparison of Linear Shrinkage Estimators of a Large Covariance Matrix in Normal and Non-Normal Distributions.” Computational Statistics & Data Analysis 95 (March): 95–108. doi:10.1016/j.csda.2015.09.011.
looks interesting and good in Monte Carlo, but I didn't try to figure out how computational expensive this is in the general case. (he introduces too many temporary variables to keep track which is which and how expensive they are to calculate)
compare with ledoit-wolf and OAS which are already in scikit-learn
aside: least squares cross-validation might work as alternative to likelihood cross-validation.
the above article and references use risk minimization to obtain the shrinkage factor.
(i.e. use squared difference between estimate and test sample covariance
(I don't remember seeing it in a reference, but I never looked systematically at cross-validation for covariance estimation)
overview of some regularized estimators and application to finance portfolio selection.
article looks useful, including references that I didn't follow up
overall best is sparse precision matrix
Senneret, M., Y. Malevergne, P. Abry, G. Perrin, and L. Jaffrès. 2016. “Covariance Versus Precision Matrix Estimation for Efficient Asset Allocation.” IEEE Journal of Selected Topics in Signal Processing 10 (6): 982–93. doi:10.1109/JSTSP.2016.2577546.
(working paper version is 2013 "A Comparative Study of Covariance and Precision Matrix Estimators for Portfolio Selection_CovarianceMatrixEstimation_20130522.pdf")
random thought related to multivariate statistics (sparse multivariate models with sparse correlation)
no references,
z-test based thresholding for sparse correlation with multiplicity correction:
scipy.stats has p-value for pearson correlation and we should be able to get confidence intervals, and a threshold for corr=0. In large correlation matrix we can use multiple-testing p-value correction. However, the correlation coefficients are not independent, e.g. use FDR for positively correlated statistics.
More difficult, I don't know if there is a standard error and distribution for penalized or shrunk correlation matrices.
The idea is to get a rough threshold based on sample size and number of variables or dimension of correlation matrix instead of assuming a fixed threshold.
in the script above
need to verify normal loglike llf = ldet - (prec_est * cov_sample).sum()
looks wrong, I don't think this corresponds to trace(prec_est @ cov_sample)
Bickel and Levina and related articles use different measures for the risk used in cross-validation or as distance between model cov and sample cov
article looks good (proofs take a lot of space)
good references throughout article,
standard Tyler-M plus Ridge during updating plus thresholding
normalization trace(sigma) = p
@josef-pkt This is a nice thread! I met the same problem when I try to calculate the covariance with limited samples. I see the JPL group uses the leave-one-out cross-validation (LOOC) estimate of the shrinkage parameter for estimating the
covariance matrix from a limited sample of data:
I feel that method is not good enough because I see some stripes in the final products. Could you recommend a better open-source Python package/function? I see you have listed many here, but I'm not sure which one is better now ;)
Activity
josef-pkt commentedon Sep 13, 2016
I thought the following is a quick getting-started job, but k-fold likelihood cross-validation doesn't seem to work.
josef-pkt commentedon Sep 23, 2016
another shrinkage article
Ikeda, Yuki, Tatsuya Kubokawa, and Muni S. Srivastava. 2016. “Comparison of Linear Shrinkage Estimators of a Large Covariance Matrix in Normal and Non-Normal Distributions.” Computational Statistics & Data Analysis 95 (March): 95–108. doi:10.1016/j.csda.2015.09.011.
looks interesting and good in Monte Carlo, but I didn't try to figure out how computational expensive this is in the general case. (he introduces too many temporary variables to keep track which is which and how expensive they are to calculate)
compare with ledoit-wolf and OAS which are already in scikit-learn
aside: least squares cross-validation might work as alternative to likelihood cross-validation.
the above article and references use risk minimization to obtain the shrinkage factor.
(i.e. use squared difference between estimate and test sample covariance
(I don't remember seeing it in a reference, but I never looked systematically at cross-validation for covariance estimation)
josef-pkt commentedon Sep 23, 2016
overview of some regularized estimators and application to finance portfolio selection.
article looks useful, including references that I didn't follow up
overall best is sparse precision matrix
Senneret, M., Y. Malevergne, P. Abry, G. Perrin, and L. Jaffrès. 2016. “Covariance Versus Precision Matrix Estimation for Efficient Asset Allocation.” IEEE Journal of Selected Topics in Signal Processing 10 (6): 982–93. doi:10.1109/JSTSP.2016.2577546.
(working paper version is 2013 "A Comparative Study of Covariance and Precision Matrix Estimators for Portfolio Selection_CovarianceMatrixEstimation_20130522.pdf")
josef-pkt commentedon Sep 2, 2017
random thought related to multivariate statistics (sparse multivariate models with sparse correlation)
no references,
z-test based thresholding for sparse correlation with multiplicity correction:
scipy.stats has p-value for pearson correlation and we should be able to get confidence intervals, and a threshold for corr=0. In large correlation matrix we can use multiple-testing p-value correction. However, the correlation coefficients are not independent, e.g. use FDR for positively correlated statistics.
More difficult, I don't know if there is a standard error and distribution for penalized or shrunk correlation matrices.
The idea is to get a rough threshold based on sample size and number of variables or dimension of correlation matrix instead of assuming a fixed threshold.
josef-pkt commentedon Oct 17, 2019
see also mailing list thread for covariance in time series context
https://groups.google.com/d/msg/pystatsmodels/Z0vRn2Y-Yek/QBcm9luSBwAJ
reference to statistics handbook chapter
I was looking at Pourahmadi and co-authors articles using cholesky, sequential regression
Bickel Levina have banded and tapered cov
josef-pkt commentedon Oct 17, 2019
in the script above
need to verify normal loglike
llf = ldet - (prec_est * cov_sample).sum()looks wrong, I don't think this corresponds to
trace(prec_est @ cov_sample)Bickel and Levina and related articles use different measures for the risk used in cross-validation or as distance between model cov and sample cov
josef-pkt commentedon Oct 17, 2019
outlier robust cov PR #3230 contains
_naive_ledoit_wolf_shrinkagefrom sklearnI don't know where my examples with shrinkage or thresholding of covariance or precision matrices are
josef-pkt commentedon Oct 17, 2019
looks like this works correctly for square matrices and requires fewer multiplications
also for computing just the diagonal
and for rectangular arrays with matching shape so cross-product is square matrix ( like exog X'X)
(actually same trick as I use in cov_type computations)
josef-pkt commentedon Mar 31, 2021
a new article, shrinkage, huber-M for cov/scatter, looks interesting (very brief look)
Ollila, E., D. P. Palomar, and F. Pascal. 2021. “Shrinking the Eigenvalues of M-Estimators of Covariance Matrix.” IEEE Transactions on Signal Processing 69: 256–69. https://doi.org/10.1109/TSP.2020.3043952.
josef-pkt commentedon Apr 1, 2021
article looks good (proofs take a lot of space)
good references throughout article,
standard Tyler-M plus Ridge during updating plus thresholding
normalization
trace(sigma) = pGoes, John, Gilad Lerman, and Boaz Nadler. 2020. “Robust Sparse Covariance Estimation by Thresholding Tyler’s M-Estimator.” The Annals of Statistics 48 (1): 86–110. https://doi.org/10.1214/18-AOS1793.
there are other recent articles for Tyler M that allow p>n
josef-pkt commentedon Jan 20, 2023
bump for 0.15
I don't see the above functions like cov_ridge included in any PR.
The only shrinkage seems to be ledoilt in the outlier robust cov PR
Should I put covariance in
multivariateso I don't have to split up penalized and outlier robust functions between stats and robust directories?zxdawn commentedon Aug 17, 2023
@josef-pkt This is a nice thread! I met the same problem when I try to calculate the covariance with limited samples. I see the JPL group uses the leave-one-out cross-validation (LOOC) estimate of the shrinkage parameter for estimating the
covariance matrix from a limited sample of data:
https://github.com/emit-sds/emit-ghg/blob/0a13107150353bf7f37256a9806b43953fb53bf4/parallel_mf.py#L283-L298
I feel that method is not good enough because I see some stripes in the final products. Could you recommend a better open-source Python package/function? I see you have listed many here, but I'm not sure which one is better now ;)
Thank you for your time and consideration!
Xin
josef-pkt commentedon Jan 26, 2025
It should be possible to try out other distance measure for cov matrices as cross-validation criterion.
#9204
We need to compare to what sklearn is doing, e.g. https://scikit-learn.org/stable/auto_examples/covariance/plot_covariance_estimation.html