Skip to content

Instantly share code, notes, and snippets.

@iandewancker
Created August 23, 2018 14:24
Show Gist options
  • Save iandewancker/840748d4f9e2ff80c1dbcd57719d6bd3 to your computer and use it in GitHub Desktop.
Save iandewancker/840748d4f9e2ff80c1dbcd57719d6bd3 to your computer and use it in GitHub Desktop.
custom weighted categorical loss for keras
def custom_cat_crossentropy(y_true, y_pred):
# negate 3x3 sub matrix of income matrix to get cost matrix
# check https://github.com/tensorflow/tensorflow/blob/r1.10/tensorflow/python/keras/backend.py#L3461
cost_m = tf.constant([[ 0.00222222, 0.01111111, 0.00222222],
[ 0.00222222, -0.05888889, 0.00222222],
[ 0.00222222, 1.51111111, 0.00222222]])
y_true = tf.matmul(y_true, cost_m)
return tf.keras.losses.categorical_crossentropy(y_true, y_pred)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment