make correlated array with cholesky decomposition python

Solutions on MaxInterview for make correlated array with cholesky decomposition python by the best coders in the world

showing results for - "make correlated array with cholesky decomposition python"
Amelia
30 Mar 2017
1import numpy as np
2
3#desired expected rho (of the distribution of the corr matrix)
4rho = 0.5
5
6# desired correlation matrix
7cor_matrix = np.ones((5,5))* rho
8np.fill_diagonal(cor_matrix,1) # 1s in diagonal
9print(cor_matrix)
10
11# this is artificial case but it will result in the derired distribution.
12array([[1. , 0.5, 0.5, 0.5, 0.5],
13       [0.5, 1. , 0.5, 0.5, 0.5],
14       [0.5, 0.5, 1. , 0.5, 0.5],
15       [0.5, 0.5, 0.5, 1. , 0.5],
16       [0.5, 0.5, 0.5, 0.5, 1. ]])
17
18
19L = np.linalg.cholesky(cor_matrix)
20
21# build some signals that will result in the desired correlation matrix
22X_synthetic = L.dot(np.random.normal(0,1, (5,2000)))
23
24# estimate their correlation matrix
25np.corrcoef(X_synthetic)
26
27array([[1.        , 0.50576661, 0.51472813, 0.47208374, 0.49260528],
28       [0.50576661, 1.        , 0.4798111 , 0.48540114, 0.47225243],
29       [0.51472813, 0.4798111 , 1.        , 0.4649033 , 0.4745259 ],
30       [0.47208374, 0.48540114, 0.4649033 , 1.        , 0.50059795],
31       [0.49260528, 0.47225243, 0.4745259 , 0.50059795, 1.        ]])
32
33#* Very good approximation. All values are fluctuating around 0.5.
34#* So the distribution of the correlation values of `X_synthetic` is around the expected value `0.5`.
35
similar questions