在由数千种相关矩阵组成的字典中进行有效计算。

问题描述 投票:0回答:1

基于20种资产的每日观测数据集,我创建了一个由(滚动)相关矩阵组成的字典。我使用日期指数作为字典的键。

现在我想做的是(以一种有效的方式)比较字典中的所有相关矩阵,并将结果保存在一个新的矩阵中。我们的想法是比较一段时间内的相关结构。

import pandas as pd
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import cophenet


key_list = dict_corr.keys()

# Create empty matrix
X = np.empty(shape=[len(key_list),len(key_list)])

key1_index = 0
key2_index = 0
for key1 in key_list:


    # Extract correlation matrix from dictionary
    corr1_temp = d[key1]

    # Transform correlation matrix into distance matrix
    dist1_temp = ((1-corr1_temp)/2.)**.5

    # Extract hierarchical structure from distance matrix
    link1_temp = linkage(dist1_temp,'single') 

    for key2 in key_list:

        corr2_temp = d[key2]
        dist2_temp = ((1-corr2_temp)/2.)**.5
        link2_temp = linkage(dist2_temp,'single')

        # Compare hierarchical structure between the two correlation matrizes -> results in 2x2 matrix
        temp = np.corrcoef(cophenet(link1_temp),cophenet(link2_temp))

        # Extract from the resulting 2x2 matrix the correlation
        X[key1_index, key2_index] = temp[1,0]

        key2_index =+ 1

    key1_index =+1

我很清楚,使用两个for循环可能是效率最低的方式。

所以,我很感激任何有用的意见,如何加快计算的速度

最好的

python pandas numpy scipy hierarchical-clustering
1个回答
1
投票

你可以看看 itertools 然后插入你的代码来计算函数中的相关性 (compute_corr)在单次for循环中调用。

import itertools
for key_1, key_2 in itertools.combinations(dict_corr, 2):
    correlation = compute_corr(key_1, key_2, dict_corr)
    #now store correlation in a list 

如果你关心顺序,就用 itertools.permutations(dict_corr, 2) 而不是组合。

编辑

由于你想要所有可能的键的组合(也是一个键与自身的组合),你应该使用 itertools.product.

l_corr = [] #list to store all the output from the function
for key_1, key_2 in itertools.product(key_list, repeat= 2 ):
    l_corr.append(compute_corr(key_1, key_2, dict_corr))

现在 l_corr 会很长。len(key_list)*len(key_list). 你可以用这种方式将这个列表转换为矩阵。

np.array(l_corr).reshape(len(key_list),len(key_list))

虚例:

def compute_corr(key_1, key_2, dict_corr):
    return key_1 * key_2 #dummy result from the function

dict_corr={1:"a",2:"b",3:"c",4:"d",5:"f"}
key_list = dict_corr.keys()

l_corr = []
for key_1, key_2 in itertools.product(key_list, repeat= 2 ):
    print(key_1, key_2)
    l_corr.append(compute_corr(key_1, key_2, dict_corr))

组合。

1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
3 1
3 2
3 3
3 4
3 5
4 1
4 2
4 3
4 4
4 5
5 1
5 2
5 3
5 4
5 5

创建最后的矩阵。

np.array(l_corr).reshape(len(key_list),len(key_list))

array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25]])

如果我错过了什么,请告诉我 希望这能帮助你

© www.soinside.com 2019 - 2024. All rights reserved.