0

I need to implement a custom objective function for Keras where i need an additional tensorflow placeholder for computation. In tensorflow, i have it as following,

pre_cost1 = tf.multiply((self.input_R - self.Decoder) , self.input_mask_R)
cost1 = tf.square(self.l2_norm(pre_cost1))

where input_mask_R is the tensorflow placeholder. input_R and Decoder are the placeholders corresponding to y_true and y_pred for Keras loss function respectively. I have the Keras loss function implemented as,

def custom_objective(y_true, y_pred):

    pre_cost1 = tf.multiply((y_true - y_pred))
    cost1 = tf.square(l2_norm(pre_cost1))

    return cost1

I need to add the additional information for input mask in the loss function for keras. (It needs to be tensorflow placeholder since its a mask for the input which is different for each row of the input data).

3
  • Does input_mask_R change during training ? or is it predefined for each input sample ?
    – Pedia
    Apr 29, 2017 at 7:45
  • its predefined for each sample Apr 29, 2017 at 8:04
  • Could you post the model ? at least a basic one that you are testing with ?
    – Pedia
    Apr 29, 2017 at 13:09

1 Answer 1

1

Use the keras backend:

import keras.backend as K

Most functions for tensors are there, such as:

input_mask_R = K.placeholder(shape=(yourshape))

But maybe, since you want a predefined mask, what you need is:

input_mask_R = K.constant(arrayWithValues, shape=(yourshape))

And you can actually multiply and square also with K.multiply and K.square. That way, if you ever think of changing the backend, everything will be ok. (Also I'm not sure if Keras will handle direct calls to tensorflow functions.....)

See documentation: https://keras.io/backend/

1
  • Yeah from my tests keras handle tf.square as a replacement for K.square
    – parsethis
    May 5, 2017 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.