Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 绘制图像分类模型的混淆矩阵_Python_Scikit Learn_Keras - Fatal编程技术网

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

Python 绘制图像分类模型的混淆矩阵,python,scikit-learn,keras,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_c

我用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))
对于混淆矩阵,我得到滚动结果(这似乎是错误的)

假阳性和真阳性为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个测试图像

我是机器学习新手。我做错了什么


提前感谢

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

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

参考资料:


如果有人因为类似的问题而像我一样来到这里,可能有以下几点可以帮助:

  • 确保在测试集生成器中设置
    shuffle=False
  • 最好将批处理大小设置为图像计数的除数。如果没有-确保生成器没有跳过任何图像
  • 先尝试不增加训练
  • 似乎存在一个问题,
    predict\u生成器的输出不一致,如果可能,请尝试设置
    workers=0
    ,如下所示:

    predictions=model.predict\u生成器(testGenerator,steps=np.ceil(testGenerator.samples/testGenerator.batch\u size),verbose=1,workers=0)

  • 在我的例子中,如果我不这样做,每次调用
    predict\u generator
    时预测都会发生变化

  • 如果只有两个类,则必须使用:

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

    np.其中(预测>0.5,1,0)
    如果预测>0.5则返回1,否则返回0


  • 我使用sklearn plot\u Mission\u矩阵

    为了使用它,我做了一个修改,所以当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()))
    
    它对我有用


    问题/错误是什么?混淆矩阵的真阳性和假阳性为0。我觉得这是因为我初始化y_pred的方式。我也不理解分类报告的警告消息。您需要确保在
    度量值中以正确的顺序插入
    y\u pred
    y\u true
    。其次,这种较差的性能可能是由于过度装配或不良的模型造成的。你使用交叉验证吗?不,我没有。由于我是机器学习新手,我不知道如何处理图像数据。你能添加数据吗?我应该如何解释混淆矩阵?你好。混淆矩阵同时显示了很多东西。首先,当黑色块位于对角线上时,性能更高。在这里,你很擅长预测一个类,但是很不擅长预测另一个类。此外,从混淆矩阵,您可以计算灵敏度、特异性、假阳性率、假阴性率等。。。我会在我的回答中添加一些关于CM的参考。我觉得我的y_pred初始化错误。如何初始化y_pred?
    y_pred
    是测试数据的预测标签。在
    模型之前。预测\u生成器
    您是否使用训练数据拟合模型?我使用fit\u生成器训练网络。当我使用predict函数对新数据进行预测时,该模型在大多数情况下运行良好。因此,混淆矩阵中的TP不应为0。
    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()))