如何为keras模型使用Tensorflow自定义损失? [英] How to use tensorflow custom loss for a keras model?

查看:163
本文介绍了如何为keras模型使用Tensorflow自定义损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to implement a loss function by using the representations of the intermediate layers. As far as I know, the Keras backend custom loss function only accepts two input arguments(y_ture, and y-pred). How can I define a loss function with @tf.function and use it for a model that has been defined via Keras? any help would be appreciated.

推荐答案

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

this a simple workaround to pass additional variables to your loss function. in our case, we pass the hidden output of one of our layers (x1). this output can be used to do something inside the loss function (I do a dummy operation)

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)

这篇关于如何为keras模型使用Tensorflow自定义损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆