-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmat_corr.py
More file actions
67 lines (55 loc) · 1.96 KB
/
Copy pathmat_corr.py
File metadata and controls
67 lines (55 loc) · 1.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 18 14:54:28 2016
@author: chaco3
"""
import numpy as np
def near_psd(x, epsilon=0):
'''
Document source
http://www.quarchome.org/correlationmatrix.pdf
Parameters
----------
x : array_like
Covariance/correlation matrix
epsilon : float
Eigenvalue limit (usually set to zero to ensure positive definiteness)
Returns
-------
near_cov : array_like
closest positive definite covariance/correlation matrix
'''
try:
if min(np.linalg.eigvals(x)) > epsilon:
return x
except:
import numpy as np
if min(np.linalg.eigvals(x)) > epsilon:
return x
# Removing scaling factor of covariance matrix
n = x.shape[0]
var_list = np.array([np.sqrt(x[i,i]) for i in xrange(n)])
y = np.array([[x[i, j]/(var_list[i]*var_list[j]) for i in xrange(n)] for j in xrange(n)])
# getting the nearest correlation matrix
eigval, eigvec = np.linalg.eig(y)
val = np.matrix(np.maximum(eigval, epsilon))
vec = np.matrix(eigvec)
T = 1/(np.multiply(vec, vec) * val.T)
T = np.matrix(np.sqrt(np.diag(np.array(T).reshape((n)) )))
B = T * vec * np.diag(np.array(np.sqrt(val)).reshape((n)))
near_corr = B*B.T
# returning the scaling factors
near_cov = np.array([[near_corr[i, j]*(var_list[i]*var_list[j]) for i in xrange(n)] for j in xrange(n)])
return near_cov
if __name__ == '__main__':
# This is a not positive-defined matrix
a = np.array([[1.0, 0.9, 0.7], [0.9, 1.0, 0.3], [0.7, 0.3, 1.0]])
#a = np.array([[1.0, 0.9, 0.7, 1], [0.9, 1.0, 0.3,1], [0.7, 0.3, 1.0,1], [1,1,1,0]])
eig = np.linalg.eigvals(a)
print(eig)
print('A negative eigenvalue is not from a positive semi-definite matrix')
b = near_psd(a)
print('The transformed matrix is: ')
print(b)
print('and the transformed eigenvalues: ')
print(np.linalg.eigvals(b))