我可以在keras中多次调用model.fit吗?

2024-04-26 12:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很长的数据集,我需要分块训练它。我已经读到可以多次调用model.fit,但最好使用model.train\u on\u批处理。这是真的吗?为什么?


Tags: 数据modelontrain分块fit
1条回答
网友
1楼 · 发布于 2024-04-26 12:48:42

而不是使用model.fit multiple。您可以在tensorflow中使用make_csv_dataset函数,并将数据集传递给fit命令。 假设您的数据为csv格式。此功能的优点是,它在需要时加载数据,而不是加载主内存中的所有内容

tf.data.experimental.make_csv_dataset(
    file_pattern, 
    batch_size,
    label_name=None, 
    select_columns=None, 
    shuffle=True,
)

这里的文件模式是单个字符串,即文件名或字符串模式,如果您想加载多个文件。见Documentation

若你们有图像数据集,你们可以从目录中使用叫做flow的东西。这也以类似的方式起作用。它只加载处理所需的图像

# this is preprocessing step where you define preprocessing on images.
train_datagen = ImageDataGenerator(
        rescale=1./255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)

# this is where you create iterator.
train_generator = train_datagen.flow_from_directory(
        'data/train',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
        'data/validation',
        target_size=(150, 150),
        batch_size=32,
        class_mode='binary')
model.fit(
        train_generator,
        steps_per_epoch=2000,
        epochs=50,
        validation_data=validation_generator,
        validation_steps=800)

Documentation

相关问题 更多 >