Python 混淆矩阵中的白线?

Python 混淆矩阵中的白线?,python,numpy,confusion-matrix,Python,Numpy,Confusion Matrix,关于numpy矩阵,我有一个非常普遍的问题:我试图根据线条来规范化结果,但是我得到了一些奇怪的白线。这是因为除法中的某些零卡住了吗 代码如下: import numpy as np from matplotlib.pylab import * def confusion_matrix(results,tagset): # results : list of tuples (predicted, true) # tagset : list of tags np.sete

关于numpy矩阵,我有一个非常普遍的问题:我试图根据线条来规范化结果,但是我得到了一些奇怪的白线。这是因为除法中的某些零卡住了吗

代码如下:

import numpy as np
from matplotlib.pylab import *

def confusion_matrix(results,tagset):
    # results : list of tuples (predicted, true)
    # tagset  : list of tags
    np.seterr(divide='ignore', invalid='ignore')
    mat     = np.zeros((len(tagset),len(tagset)))
    percent = [0,0]
    for guessed,real in results :
        mat[tagset.index(guessed),tagset.index(real)] +=1
        if guessed == real :
            percent[0] += 1
            percent[1] += 1
        else :
            percent[1] += 1
    mat /=  mat.sum(axis=1)[:,np.newaxis]
    matshow(mat,fignum=100)
    xticks(arange(len(tagset)),tagset,rotation =90,size='x-small')
    yticks(arange(len(tagset)),tagset,size='x-small')
    colorbar()
    show()
    #print "\n".join(["\t".join([""]+tagset)]+["\t".join([tagset[i]]+[str(x) for x in 
                (mat[i,:])]) for i in xrange(mat.shape[1])])
    return (percent[0] / float(percent[1]))*100

谢谢你的时间!(我希望答案不太明显)

不直接回答您的问题,但这很容易做到:

输出:

[[13  0  0]
 [ 0 15  1]
 [ 0  0  9]]

简而言之,您有一些标签,而这些标签从未被猜到。因为您正在根据猜测标记的次数进行规范化,所以您有一行
0/0
,这将产生
np.nan
。默认情况下,matplotlib的颜色栏将设置为无填充颜色,从而使轴的背景显示(默认情况下为白色)

下面是一个重现当前问题的快速示例:

import numpy as np
import matplotlib.pyplot as plt

def main():
    tags = ['A', 'B', 'C', 'D']
    results = [('A', 'A'), ('B', 'B'), ('C', 'C'), ('A', 'D'), ('C', 'A'),
               ('B', 'B'), ('C', 'B')]
    matrix = confusion_matrix(results, tags)
    plot(matrix, tags)
    plt.show()

def confusion_matrix(results, tagset):
    output = np.zeros((len(tagset), len(tagset)), dtype=float)
    for guessed, real in results:
        output[tagset.index(guessed), tagset.index(real)] += 1
    return output / output.sum(axis=1)[:, None]

def plot(matrix, tags):
    fig, ax = plt.subplots()
    im = ax.matshow(matrix)
    cb = fig.colorbar(im)
    cb.set_label('Percentage Correct')

    ticks = range(len(tags))
    ax.set(xlabel='True Label', ylabel='Predicted Label',
           xticks=ticks, xticklabels=tags, yticks=ticks, yticklabels=tags)
    ax.xaxis.set(label_position='top')
    return fig

main()

如果我们看一下混淆矩阵:

array([[ 0.5  ,  0.   ,  0.   ,  0.5  ],
       [ 0.   ,  1.   ,  0.   ,  0.   ],
       [ 0.333,  0.333,  0.333,  0.   ],
       [   nan,    nan,    nan,    nan]])
如果您想避免在从不猜测标记时出现问题,可以执行类似的操作:

def confusion_matrix(results, tagset):
    output = np.zeros((len(tagset), len(tagset)), dtype=float)
    for guessed, real in results:
        output[tagset.index(guessed), tagset.index(real)] += 1
    num_guessed = output.sum(axis=1)[:, None]
    num_guessed[num_guessed == 0] = 1
    return output / num_guessed
这将产生(其他所有内容都相同):


一个示例图像可能会有所帮助(什么是“奇怪的白线”)。为了简化调试,您可以尝试将代码分为两部分:一部分创建矩阵,另一部分绘制矩阵。然后在ipython(或其他)中运行第一个函数以获得矩阵。检查整条线的数据中是否没有0或NaN,并且它看起来与您期望的一样。哦,好的。谢谢。好吧,如果我跳过规范化部分,我的就行了。。。所以,如果我想用你的代码规范化矩阵,我需要在之前(在列表中)这样做,对吗?我将检查scikit,但我想自己实现它。。。
def confusion_matrix(results, tagset):
    output = np.zeros((len(tagset), len(tagset)), dtype=float)
    for guessed, real in results:
        output[tagset.index(guessed), tagset.index(real)] += 1
    num_guessed = output.sum(axis=1)[:, None]
    num_guessed[num_guessed == 0] = 1
    return output / num_guessed