Keras Model在训练和验证中获得很高的准确性,然后弄乱了Confusion指标

时间:2019-10-01 08:18:57

标签: python tensorflow keras

因此,我有一个二元分类模型,该模型在训练验证和测试阶段获得了非常好的分数。

validation_generator.reset # reset the validation gen for testing
loss: 0.0725 - accuracy: 0.9750 - val_loss: 0.1703 - val_accuracy: 0.9328
scores = model.evaluate_generator(validation_generator, workers=1, use_multiprocessing=False, verbose=1)
print(scores)
[0.023366881534457207, 0.9353214502334595]

好吧,那看起来对我来说真的很好,对吗? 现在,当我尝试混淆指标时,所有这些都归为一类,这是完全错误的。

Confusion Matrix
[[1045    0]
[1537    0]]

这是CM代码:

validation_generator.reset
Y_pred = model.predict_generator(validation_generator, validation_generator.samples // BATCH_SIZE+1)
y_pred = np.argmax(Y_pred, axis=1)
print(confusion_matrix(validation_generator.classes, y_pred))
target_names = ['male', 'female']
print(classification_report(validation_generator.classes, y_pred, target_names=target_names))

我不认为那不应该。可能与发电机有关,但对我来说似乎正确。

BATCH_SIZE = 32
train_datagen = ImageDataGenerator(preprocessing_function=preprocess_input,
                               horizontal_flip=True,                            
                               validation_split=0.2) # set validation split

train_generator = train_datagen.flow_from_directory(
    DATA_PATH,
    target_size=(224, 224),
    shuffle=True,
    batch_size=BATCH_SIZE,
    class_mode='binary',
    subset='training') # set as training data

validation_generator = train_datagen.flow_from_directory(
    DATA_PATH, # same directory as training data
    target_size=(224, 224),
    batch_size=BATCH_SIZE,
    shuffle=False,
    class_mode='binary',
    subset='validation') # set as validation data

我应该将验证批大小设置为1吗?

如果有帮助,这里是模型声明。

history = model.fit_generator(
    train_generator,
    steps_per_epoch = train_generator.samples // BATCH_SIZE,
    validation_data = validation_generator, 
    validation_steps = validation_generator.samples // BATCH_SIZE,
    epochs = EPOCHS,
    verbose=1, 
    callbacks=callbacks_list)

此问题的更新和修复:

将此添加到代码中

y_pred[y_pred <= 0.5] = 0.
y_pred[y_pred > 0.5] = 1.
#Old code
#y_pred = np.argmax(Y_pred, axis=1) # This does not work for this

1 个答案:

答案 0 :(得分:1)

据我了解,您正在执行 binary 分类,并且在您的代码中看到您正在使用np.argmax(Y_pred, axis=1)。我认为argmax应该与多类分类一起使用。

对于解决方案,您应该尝试类似y_pred = [y[0] >= 0.5 for y in y_pred]

请注意,我不确定此代码是否完全有效,但我确定需要np.argmax()进行替换。