从这里窃取示例代码:
def custom_loss_wrapper(input_tensor): def custom_loss(y_true, y_pred): return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor) return custom_lossinput_tensor = Input(shape=(10,))hidden = Dense(100, activation='relu')(input_tensor)out = Dense(1, activation='sigmoid')(hidden)model = Model(input_tensor, out)model.compile(loss=custom_loss_wrapper(input_tensor), optimizer='adam')X = np.random.rand(1000, 10)y = np.random.rand(1000, 1)model.train_on_batch(X, y)
在最近的Tensorflow版本中,这不再有效。我看到的主要解决方案是禁用渴望执行,但这会破坏我正在做的其他事情。
如何在保持渴望模式的同时维持这种功能?也就是说,将输入传递给损失函数?我能想到的最好方法是修改网络,将输入连接到输出,然后在损失中拆分它。不过这非常笨拙。
回答:
你可以使用add_loss
将外部层传递给你的损失,在你的例子中就是输入张量。
这是一个例子:
def CustomLoss(y_true, y_pred, input_tensor): return K.binary_crossentropy(y_true, y_pred) + K.mean(input_tensor)X = np.random.uniform(0,1, (1000,10))y = np.random.randint(0,2, (1000,1))inp = Input(shape=(10,))hidden = Dense(100, activation='relu')(inp)out = Dense(1, activation='sigmoid')(hidden)target = Input((1,))model = Model([inp,target], out)model.add_loss( CustomLoss( target, out, inp ) )model.compile(loss=None, optimizer='adam')model.fit(x=[X,y], y=None, epochs=3)
在推理模式下使用模型(从输入中移除目标)
final_model = Model(model.input[0], model.output)final_model.predict(X)