【问题标题】:looking for a simplied approach for calculating pairwise correlation among arrays寻找一种简化的方法来计算数组之间的成对相关性
【发布时间】:2021-06-24 07:23:44
【问题描述】:

我有 n 个长度为 m 的数组,我想在数组之间取成对的 Pearson 相关性,然后取它们的平均值。

数组保存为形状为(n, m)的numpy数组

一种方法是编写“两个for循环操作”。但是,我想知道这可以用python以更简化的方式编写吗?

我当前的代码如下所示:

sum_dd = 0
counter_dd = 0
for i in range(len(stc_data_roi)):
    for j in range(i+1, len(stc_data_roi)):
        sum_dd += np.corrcoef(stc_data_roi[i], stc_data_roi[j])
        counter += 1

【问题讨论】:

  • 创建一个包含您的数据的 pandas 数据框并使用方法corr。请添加Minimal reproducible example,以便我们为您提供更多帮助
  • 您希望如何关联?也许您可以详细说明一下输入和预期输出

标签: python arrays numpy pearson-correlation


【解决方案1】:

假设您有 n=4 个长度为 m=5 的数组

n = 4
m = 5
X = np.random.rand(n, m)
print(X)

array([[0.49017121, 0.58751099, 0.87868983, 0.75328938, 0.16491984],
   [0.81175397, 0.26486309, 0.42424784, 0.37485824, 0.66667452],
   [0.80901099, 0.84121723, 0.36623767, 0.59928036, 0.22773295],
   [0.59606777, 0.63301654, 0.30963807, 0.82884099, 0.95136045]])

现在转置数组并转换为数据帧。 dataframe 的每一列代表一个数组,然后使用 pandas corr 函数。

df = pd.DataFrame(X.T)
corr_coef = df.corr(method="pearson")
print(corr_coef)

corr_coef 的每一列将表示与其他数组的相关系数,包括它自己(它将是一个)。

#sum of relevant coefficients as per your code
#Subtract by 4 because we don't want self correlation
#Divide by 2 becasue we are adding twice
corr_coef_sum = (corr_coef.sum().sum() - n) / 2
corr_coef_avg = corr_coef_sum / 6 #Total 6 combination in our example case

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-19
    • 2021-08-23
    相关资源
    最近更新 更多