generating confusion matrix in keras for multiclass classification
通过训练模型获得高达98%的准确性,但是混淆矩阵显示出很高的未分类率。
我正在使用预训练的VGG16模型上的迁移学习方法使用keras进行多类分类。
问题是使用CNN将图像分类为5种番茄疾病。
有5种疾病类别,其中包含6970个训练图像和70个测试图像。
训练模型显示96.85%的准确性,而测试显示94%的准确性。
但是问题是当我生成混淆矩阵时,它显示出很高的未分类率。
有人请帮助我,无论我的代码错误还是模型错误?我很困惑我的模型是否给我正确的结果。
而且,如果有人可以向我解释keras如何使用model.fit_generator函数实际计算精度,因为在混淆矩阵上应用精度的一般公式并不能得出与keras计算得出的结果相同的结果。
用于测试数据集的代码是:
1 2 3 4 5 6 7 | test_generator = test_datagen.flow_from_directory( test_dir, target_size=(150, 150), batch_size=20, class_mode='categorical') test_loss, test_acc = model.evaluate_generator(test_generator, steps=50) print('test acc:', test_acc) |
我在其中一个论坛上找到了生成混淆矩阵的代码;
代码是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import numpy as np from sklearn.metrics import confusion_matrix,classification_report batch_size = 20 num_of_test_samples = 70 predictions = model.predict_generator(test_generator, num_of_test_samples // batch_size+1) y_pred = np.argmax(predictions, axis=1) true_classes = test_generator.classes class_labels = list(test_generator.class_indices.keys()) print(class_labels) print(confusion_matrix(test_generator.classes, y_pred)) report = classification_report(true_classes, y_pred, target_names=class_labels) print(report) |
以下是我得到的结果:
测试精度:
1 2 | Found 70 images belonging to 5 classes. test acc: 0.9420454461466182 |
混淆矩阵的结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | ['TEB', 'TH', 'TLB', 'TLM', 'TSL'] [[2 3 2 4 3] [4 2 3 0 5] [3 3 3 2 3] [3 3 2 4 2] [2 2 4 4 2]]] precision recall f1-score support TEB 0.14 0.14 0.14 14 TH 0.15 0.14 0.15 14 TLB 0.21 0.21 0.21 14 TLM 0.29 0.29 0.29 14 TSL 0.13 0.14 0.14 14 micro avg 0.19 0.19 0.19 70 macro avg 0.19 0.19 0.19 70 weighted avg 0.19 0.19 0.19 70 |
创建测试数据生成器时,默认情况下
只需在测试数据生成器中将shuffle设置为False,预测就会以正确的顺序进行。 由于验证/测试数据的目的是评估模型,因此您几乎总是可以将shuffle设置为False。
我可能参加聚会的时间很晚,但是也许您没有像训练火车那样对测试数据进行预处理。 尝试从VGG16导入预处理功能,并将其作为参数(preprocessing_function)添加到生成器中。
测试标签应该是class_indices而不是class
1 | true_classes = test_generator.class_indices |