如何为分类特征绘制 Cramer's V 热图?

ebr*_*imi 6 data-visualization heatmap python-3.x categorical-data bokeh

应该使用 Crammer's V 计算分类变量之间的关联。因此,我找到了以下代码来绘制它,但我不知道他为什么将它绘制为“贡献”,这是一个数字变量?

def cramers_corrected_stat(confusion_matrix):
    """ calculate Cramers V statistic for categorical-categorical association.
        uses correction from Bergsma and Wicher, 
        Journal of the Korean Statistical Society 42 (2013): 323-328
    """
    chi2 = ss.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)))


cols = ["Party", "Vote", "contrib"]
corrM = np.zeros((len(cols),len(cols)))
# there's probably a nice pandas way to do this
for col1, col2 in itertools.combinations(cols, 2):
    idx1, idx2 = cols.index(col1), cols.index(col2)
    corrM[idx1, idx2] = cramers_corrected_stat(pd.crosstab(df[col1], df[col2]))
    corrM[idx2, idx1] = corrM[idx1, idx2]

corr = pd.DataFrame(corrM, index=cols, columns=cols)
fig, ax = plt.subplots(figsize=(7, 6))
ax = sns.heatmap(corr, annot=True, ax=ax); ax.set_title("Cramer V Correlation between Variables");
Run Code Online (Sandbox Code Playgroud)

我还发现了Bokeh。但是,我不确定它是否使用 Crammer's V 来绘制热图?

真的,我有两个分类特征:第一个有 2 个类别,第二个有 37 个类别。你能告诉我如何绘制 Crammer 的 V 热图吗?

我的数据集的某些部分在这里

提前致谢。

Edw*_*ard 2

有什么问题?代码是绝对正确的。

ax在这种情况下,是变量之间的相关矩阵。使用“贡献”是不正确的,但您可以在下面的文章中看到引用

*

“对贡献变量这样做是不对的,但我们稍后会用模型做更多的事情。”

* 作者仅作为示例显示此变量。在你的例子中,制作 Crammer's V 情节的原因是什么?你只有两个变量(正如我所见),你只会得到一个相关系数 Crammer's V

但当然,您可以在数据上重复代码并绘制 Crammer 的 V 热图