如何将tensorflow自定义损失用于keras模型?

时间:2020-06-18 16:13:06

标签: keras tensorflow2.0 loss-function

我正在尝试通过使用中间层的表示来实现损失函数。据我所知,Keras后端自定义损失函数仅接受两个输入参数(y_ture和y-pred)。如何使用@ tf.function定义损失函数并将其用于通过Keras定义的模型? 任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是一个简单的解决方法,可以将其他变量传递给损失函数。在本例中,我们传递了一层(x1)的隐藏输出。此输出可用于在损失函数内做某事(我做一个虚拟操作)

def mse(y_true, y_pred, hidden):

    error = y_true-y_pred
    return K.mean(K.sqrt(error)) + K.mean(hidden)


X = np.random.uniform(0,1, (1000,10))
y = np.random.uniform(0,1, 1000)

inp = Input((10,))
true = Input((1,))
x1 = Dense(32, activation='relu')(inp)
x2 = Dense(16, activation='relu')(x1)
out = Dense(1)(x2)

m = Model([inp,true], out)
m.add_loss( mse( true, out, x1 ) )
m.compile(loss=None, optimizer='adam')
m.summary()

history = m.fit([X, y], y, epochs=10)

## final fitted model to compute predictions
final_m = Model(inp, out)