【问题标题】:Is it logical to loop on model.fit in Keras?在 Keras 中循环 model.fit 是否合乎逻辑?
【发布时间】:2018-10-31 02:29:57
【问题描述】:

为了不耗尽内存,在 Keras 中执行以下操作是否合乎逻辑?

for path in ['xaa', 'xab', 'xac', 'xad']:
    x_train, y_train = prepare_data(path)
    model.fit(x_train, y_train, batch_size=50, epochs=20, shuffle=True)

model.save('model')

【问题讨论】:

    标签: keras large-data batching


    【解决方案1】:

    是的,但如果每次迭代都生成一个批次,则更喜欢model.train_on_batch。这消除了fit 带来的一些开销。

    您也可以尝试创建一个生成器并使用model.fit_generator():

    def dataGenerator(pathes, batch_size):
    
        while True: #generators for keras must be infinite
            for path in pathes:
                x_train, y_train = prepare_data(path)
    
                totalSamps = x_train.shape[0]
                batches = totalSamps // batch_size
    
                if totalSamps % batch_size > 0:
                    batches+=1
    
                for batch in range(batches):
                    section = slice(batch*batch_size,(batch+1)*batch_size)
                    yield (x_train[section], y_train[section])
    

    创建和使用:

    gen = dataGenerator(['xaa', 'xab', 'xac', 'xad'], 50)
    model.fit_generator(gen,
                        steps_per_epoch = expectedTotalNumberOfYieldsForOneEpoch
                        epochs = epochs)
    

    【讨论】:

    • 谢谢,但“我”是什么?
    • LOL...与另一个答案中的错误完全相同:) - 这是batch。
    【解决方案2】:

    我建议在 Github 上查看这个 thread。

    您确实可以考虑使用model.fit(),但这样会使训练更加稳定:

    for epoch in range(20):
        for path in ['xaa', 'xab', 'xac', 'xad']:
            x_train, y_train = prepare_data(path)
            model.fit(x_train, y_train, batch_size=50, epochs=epoch+1, initial_epoch=epoch, shuffle=True)
    

    这样,您在每个 epoch 迭代所有数据一次,而不是在切换之前对部分数据迭代 20 epoch。

    正如线程中所讨论的,另一种解决方案是开发自己的数据生成器并将其与model.fit_generator() 一起使用。

    【讨论】:

    • 非常感谢,但是“i”是什么意思?不应该是“纪元”吗?
    • 您是对的,感谢您发现我的错误。我更正了我的帖子。
    猜你喜欢
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    相关资源
    最近更新 更多