如何将隐藏层的输出传递给自定义损失函数

时间:2020-04-01 02:15:49

标签: keras prediction loss

我想结合一个二进制分类和预测模型,换句话说,我想从给定的时间窗口预测多步,然后使用二进制分类来确定预测的输出是否可接受。定义模型和损失函数的代码如下:

n_output = n_steps_out * n_features
input_x = Input(shape= (n_steps, n_features))
input_y = Input(shape =(1,n_output))

# Model to predict future
pred = forecast_branch(input_x)

# layer to calculate l1 distance between pred and target
L1_distance = Lambda(lambda tensors: K.abs(tensors[0] - tensors[1]))([input_y, pred])
dist = Flatten(name="dist")(L1_distance)

# estimate the final label
cp = Dense(1, name="cp_dense", activation='sigmoid')(dist)

CPNET = Model(inputs=[input_x, input_y], outputs =[cp, dist], name="CPNET")
model.compile(loss=[custom_loss(CPNET.get_layer(name="dist")),'mse'], optimizer='adam', metrics=['accuracy'])

为了最小化预测误差,我为第二个输出调用了mse损失函数。但是对于第一个输出(cp),我想根据预测值估算值。因此,我将“ dist”层传递给了我的custom_loss函数。这是custom_loss:

# Define custom loss
def contrastive_loss(mlayer):

def loss(y_true, y_pred):    
    margin = 1
    return  K.mean(y_pred * K.square(mlayer.output) +
                  (1 - y_pred) * K.square(K.maximum(margin - mlayer.output, 0)))
return loss

当我拟合模型时,出现以下错误:

TypeError                                 Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
 59     tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name,
---> 60                                         inputs, attrs, num_outputs)
 61   except core._NotOkStatusException as e:

TypeError: An op outside of the function building code is being passed a "Graph" tensor. It is possible to have Graph tensors leak out of the function building context by including a tf.init_scope in your function building code.
For example, the following function will fail:
@tf.function
def has_init_scope():
my_constant = tf.constant(1.)
with tf.init_scope():
  added = my_constant * 2
The graph tensor has name: dist_4/Identity:0

During handling of the above exception, another exception occurred:

_SymbolicException                        Traceback (most recent call last) 9 frames /usr/local/lib/python3.6/dist-packages/tensorflow/python/eager/execute.py in quick_execute(op_name, num_outputs, inputs, attrs, ctx, name)
 72       raise core._SymbolicException(
 73           "Inputs to eager execution function cannot be Keras symbolic "
 ---> 74           "tensors, but found {}".format(keras_symbolic_tensors))
 75     raise e
 76   # pylint: enable=protected-access

 _SymbolicException: Inputs to eager execution function cannot be Keras     symbolic tensors, but found [<tf.Tensor 'dist_4/Identity:0' shape=(None, 9) dtype=float32>]

我不知道损失函数有什么问题吗?

干杯

0 个答案:

没有答案