cnn:分割训练、测试和验证并保存训练进度

r1zhe5dt  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(337)

我正在为以下问题编写代码:
我有一个包含训练和测试目录的水果数据集。在这两个目录中,包含6类(新鲜/腐烂的苹果、新鲜/腐烂的橙子、新鲜/腐烂的香蕉)。
我正在MobileNet V2模型上使用迁移学习
我正试图让我的数据分割设置正确,但我对如何。。。
获得培训、验证和测试拆分设置
如何检查它们是否确实正确设置(例如,没有数据重叠)
如何通过培训保存进度(我运行的脚本可以训练10个时代。当我再次运行x时代的脚本时,如何确保培训从我停止的地方继续进行。)
到目前为止,我的代码是:

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']
              )

这是我的fit,但还没有完成,因为我不确定验证和测试要包括什么。。。。

model.fit(train_batches, steps_per_epoch=4, )
0ejtzxu1

0ejtzxu11#

请参阅下面的代码

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)'

为了获得更好的结果,我还建议您考虑使用Kelas回调ReleloLoad的可调整学习速率。文档在这里。将其设置为监视验证丢失。使用以下代码:

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

我还建议您使用keras回调Earlystoping。文档在这里。使用下面的代码

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

现在在model.fit中包括

callbacks=[rlronp, es]

相关问题