【问题标题】:How to fit two model alternately in keras如何在keras中交替拟合两个模型
【发布时间】:2019-10-20 01:21:55
【问题描述】:

link1link2不同,现在我有两个损失函数不同的网络,我想在一批中交替拟合这两个模型。

具体来说,如果有一个模型,A。我用下面的伪代码训练它:

model = some_value # initial
for e in 1:epoch
    for b in 1:batch
        model = train(A, model)

上面的程序在keras中只需要一行代码就可以实现:

model.fit(X_train, Y_train,
          batch_size=32, epoch=10)

现在,我有两个模型,A 和 B。我通过以下伪代码训练它们:

model_A = some_value # initial
model_B = some_value # initial
for e in 1:epoch
    for b in 1:batch
        model_A = train(A, model_B) # I using the model_B in the loss function of neural network model_A
        model_B = train(A, model_A) # I using the model_A in the loss function of neural network model_B

如何在keras中实现这个程序?

【问题讨论】:

    标签: python-3.x keras neural-network


    【解决方案1】:
    batchlen = int(len(X_train)/batches)
    for e in range(0,epochs):
        for b in range(0,batches):
            model_A.fit(
              X_train[b*batchlen:(b+1)*batchlen], 
              Y_train[b*batchlen:(b+1)*batchlen], 
              initial_epoch=e, 
              epochs=e+1)
            model_B.fit(X_train[b*batchlen:(b+1)*batchlen], Y_train[b*batchlen:(b+1)*batchlen], initial_epoch=e, epochs=e+1)
    

    更好的方法是使用fit_generatorgenerator 来提供X_train, Y_train。结果应该是这样的

    for e in range(0,epochs):
        model_A.fit_generator(
          your_generator(X_train, Y_train), 
          initial_epoch=e, 
          epochs=e+1, 
          steps_per_epoch=len(X_train)/(batch_size))
        model_B.fit_generator(your_generator(X_train, Y_train), initial_epoch=e, epochs=e+1, steps_per_epoch=len(X_train)/(batch_size))
    

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 2017-05-11
      • 1970-01-01
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2022-12-12
      相关资源
      最近更新 更多