keras模型上的转移学习总是给出相同的预测

时间:2019-06-27 14:00:49

标签: python tensorflow machine-learning keras deep-learning

我正在尝试使用keras应用程序模块训练图像分类器。当我在验证集上运行预测时,所有图像都被预测为同一类。它并不总是同一个班级,在培训期间会有所不同。我正在使用MobileNetV2和ImageNet的权重,但是我也尝试了其他具有相同结果的模型。

我已经尝试过使用TensorFlow集线器中的模型,如本教程中所述:https://www.tensorflow.org/beta/tutorials/images/hub_with_keras,而且效果很好,所以这不是数据集问题。

我的代码段:

image_size = 224
batch_size = 32
train_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input)
validation_datagen = tf.keras.preprocessing.image.ImageDataGenerator(
    preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input)
train_generator = train_datagen.flow_from_directory(training_data_dir,
                                                    target_size=(image_size, image_size),
                                                    batch_size=batch_size)
validation_generator = train_datagen.flow_from_directory(validation_data_dir,
                                                         target_size=(image_size, image_size),
                                                         batch_size=batch_size)

IMG_SHAPE = (image_size, image_size, 3)
base_model = tf.keras.applications.MobileNetV2(input_shape=IMG_SHAPE,
                                               include_top=False,
                                               weights="imagenet")
base_model.trainable = False

model = tf.keras.Sequential([
    base_model,
    tf.keras.layers.GlobalAveragePooling2D(),
    tf.keras.layers.Dense(train_generator.num_classes, activation='softmax')
])
model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.001),
              loss="categorical_crossentropy",
              metrics=["accuracy"])
model.summary()

batch_stats = CollectBatchStats()
epoch_stats = CollectEpochStats(model, validation_generator)
checkpoint = tf.keras.callbacks.ModelCheckpoint(...)

epochs = 10
steps_per_epoch = train_generator.n // train_generator.batch_size
validation_steps = validation_generator.n // validation_generator.batch_size

history = model.fit_generator(train_generator,
                              epochs=epochs,
                              steps_per_epoch=steps_per_epoch,
                              callbacks=[batch_stats, epoch_stats, checkpoint],
                              workers=4,
                              validation_data=validation_generator,
                              validation_steps=validation_steps)

1 个答案:

答案 0 :(得分:0)

问题已解决:在我的代码中,模型编译后有以下几行:

connect.example.com:/oauthcallback

删除它们后,一切正常。