现在与link1和link2不同,我有两个分别具有不同损失函数的网络,并且我希望将这两个模型交替地放入一批中。
具体来说,如果有一个模型,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中实现此过程?
答案 0 :(得分:0)
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_generator
与generator一起使用来填充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))