python - CNN keras中图像的混淆矩阵

标签 python scikit-learn keras conv-neural-network

我已经使用 keras 训练了我的 CNN 模型(多类分类),现在我想在我的测试图像集上评估该模型。

除了准确度、精确度和召回率之外,还有哪些可能的选项可以用来评估我的模型?我知道如何从自定义脚本中获得精确度和召回率。但是我找不到一种方法来获取我的 12 类图像的混淆矩阵。 Scikit-learn 显示一个 way ,但不适用于图像。 我正在使用 model.fit_generator ()

有没有办法为我的所有类创建混淆矩阵或找到我的类的分类置信度?我使用的是 Google Colab,但我可以下载模型并在本地运行。

如有任何帮助,我们将不胜感激。

代码:

train_data_path = 'dataset_cfps/train'
validation_data_path = 'dataset_cfps/validation'

#Parametres
img_width, img_height = 224, 224

vggface = VGGFace(model='resnet50', include_top=False, input_shape=(img_width, img_height, 3))

#vgg_model = VGGFace(include_top=False, input_shape=(224, 224, 3))

last_layer = vggface.get_layer('avg_pool').output
x = Flatten(name='flatten')(last_layer)
xx = Dense(256, activation = 'sigmoid')(x)
x1 = BatchNormalization()(xx)
x2 = Dropout(0.3)(x1)
y = Dense(256, activation = 'sigmoid')(x2)
yy = BatchNormalization()(y)
y1 = Dropout(0.6)(yy)
x3 = Dense(12, activation='sigmoid', name='classifier')(y1)

custom_vgg_model = Model(vggface.input, x3)


# Create the model
model = models.Sequential()

# Add the convolutional base model
model.add(custom_vgg_model)

model.summary()
#model = load_model('facenet_resnet_lr3_SGD_sameas1.h5')

def recall(y_true, y_pred):
     true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
     possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))
     recall = true_positives / (possible_positives + K.epsilon())
     return recall

def precision(y_true, y_pred):
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision

train_datagen = ImageDataGenerator(
      rescale=1./255,
      rotation_range=20,
      width_shift_range=0.2,
      height_shift_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')


validation_datagen = ImageDataGenerator(rescale=1./255)

# Change the batchsize according to your system RAM
train_batchsize = 32
val_batchsize = 32

train_generator = train_datagen.flow_from_directory(
        train_data_path,
        target_size=(img_width, img_height),
        batch_size=train_batchsize,
        class_mode='categorical')

validation_generator = validation_datagen.flow_from_directory(
        validation_data_path,
        target_size=(img_width, img_height),
        batch_size=val_batchsize,
        class_mode='categorical',
        shuffle=True)

# Compile the model
model.compile(loss='categorical_crossentropy',
              optimizer=optimizers.SGD(lr=1e-3),
              metrics=['acc', recall, precision])
# Train the model
history = model.fit_generator(
      train_generator,
      steps_per_epoch=train_generator.samples/train_generator.batch_size ,
      epochs=100,
      validation_data=validation_generator,
      validation_steps=validation_generator.samples/validation_generator.batch_size,
      verbose=1)

# Save the model
model.save('facenet_resnet_lr3_SGD_new_FC.h5')

最佳答案

以下是获取所有类的混淆矩阵(或者可能是使用 scikit-learn 的统计数据)的方法:

1.预测类

test_generator = ImageDataGenerator()
test_data_generator = test_generator.flow_from_directory(
    test_data_path, # Put your path here
     target_size=(img_width, img_height),
    batch_size=32,
    shuffle=False)
test_steps_per_epoch = numpy.math.ceil(test_data_generator.samples / test_data_generator.batch_size)

predictions = model.predict_generator(test_data_generator, steps=test_steps_per_epoch)
# Get most likely class
predicted_classes = numpy.argmax(predictions, axis=1)

2.获取真实类和类标签

true_classes = test_data_generator.classes
class_labels = list(test_data_generator.class_indices.keys())   

3。使用 scikit-learn 获取统计信息

report = metrics.classification_report(true_classes, predicted_classes, target_names=class_labels)
print(report)    

您可以阅读更多 here

编辑: 如果以上方法不起作用,请观看此视频 Create confusion matrix for predictions from Keras model .如果您有问题,可能会查看评论。 或者 Make predictions with a Keras CNN Image Classifier

关于python - CNN keras中图像的混淆矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50825936/

相关文章:

python - 如何在 scipy.optimize 中使用 fmin_cg 获得正确的尺寸

python - AttributeError at/'tuple' 对象没有属性 '_meta'

python - 如何使用提交表单将消息保存在数据库中

python - sklearn - 具有多个分数的交叉验证

tensorflow - 为什么我的 Keras 模型在训练时的准确率始终为 0?

python - 与第 3 方 API 交互时,定时处理时间以处理每分钟的请求限制

python - 值错误 : could not convert string to float: med

python - Scikit-Learn:Std.Error,来自 LinearRegression 的 p 值

tensorflow - strip_unused_nodes 的正确参数

python - “RandomForestClassifier”对象没有属性 'layers'