我建立了一个基于VGG预训练模型的CNN。我对最后一个转换块(#5)和我添加的完全连接层进行了微调。我的分类问题有4个类,我的最后一个激活层是'softmax',我使用'sparse_categorical_crossentropy'作为我的损失函数。当我创建我的train / valid生成器时,我正在使用class_mode('sparse')。因此,我适合我的模型,在2个时期后,我的验证数据集的准确率达到92%。我遇到的问题是,当我检查predict_generator以查看我的验证集上的预测时,准确度大约为73真预测/(73 + 161错误预测)= 0.31%,但是model.evaluate_generator(validation_generator)有91%准确性。
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
path_data_train,
target_size=(img_width, img_height),
batch_size=16,
class_mode="sparse")
validation_generator = test_datagen.flow_from_directory(
path_data_valid,
target_size=(img_width, img_height),
batch_size=16,
class_mode="sparse")
nb_train_samples = 1874
nb_validation_samples = 234
epochs = 10
batch_size = 16
history = model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_validation_samples // batch_size,
callbacks = [checkpointer])
Epoch 1/10
117/117 [==============================] - 42s 356ms/step - loss: 0.0850 - acc: 0.9690 - val_loss: 0.4173 - val_acc: 0.9062
Epoch 2/10
117/117 [==============================] - 42s 360ms/step - loss: 0.0690 - acc: 0.9765 - val_loss: 0.4423 - val_acc: 0.894
print (model.metrics_names)
model.evaluate_generator(validation_generator)
['loss', 'acc']
[0.39189313988909763, 0.9059829049640231]
preds = model.predict_generator(validation_generator)
任何帮助表示赞赏。
如果以后有人遇到同样的问题,我会发布答案。您需要在验证生成器中设置Shuffle = False。
validation_generator = test_datagen.flow_from_directory(
path_data_valid,
target_size=(img_width, img_height),
batch_size=16,
class_mode="sparse", shuffle = False)