在 for 循环中拟合模型是否等同于使用 epochs>1?

数据挖掘 Python 喀拉斯 张量流 时代
2022-03-07 13:36:39

我正在使用 tensorflow 训练网络来执行图像分割任务,并且我对 epoch 之间的行为有疑问model.fit,特别是:

model.fit用 512 个 epoch 调用和调用model.fit512 次有什么区别吗?

这是我的代码的简化版本,以防万一。首先,一些设置:

# Create image generators for dataset augmentation
imgGen = ImageDataGenerator(**data_augmentation_parameters)
maskGen = ImageDataGenerator(**data_augmentation_parameters)
seed = random.randint(0, 1000000000)
imgIterator = imgGen.flow(img, seed=seed, shuffle=False, batch_size=batch_size)
maskIterator = maskGen.flow(mask, seed=seed, shuffle=False, batch_size=batch_size)

# Load network structure from model.py file
network = unet(net_scale = 1)

# Calculate # of iterations
steps_per_epoch = int(num_samples / batch_size)

迭代拟合的两种方法:

拟合方法#1:

network.fit(
    ((imgBatch, maskBatch) for imgBatch, maskBatch in zip(imgIterator, maskIterator)),
    steps_per_epoch=steps_per_epoch,
    epochs=512,
)

拟合方法#2:

for epoch in range(512):
    network.fit(
        ((imgBatch, maskBatch) for imgBatch, maskBatch in zip(imgIterator, maskIterator)),
        steps_per_epoch=steps_per_epoch,
        epochs=1,
    )

我认为这个问题和我的一样,但我不明白一个答案如何适用于这个问题——我只是想知道指定一个 epoch number > 1 和model.fit在 for 循环中运行之间是否存在一些内部差异。

谢谢!

1个回答

根据Keras 的 github 存储库中的这个问题,是的,您应该能够以您想要的方式在循环中增量训练您的模型。话虽如此,您可能应该在这两种方式上运行测试,看看它是否会产生不同的结果。