我正在嘗試使用 cramers 創建一個熱圖/相關矩陣。我發現下面的代碼可以幫助我解決這個問題,但是當使用 itertools.combinations 時,它不會返回與自身的組合,例如 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 thisfor 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]我該如何解決?
添加回答
舉報
0/150
提交
取消