Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in Machine Learning by (4.2k points)

Hi, I have been trying to make a custom loss function in Keras for dice_error_coefficient. It has its implementations in TensorBoard and I tried using the same function in Keras with TensorFlow but it keeps returning a NoneType when used model.train_on_batch or model.fit whereas it gives proper values when used in metrics in the model. Can please someone help me out with what should I do? I have tried following libraries like Keras-FCN by ahundt where he has used custom loss functions but none of it seems to work. The target and output in the code are y_true and y_pred respectively as used in the losses.py file in Keras.

def dice_hard_coe(target, output, threshold=0.5, axis=[1,2], smooth=1e-5):
    """References
    -----------
    - `Wiki-Dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_
    """

    output = tf.cast(output > threshold, dtype=tf.float32)
    target = tf.cast(target > threshold, dtype=tf.float32)
    inse = tf.reduce_sum(tf.multiply(output, target), axis=axis)
    l = tf.reduce_sum(output, axis=axis)
    r = tf.reduce_sum(target, axis=axis)
    hard_dice = (2. * inse + smooth) / (l + r + smooth)
    hard_dice = tf.reduce_mean(hard_dice)
    return hard_dice

1 Answer

+2 votes
by (6.8k points)
edited by

Yes, it possible to build the custom loss function in keras by adding new layers to model and compile them with various loss value based on datasets (loss = Binary_crossentropy if datasets have two target values such as yes or no ). Create a Sequential model by passing a list of layer instances to the constructor:

from keras.models import Sequential

from keras.layers import Dense, Activation

model = Sequential([Dense(32, input_dim=784), Activation('relu'), Dense(10),  Activation('softmax'),])

model = Sequential()

//You can also simply add layers via the .add() method:

model.add(Dense(32, input_dim=784))

model.add(Activation('relu'))

//Finally, you can use it as follows in Keras compile.

model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])

If You want to learn Machine learning, visit this machine learning interview questions.

Browse Categories

...