Seaborn Confusion Matrix (heatmap) 2 color schemes (correct diagonal vs wrong rest)

后端 未结 2 718
盖世英雄少女心
盖世英雄少女心 2021-01-07 10:37

Background

In a confusion matrix, the diagonal represents the cases that the predicted label matches the correct label. So the diagonal is good, while all other cel

2条回答
  •  礼貌的吻别
    2021-01-07 10:40

    You could first plot the heatmap with colormap 'OrRd' and then overlay it with a heatmap with colormap 'Blues', with the upper and lower triangle values replaced with NaN's, see the following example:

    def diagonal_heatmap(m):
    
        vmin = np.min(m)
        vmax = np.max(m)    
        
        sns.heatmap(cf_matrix, annot=True, cmap='OrRd', vmin=vmin, vmax=vmax)
    
        diag_nan = np.full_like(m, np.nan, dtype=float)
        np.fill_diagonal(diag_nan, np.diag(m))
        
        sns.heatmap(diag_nan, annot=True, cmap='Blues', vmin=vmin, vmax=vmax, cbar_kws={'ticks':[]}) 
    
    
    
    
    cf_matrix = np.array([[50, 2, 38],
                          [7, 43, 32],
                          [9,  4, 76]])
    
    diagonal_heatmap(cf_matrix)
    

提交回复
热议问题