擅长:python、mysql、java
<p>不幸的是,<a href="https://stackoverflow.com/a/38727681/3490833">Alt's answer</a>没有适合我。给<code>np.sqrt</code>函数的值,其中大部分为负,因此得到的协方差值为nan。</p>
<p>我也不能使用<a href="https://stackoverflow.com/a/19235925/3490833">ali_m's answer</a>,因为我的矩阵太大,无法在内存中容纳<code>centering = rowsum.dot(rowsum.T.conjugate()) / n</code>矩阵(矩阵的维数是:3.5*10^6 x 33)</p>
<p>相反,我使用<a href="http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html" rel="nofollow noreferrer">scikit-learn's ^{<cd3>}</a>来计算标准稀疏矩阵,然后使用乘法来获得相关矩阵。</p>
<pre><code>from sklearn.preprocessing import StandardScaler
def compute_sparse_correlation_matrix(A):
scaler = StandardScaler(with_mean=False)
scaled_A = scaler.fit_transform(A) # Assuming A is a CSR or CSC matrix
corr_matrix = (1/scaled_A.shape[0]) * (scaled_A.T @ scaled_A)
return corr_matrix
</code></pre>
<p>我相信这种方法比其他提到的方法更快、更健壮。此外,它还保持了输入矩阵的稀疏性。</p>