如何在keras中测试自定义损失函数?

Sör*_*ren 5 python testing keras tensorflow loss-function

我正在训练带有两个输出的CovNet。我的训练样本如下所示:

[0, value_a1], [0, value_a2], ...
Run Code Online (Sandbox Code Playgroud)

[value_b1, 0], [value_b2, 0], ....
Run Code Online (Sandbox Code Playgroud)

我想生成自己的损失函数和包含的掩码对mask_value = 0。我具有此功能,尽管不确定是否确实可以实现我想要的功能。所以,我想写一些测试。

from tensorflow.python.keras import backend as K
from tensorflow.python.keras import losses

def masked_loss_function(y_true, y_pred, mask_value=0):
    '''
    This model has two target values which are independent of each other.
    We mask the output so that only the value that is used for training 
    contributes to the loss.
        mask_value : is the value that is not used for training
    '''
    mask = K.cast(K.not_equal(y_true, mask_value), K.floatx())
    return losses.mean_squared_error(y_true * mask, y_pred * mask)
Run Code Online (Sandbox Code Playgroud)

但是,我不知道如何用keras测试此功能?通常,这将传递给model.compile()。类似于以下内容:

x = [1, 0]
y = [1, 1]
assert masked_loss_function(x, y, 0) == 0
Run Code Online (Sandbox Code Playgroud)

tod*_*day 8

我认为实现这一目标的一种方法是使用 Keras 后端功能。这里我们定义了一个函数,它以两个张量作为输入并返回一个张量作为输出:

from keras import Model
from keras import layers

x = layers.Input(shape=(None,))
y = layers.Input(shape=(None,))
loss_func = K.function([x, y], [masked_loss_function(x, y, 0)])
Run Code Online (Sandbox Code Playgroud)

现在我们可以loss_func用来运行我们定义的计算图:

assert loss_func([[[1,0]], [[1,1]]]) == [[0]]
Run Code Online (Sandbox Code Playgroud)

请注意,keras 后端函数,即function,期望输入和输出参数是张量数组。此外,xandy接受一批张量,即一个形状未定义的张量数组。