【问题标题】:Compute correlation between features and target variable计算特征和目标变量之间的相关性
【发布时间】:2018-09-25 11:44:49
【问题描述】:

计算我的特征和目标变量之间相关性的最佳解决方案是什么?我的数据框有 1000 行和 40 000 列...

示例:

df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]], columns=['Feature1', 'Feature2','Feature3','Target'])

这段代码运行良好,但在我的数据帧上太长了……我只需要相关矩阵的最后一列:与目标相关(不是成对特征相关)。

corr_matrix=df.corr()
corr_matrix["Target"].sort_values(ascending=False)

np.corcoeff() 函数适用于数组,但我们可以排除成对特征相关性吗?

【问题讨论】:

标签: python numpy dataframe correlation


【解决方案1】:

您可以在每一列上使用 pandas corr

df.drop("Target", axis=1).apply(lambda x: x.corr(df.Target))

【讨论】:

  • 正是我需要的!
【解决方案2】:

由于 Pandas 0.24 于 2019 年 1 月发布,您可以简单地使用DataFrame.corrwith()

df.corrwith(df["Target"])

【讨论】:

  • 我们如何将这个相关数组绘制为热图?
【解决方案3】:

您可以像这样在每个特征列上使用 scipy.stats.pearsonr:

import pandas as pd
import numpy as np
from scipy.stats import pearsonr

# example data
df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]],
                  columns=['Feature1', 'Feature2','Feature3','Target'])

# Only compute pearson prod-moment correlations between feature
# columns and target column
target_col_name = 'Target'
feature_target_corr = {}
for col in df:
    if target_col_name != col:
        feature_target_corr[col + '_' + target_col_name] = \
            pearsonr(df[col], df[target_col_name])[0]
print("Feature-Target Correlations")
print(feature_target_corr)

【讨论】:

    【解决方案4】:
    df = pd.DataFrame([[1, 2, 4 ,6], [1, 3, 4, 7], [4, 6, 8, 12], [5, 3, 2 ,10]], columns=['Feature1', 'Feature2','Feature3','Target'])
    

    关于目标变量与所有其他特征之间的相关性:

    df.corr()['Target']
    

    这适用于我的情况。让我知道是否有任何更正/更新。

    要获得任何确凿的结果,您的实例应至少是您的功能数量的 10 倍。

    【讨论】:

    • 这将不必要地计算所有列之间的相关性。相反,您应该使用df.corrwith(df['target'])
    猜你喜欢
    • 2018-05-20
    • 2019-03-09
    • 1970-01-01
    • 2019-02-14
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    相关资源
    最近更新 更多