Today a very simple thing: create your own loss and metric functions in Keras (Tensorflow backend). The most important thing is to remember to perform actions on tensors. It’s worth to keep the parameter names unchanged.


import tensorflow as tf
import tensorflow.keras.backend as K

Create own loss and metric

# we measure mean_squared_error and increase it 4 times
def loss(y_true, y_pred):
    mse = tf.keras.losses.mean_squared_error(y_true=y_true, y_pred=y_pred)
    return mse * 4

# we are looking for the maximum and we count the ratio
def metric(y_true, y_pred):
    max_true = K.max(K.max(y_true, axis=0), axis=0)
    max_pred = K.max(K.max(y_pred, axis=0), axis=0)
    return max_pred/max_true   

Use own functions

# define the model earlier
model.compile(optimizer='adam', loss=loss, metrics=[metric])