【问题标题】:How to get confusion matrix and ROC curve when using flow_from_directory?使用flow_from_directory时如何获取混淆矩阵和ROC曲线?
【发布时间】:2021-09-18 23:49:26
【问题描述】:

我已经使用以下方法训练了一个模型:

    train_datagen = ImageDataGenerator(rescale = 1/255,
                                       zoom_range=0.3,
                                       shear_range=0.3,
                                       horizontal_flip=True,
                                       rotation_range=30,
                                       fill_mode="nearest",
                                       validation_split = 0.2)
    
    test_datagen  = ImageDataGenerator(rescale = 1./255
                                      )



    train_dataset  = train_datagen.flow_from_directory(directory = './train',
                                                       target_size = tsize,
                                                       class_mode = 'categorical',
                                                       subset = 'training',
                                                       batch_size = BS)
    
    valid_dataset = train_datagen.flow_from_directory(directory = './train',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      subset = 'validation',
                                                      batch_size = BS)
    
    test_dataset = test_datagen.flow_from_directory(directory = './test',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      batch_size = BS)

还有:

    hist = model.fit(train_dataset,validation_data=valid_dataset,epochs=30,callbacks=[vgg_step_1])

我如何绘制混淆矩阵?,我很困惑,我只有验证与训练图。

【问题讨论】:

    标签: tensorflow machine-learning keras


    【解决方案1】:

    要获得混淆矩阵,您需要对测试集进行预测。然后,您需要将预测值和相关的真实值提供给混淆矩阵。注意 - 在您的 test_dataset 代码中,您必须在 flow_from_directory 中设置 shuffle=False! 下面的代码应该生成一个适应性强的混淆矩阵图和分类报告。 model 是您经过训练的模型。

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.pyplot import imshow
    import seaborn as sns
    sns.set_style('darkgrid')
    def cm_cr(test_gen, model):
        preds=model.predict(test_gen)    
        labels=test_gen.labels
        classes=list(test_gen.class_indices.keys()) # ordered lst of class names 
        pred_list=[ ] # will store the predicted classes here
        true_list=[]
        for i, p in enumerate (preds):
            index=np.argmax(p)
            pred_list.append(classes[index])
            true_list.append(classes[labels[i]])
        y_pred=np.array(pred_list)
        y_true=np.array(true_list)
        clr = classification_report(y_true, y_pred, target_names=classes)
        print("Classification Report:\n----------------------\n", clr)
        cm = confusion_matrix(y_true, y_pred )        
        length=len(classes)
        if length<8:
            fig_width=8
            fig_height=8
        else:
            fig_width= int(length * .5)
            fig_height= int(length * .5)
        plt.figure(figsize=(fig_width, fig_height))
        sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False)       
        plt.xticks(np.arange(length)+.5, classes, rotation= 90, fontsize=16)
        plt.yticks(np.arange(length)+.5, classes, rotation=0, fontsize=16)
        plt.xlabel("Predicted")
        plt.ylabel("Actual")
        plt.title("Confusion Matrix")
        plt.show()
    
    cm_cr(test_dataset, model)
    

    我没有做 ROC 曲线,但有一个很好的教程 here 用于该活动。

    【讨论】:

      猜你喜欢
      • 2018-12-26
      • 2018-09-23
      • 2016-01-15
      • 2017-08-29
      • 2019-12-26
      • 2022-06-15
      • 2016-11-28
      • 2014-09-03
      相关资源
      最近更新 更多