【问题标题】:co-relation with multiple categorical variables与多个分类变量的相关性
【发布时间】:2020-04-16 08:44:47
【问题描述】:

有没有一种方法可以找到多个分类变量之间的关联关系?当您拥有一个包含大量分类变量的非常大的数据集时。

【问题讨论】:

标签: statistics data-science data-analysis


【解决方案1】:

正如@arpitrathi 提到的,通常您需要使用 Cramer 的 V。 我记得,网上已经有准备好的代码sn-ps, 我会留给你我通常使用的那个,也许它会对你有所帮助。

您需要导入一些库才能使用它。

from scipy import stats
import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

def cramers_v(x, y):
    '''
    Returns cramers_v for 2 categorical features
    '''
    confusion_matrix = pd.crosstab(x,y)
    chi2 = stats.chi2_contingency(confusion_matrix)[0]
    n = confusion_matrix.sum().sum()
    phi2 = chi2/n
    r,k = confusion_matrix.shape
    phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1))
    rcorr = r-((r-1)**2)/(n-1)
    kcorr = k-((k-1)**2)/(n-1)
    return np.sqrt(phi2corr/min((kcorr-1),(rcorr-1)))


def heatmap_categorical_columns_w_dependant_categorical(df, dependent_variable, columns):
    '''
    Takes df, a dependant variable as str
    Returns a heatmap of catecorical columns cramers_v with dependent variable 
    '''
    plt.figure(figsize=(8, 10))
    corrM = [cramers_v(df[dependent_variable], df[column]) for column in columns]
    corr = pd.DataFrame(corrM, index=columns, columns=[dependent_variable])
    ax = sns.heatmap(corr,
            annot=True,
            cmap='coolwarm', 
            vmin=-1,
            vmax=1,
           )
    ax.set_title("Cramer V Correlation between Variables")
    return ax

结果将类似于:

您可以在此代码中查看使用示例: https://github.com/OzmundSedler/IBM-advanced-DS-coursera/blob/master/4%20Capstone%20/ML-project-draft.ipynb

【讨论】:

【解决方案2】:

您可以使用此代码通过 plt.matshow 获取多个变量之间的相关性。其中 'bikesharing_data' 是 pandas DataFrame。

    plt.figure(figsize=[12, 8])
    plt.matshow(bikesharing_data.corr(),
    fignum=False,
    aspect='equal')

    columns = len(bikesharing_data.columns)

    plt.xticks(range(columns), bikesharing_data.columns)
    plt.yticks(range(columns), bikesharing_data.columns)

    plt.colorbar() 
    plt.xticks(rotation=90)
    plt.title('Correlation', y=1.2)

    plt.show()

您可以使用以下方式删除数值变量:

    features = bikesharing_data.drop(['x1', 'x2', ... ,'xn'], axis=1)

结果输出如下; Correlation Matrix

【讨论】:

    猜你喜欢
    • 2016-12-14
    • 2018-01-17
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 2020-10-24
    • 1970-01-01
    相关资源
    最近更新 更多