在自定义keras丢失中使用keras模型

时间:2018-02-10 22:41:20

标签: tensorflow keras predict loss-function

我有一个名为e的常规keras模型,我想在自定义丢失函数中比较y_predy_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)

我收到错误:AttributeError: 'Tensor' object has no attribute 'ndim' 这是因为y_truey_pred都是张量对象,keras.model.predict期望传递numpy.array

知道如何在自定义丢失函数中使用keras.model成功吗?

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

1 个答案:

答案 0 :(得分:4)

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

  

AttributeError:'Tensor'对象没有属性'ndim'

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

  

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

因此,该模型试图获得ndims的{​​{1}}属性,因为它期望数组作为输入。另一方面,Keras框架的自定义丢失函数获取numpy array作为输入。因此,不要在其中编写任何python代码 - 它将永远不会在评估期间执行。只调用此函数来构造计算图。

好的,现在我们发现了该错误信息背后的含义,我们如何在自定义丢失函数中使用Keras模型?简单!我们只需要获得模型的评估图。尝试这样的事情:

tensors

请注意,上述代码未经过测试。但是,无论实现如何,总体思路都将保持不变:您需要构建一个图形,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) y_true将在其中流经最终操作。

相关问题