使用模型中生成的目标数据进行训练

Train with target data generated within the model

如何获得 tf.keras.Model.fit(x, y) 使用的损失函数来比较图中的两个输出而不是一个输出与外部提供的目标数据,y

手册说您可以使用张量作为目标值,这听起来像我想要的,但是您还需要输入是张量。但我的输入是 numpy 数组,我认为我不必更改它。

1 - 简单,最好 - 可能不利于记忆

为什么不直接拿到预期的损失物品呢?

new_y_train = non_trainable_ops_model.predict(original_y_train)   
nn_model.fit(x_train, new_y_train)

如果您的记忆力可以处理,这听起来绝对是最好的方法。更简单的模型,更快的训练。

你甚至可以save/load新数据:

np.save(name, new_y_train)   
new_y_train = np.load(name)

2 - 使模型输出损失并使用虚拟损失进行编译

损失:

def dummy_loss(true, pred):
    return pred

def true_loss(x):
    true, pred = x

    return loss_function(true, pred) #you can probably from keras.losses import loss_function    

型号:

#given
nn_model = create_nn_model()
non_trainable_ops_model = create_nto_model()

nn_input = Input(nn_input_shape)
nto_input = Input(nto_input_shape)

nn_outputs = nn_model(nn_input)
nto_outputs = non_trainable_ops_model(nto_input)

loss = Lambda(true_loss)([nto_outputs, nn_outputs])

training_model = Model([nn_input, nto_input], loss)
training_model.compile(loss = dummy_loss, ...)

training_model.fit([nn_x_train, nto_x_train], np.zeros((len(nn_x_train),)))

3 - 使用 model.add_loss 而不是编译损失

跟上一个答案一样,你可以:

training_model = Model([nn_input, nto_input], nn_outputs)

loss = true_loss([nto_outputs, nn_outputs])
training_model.add_loss(loss)

training_model.compile(loss=None, ...)
training_model.fit([nn_x_train, nto_x_train], None)

4 - 启用急切执行并进行自定义训练循环

https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough