混乱矩阵中的白线?

时间:2015-01-06 17:14:51

标签: 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.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

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

2 个答案:

答案 0 :(得分:2)

简而言之,您有一些标签,其中特定标签从未被猜到。因为您按照标记被猜测的次数进行了标准化,所以您有一行0/0,这会产生np.nan。默认情况下,matplotlib的颜色条将NaN设置为没有填充颜色,导致轴的背景显示(默认情况下为白色)。

以下是重现当前问题的简单示例:

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()

enter image description here

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

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

哪个收益率(其他一切都相同):

enter image description here

答案 1 :(得分:1)

不直接回答您的问题,但使用scikit-learn非常容易:

from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt

y_test=[2, 1, 0, 2, 0, 2, 0, 1, 1, 1, 2, 1, 1, 1, 1, 0, 1, 1, 0, 0, 2, 1, 0, 0, 2, 0, 0, 1, 1, 0, 2, 1, 0, 2, 2, 1, 0, 1]
y_pred = [2, 1, 0, 2, 0, 2, 0, 1, 1, 1, 2, 1, 1, 1, 1, 0, 1, 1, 0, 0, 2, 1, 0, 0, 2, 0, 0, 1, 1, 0, 2, 1, 0, 2, 2, 1, 0, 2]

cm = confusion_matrix(y_test, y_pred)
print(cm)

# Plot confusion matrix
plt.matshow(cm)
plt.title('Confusion matrix')
plt.colorbar()    plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()

<强>输出:

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

enter image description here