在定制的keras损失中使用keras模型

Ale*_*tin 2 predict keras tensorflow loss-function

我有一个名为定期keras模型e,我想它的输出比较两者y_pred,并y_true在我的自定义损失函数。

from keras import backend as K
def custom_loss(y_true, y_pred):
    return K.mean(K.square(e.predict(y_pred)-e.predict(y_true)), axis=-1)
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:AttributeError: 'Tensor' object has no attribute 'ndim' 这是因为y_true和y_pred都是张量对象,keras.model.predict希望传递给numpy.array。

知道如何keras.model在自定义损失函数中成功使用我的方法吗?

如果需要,我愿意获取指定层的输出,也可以将其转换keras.model为tf.estimator对象(或其他任何对象)。

Fal*_*nUA 5

首先,让我们尝试了解您收到的错误消息:

AttributeError:“ Tensor”对象没有属性“ ndim”

让我们看一下Keras文档,找到Keras模型的预测方法。我们可以看到函数参数的描述:

x:输入数据,作为一个Numpy数组。

因此,该模型试图获取a的ndims属性numpy array,因为它希望将数组作为输入。另一方面,Keras框架的自定义损失函数将tensors作为输入。因此,请勿在其中编写任何python代码-永远不会在评估过程中执行该代码。只是调用此函数来构造计算图。


好的,现在我们找到了该错误消息的含义,那么如何在自定义损失函数中使用Keras模型?简单!我们只需要获取模型的评估图即可。尝试这样的事情:

def custom_loss(y_true, y_pred):
    # Your model exists in global scope
    global e

    # Get the layers of your model
    layers = [l for l in e.layers]

    # Construct a graph to evaluate your other model on y_pred
    eval_pred = y_pred
    for i in range(len(layers)):
        eval_pred = layers[i](eval_pred)

    # Construct a graph to evaluate your other model on y_true
    eval_true = y_true
    for i in range(len(layers)):
        eval_true = layers[i](eval_true)

    # Now do what you wanted to do with outputs.
    # Note that we are not returning the values, but a tensor.
    return K.mean(K.square(eval_pred - eval_true), axis=-1)
Run Code Online (Sandbox Code Playgroud)

请注意,上面的代码未经测试。但是,无论采用何种实现方式,总体思路都将保持不变:您需要构造一个图,其中y_true和y_pred将流经它并到达最终操作。