【问题标题】:CNN: Splitting Train, Test, and Validation and saving training progressCNN:拆分训练、测试和验证并保存训练进度
【发布时间】:2021-07-08 16:35:34
【问题描述】:

我正在为以下问题编写代码:

  • 我有一个包含训练和测试目录的水果数据集。在这两个目录中,都包含 6 个类(新鲜/烂苹果、新鲜/烂橙、新鲜/烂香蕉)。
  • 我在 MobileNetV2 模型上使用迁移学习

我正在尝试正确设置我的数据拆分,但对如何...

感到困惑
  1. 获取训练、验证和测试拆分设置
  2. 如何检查它们是否确实设置正确(例如没有数据重叠)
  3. 如何通过培训保存进度。 (示例:我运行我的脚本训练了 10 个 epoch。当我再次运行我的脚本 x epoch 时,如何确保训练从我中断的地方继续。)

到目前为止我的代码:

train_batches = ImageDataGenerator(preprocessing_function=mobilenet_v2.preprocess_input, validation_split=0.20).flow_from_directory(
    train_path, target_size=(im_height, im_width), batch_size=batch_size)
test_batches = ImageDataGenerator(preprocessing_function=mobilenet_v2.preprocess_input).flow_from_directory(
    test_path, target_size=(im_height, im_width), batch_size=batch_size)

mobv2 = tf.keras.applications.mobilenet_v2.MobileNetV2()

x = mobv2.layers[-2].output
output_layer = Dense(units=6, activation='softmax')(x)

model = tf.keras.models.Model(inputs=mobv2.input, outputs=output_layer)
for layer in model.layers[:-25]:
    layer.trainable = False

model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=.0001),
              loss='categorical_crossentropy',
              metrics=['accuracy']
              )

这是我的适合,但还没有完成,因为我不确定要包含什么来进行验证和测试......

model.fit(train_batches, steps_per_epoch=4, )

【问题讨论】:

    标签: python tensorflow machine-learning conv-neural-network


    【解决方案1】:

    见下面的代码

    train_batches = ImageDataGenerator(preprocessing_function=mobilenet_v2.preprocess_input, validation_split=0.20).flow_from_directory(
        train_path, target_size=(im_height, im_width), batch_size=batch_size,
         subset='training)
    valid_batches=ImageDataGenerator(preprocessing_function=mobilenet_v2.preprocess_input, validation_split=0.20).flow_from_directory(
        train_path, target_size=(im_height, im_width), batch_size=batch_size,
         subset='validation')
    epochs = 15 # set the number of epochs to run
    history=model.fit(train_batches,  epochs=epochs, verbose=1, 
                    validation_data=valid_batches, verbose=1)'
    

    为了获得更好的结果,我还建议您考虑使用可调整的学习 使用 Keras 回调 ReduceLROnPlateau 进行评分。文档是 here. 设置它来监控验证损失。使用下面的代码:

    rlronp=tf.keras.callbacks.ReduceLROnPlateau( monitor="val_loss", factor=0.5,
                                                patience=10, verbose=1)
    

    我还建议您使用 Keras 回调 EarlyStopping。文档是here. 使用下面的代码

    es=tf.keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, verbose=1,    
                                      restore_best_weights=True)
    

    现在在 model.fit 中包含

    callbacks=[rlronp, es]
    

    【讨论】:

    • 我在 model.fit() 中看到您两次声明了 verbose=1。是否有必要这样做,或者你可以只声明一次吗?@Gerry
    • 不,这只是一个错字,声明一次。
    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 2019-06-13
    • 1970-01-01
    • 2019-05-01
    • 2012-06-04
    • 2021-06-28
    • 2020-05-11
    • 2017-11-01
    相关资源
    最近更新 更多