【问题标题】:Correlation between the the columns of the matrix when there are columns with constant value ( Very Slow!)当存在具有恒定值的列时,矩阵列之间的相关性(非常慢!)
【发布时间】:2020-07-24 17:16:25
【问题描述】:

我在 python 中编写了一个不返回“nan”的自定义相关代码,事实上,当它尝试计算任意两列之间的相关性时,它会返回 0,其中任一列或两列都是常量

def getCorreCustom(matrix,columns=30):
  A=np.zeros((columns,columns))
  for i in range(columns):
    for j in range(columns):
      if i==j:
        A[i,j]=1
      else:
        a=matrix[:,i]
        b=matrix[:,j]

        if np.std(a)==0 or np.std(b)==0:
          A[i,j]=0
        else:
          A[i,j]=scipy.stats.spearmanr(a,b).correlation
  return A

所以当我尝试使用内置的 numpy 相关函数时,它会将“nan”值放在它获得常量列的任何位置

Test=np.random.random((50,30))
Test[:,0]=1                          //deliberately setting constant column
Test[:,10]=1

np.corrcoef(Test.transpose()).shape

使用 numpy.corrcoef 输出

/usr/local/lib/python3.6/dist-packages/numpy/lib/function_base.py:2534: RuntimeWarning: invalid value encountered in true_divide
  c /= stddev[:, None]
/usr/local/lib/python3.6/dist-packages/numpy/lib/function_base.py:2535: RuntimeWarning: invalid value encountered in true_divide
  c /= stddev[None, :]
(30, 30)

我自定义的相关系数

R=getCorreCustom(Test)
R.shape    // 30 x 30

问题

我的代码运行良好,但我遇到的最大问题是我的代码非常慢,而且在大型矩阵上,因为我需要尺寸为 100 x 30 有时是 170 x 30,它变得太慢了。

那么我怎样才能使这个代码快速,因为我确信内置的 numpy 相关代码是矢量化的并且非常快?

注意

【问题讨论】:

  • 您可以使用np.nan_to_num 安全地执行此操作,例如np.nan_to_num(np.corrcoef(Test))

标签: python numpy


【解决方案1】:

你可以像这样使用熊猫

from datetime import datetime
import pandas as pd
Test = np.random.random((50, 30))
Test[:, 0] = 1
Test[:, 10] = 1
start_time = datetime.now()
R = getCorreCustom(Test)
print("Custom Method")
print(datetime.now() - start_time)
print(R.shape)
start_time = datetime.now()
P = pd.DataFrame(Test)
print("Pandas Method")
print(datetime.now() - start_time)
print(P.corr(method="spearman").fillna(0).shape)

结果是:

Custom Method
0:00:00.498294
(30, 30)
Pandas Method
0:00:00.000230
(30, 30)

这比我电脑上的自定义方法快 2166.495652173913 倍。

【讨论】:

  • 问题是它也给出了 nan 值
猜你喜欢
  • 1970-01-01
  • 2015-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多