如何为keras模型使用tensorflow自定义损失?
How to use tensorflow custom loss for a keras model?
我正在尝试通过使用中间层的表示来实现损失函数。据我所知,Keras 后端自定义损失函数只接受两个输入参数(y_ture 和 y-pred)。如何使用 @tf.function 定义损失函数并将其用于已通过 Keras 定义的模型?
任何帮助将不胜感激。
这是将附加变量传递给损失函数的简单解决方法。在我们的例子中,我们传递了其中一层 (x1) 的隐藏输出。这个输出可以用来在损失函数中做一些事情(我做了一个虚拟操作)
def mse(y_true, y_pred, hidden):
error = y_true-y_pred
return K.mean(K.square(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.fit(x=[X, y], y=None, epochs=3)
## final fitted model to compute predictions
final_m = Model(inp, out)
我正在尝试通过使用中间层的表示来实现损失函数。据我所知,Keras 后端自定义损失函数只接受两个输入参数(y_ture 和 y-pred)。如何使用 @tf.function 定义损失函数并将其用于已通过 Keras 定义的模型? 任何帮助将不胜感激。
这是将附加变量传递给损失函数的简单解决方法。在我们的例子中,我们传递了其中一层 (x1) 的隐藏输出。这个输出可以用来在损失函数中做一些事情(我做了一个虚拟操作)
def mse(y_true, y_pred, hidden):
error = y_true-y_pred
return K.mean(K.square(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.fit(x=[X, y], y=None, epochs=3)
## final fitted model to compute predictions
final_m = Model(inp, out)