这里的问题是指一个巨大的数据集。但是,我看到的所有答案都是处理数据帧。我提出了一个并行运行的 scipy 稀疏矩阵的答案。这不是返回一个巨大的相关矩阵,而是在检查所有字段的正和负 Pearson 相关后返回一个字段的特征掩码。
我还尝试使用以下策略最小化计算:
- 处理每一列
- 从当前列 + 1 开始并向右移动计算相关性。
- 对于任何 abs(correlation) >= 阈值,将当前列标记为要删除,并且不再计算相关性。
- 对数据集中除最后一列之外的每一列执行这些步骤。
通过保留标记为要删除的列的全局列表并跳过对此类列的进一步相关性计算,这可能会进一步加快速度,因为列将无序执行。但是,我对 python 中的竞争条件了解不够,无法在今晚实现这一点。
与返回整个相关矩阵相比,返回列掩码显然允许代码处理更大的数据集。
使用此函数检查每一列:
def get_corr_row(idx_num, sp_mat, thresh):
# slice the column at idx_num
cols = sp_mat.shape[1]
x = sp_mat[:,idx_num].toarray().ravel()
start = idx_num + 1
# Now slice each column to the right of idx_num
for i in range(start, cols):
y = sp_mat[:,i].toarray().ravel()
# Check the pearson correlation
corr, pVal = pearsonr(x,y)
# Pearson ranges from -1 to 1.
# We check both positive and negative correlations >= thresh using abs(corr)
if abs(corr) >= thresh:
# stop checking after finding the 1st correlation > thresh
return False
# Mark column at idx_num for removal in the mask
return True
并行运行列级相关性检查:
from joblib import Parallel, delayed
import multiprocessing
def Get_Corr_Mask(sp_mat, thresh, n_jobs=-1):
# we must make sure the matrix is in csc format
# before we start doing all these column slices!
sp_mat = sp_mat.tocsc()
cols = sp_mat.shape[1]
if n_jobs == -1:
# Process the work on all available CPU cores
num_cores = multiprocessing.cpu_count()
else:
# Process the work on the specified number of CPU cores
num_cores = n_jobs
# Return a mask of all columns to keep by calling get_corr_row()
# once for each column in the matrix
return Parallel(n_jobs=num_cores, verbose=5)(delayed(get_corr_row)(i, sp_mat, thresh)for i in range(cols))
一般用法:
#Get the mask using your sparse matrix and threshold.
corr_mask = Get_Corr_Mask(X_t_fpr, 0.95)
# Remove features that are >= 95% correlated
X_t_fpr_corr = X_t_fpr[:,corr_mask]