Как передать вывод скрытого слоя в пользовательскую функцию потерь - PullRequest
0 голосов
/ 01 апреля 2020

Я хочу объединить двоичную модель классификации и прогнозирования. Другими словами, сначала я хочу предсказать многоэтапные шаги из заданного временного окна, а затем использовать двоичную классификацию, чтобы решить, является ли прогнозируемый результат приемлемым или нет. Код для определения модели и функции потерь:

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 loss для второго выхода. Тем не менее, для первого результата (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>]

Я не знаю, в чем проблема в функции потерь?

Приветствия,

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...