如何使用下面的代码构建cramerv矩阵?

2024-10-01 17:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着用cramers创建一个热图/相关矩阵。我发现下面的代码可以帮助我解决这个问题,但是当使用itertools.组合它不返回与自身的组合,例如0,0,1,1等等,所以我的矩阵是完全错误的,因为当一个列与它自己比较时,对角线应该是1,但它们是0。我的20个专栏中除了2个是分类的,这就是为什么我使用cramers

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 = df.columns.to_list()
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]

我怎么解决这个问题?在


Tags: dfformatrixstatcol2col1colsitertools

热门问题