为图像分类模型绘制混淆矩阵

时间:2018-07-11 09:38:06

标签: python scikit-learn keras

我用keras构建了图像分类CNN。虽然模型本身可以正常工作(它可以根据新数据正确预测),但在绘制模型的混淆矩阵和分类报告时遇到了问题。

我使用ImageDataGenerator训练了模型

train_path = '../DATASET/TRAIN'
test_path = '../DATASET/TEST'
IMG_BREDTH = 30
IMG_HEIGHT = 60
num_classes = 2

train_batch = ImageDataGenerator(featurewise_center=False,
                                 samplewise_center=False, 
                                 featurewise_std_normalization=False, 
                                 samplewise_std_normalization=False, 
                                 zca_whitening=False, 
                                 rotation_range=45, 
                                 width_shift_range=0.2, 
                                 height_shift_range=0.2, 
                                 horizontal_flip=True, 
                                 vertical_flip=False).flow_from_directory(train_path, 
                                                                          target_size=(IMG_HEIGHT, IMG_BREDTH), 
                                                                          classes=['O', 'R'], 
                                                                          batch_size=100)

test_batch = ImageDataGenerator().flow_from_directory(test_path, 
                                                      target_size=(IMG_HEIGHT, IMG_BREDTH), 
                                                      classes=['O', 'R'], 
                                                      batch_size=100)

这是混淆矩阵和分类报告的代码

batch_size = 100
target_names = ['O', 'R']
Y_pred = model.predict_generator(test_batch, 2513 // batch_size+1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
cm = metrics.confusion_matrix(test_batch.classes, y_pred)
print(cm)
print('Classification Report')
print(metrics.classification_report(test_batch.classes, y_pred))

对于混淆矩阵,我得到了滚动结果(这似乎是错误的)

Confusion Matrix
[[1401    0]
 [1112    0]]

假阳性和真阳性均为0。 对于分类报告,我得到以下输出和警告

Classification Report
             precision    recall  f1-score   support

          0       0.56      1.00      0.72      1401
          1       0.00      0.00      0.00      1112

avg / total       0.31      0.56      0.40      2513

/Users/sashaanksekar/anaconda3/lib/python3.6/site-packages/sklearn/metrics/classification.py:1135: UndefinedMetricWarning: Precision and F-score are ill-defined and being set to 0.0 in labels with no predicted samples.
  'precision', 'predicted', average, warn_for)

我正在尝试预测物体是有机的还是可回收的。我大约有22000张火车图像和2513张测试图像。

我是机器学习的新手。我究竟做错了什么?

预先感谢

3 个答案:

答案 0 :(得分:1)

我使用 sklearn plot_confusion_matrix

为了使用它,我做了一个 hack,所以当 sklearn 估计器进行预测时不要抱怨,因为它是 Keras 模型。 因此,如果模型是经过训练的 keras 模型:

X,y = test_generator.next()
y = np.argmax(y, axis=1)

from sklearn.metrics import plot_confusion_matrix
class newmodel(MLPClassifier):
    def __init__(self, model):
        self.model = model
    def predict(self, X):
        y = self.model.predict(X)
        return np.argmax(y,axis=1)

model1 = newmodel(model)
plot_confusion_matrix(model1, X, y , normalize='true', xticks_rotation = 'vertical', display_labels = list(train_generator.class_indices.keys()))

它对我有用。

enter image description here

答案 1 :(得分:0)

要绘制混淆矩阵,请执行以下操作:

import matplotlib.pyplot as plt
import numpy as np

cm = metrics.confusion_matrix(test_batch.classes, y_pred)
# or
#cm = np.array([[1401,    0],[1112, 0]])

plt.imshow(cm, cmap=plt.cm.Blues)
plt.xlabel("Predicted labels")
plt.ylabel("True labels")
plt.xticks([], [])
plt.yticks([], [])
plt.title('Confusion matrix ')
plt.colorbar()
plt.show()

enter image description here

参考文献:

https://www.dataschool.io/simple-guide-to-confusion-matrix-terminology/

https://machinelearningmastery.com/confusion-matrix-machine-learning/

答案 2 :(得分:0)

如果由于类似的问题有人像我一样来到这里,可能有几件事情可以帮忙:

  1. 确保在测试集生成器中设置shuffle = False
  2. 最好将batch_size设置为图像数量的除数。如果不是,请确保生成器不会跳过任何图像;
  3. 首先尝试不进行增强训练;
  4. 似乎存在一个问题,predict_generator的输出不一致,请尝试设置workers = 0,如下所示:

    predictions = model.predict_generator(testGenerator, steps = np.ceil(testGenerator.samples / testGenerator.batch_size), verbose=1, workers=0)

就我而言,如果我不这样做,每次打电话给predict_generator时,预测都会改变。

  1. 只有两个类时,必须使用:

    predictedClasses = np.where(predictions>0.5, 1, 0) 而不是np.argmax(Y_pred, axis=1),因为在这种情况下np.argmax将始终输出0。

    np.where(predictions>0.5, 1, 0)如果预测> 0.5则返回1,否则返回0。