Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freifrauvonbleifrei/2a2953b56cf9b61caa0a7aa01a15cae4 to your computer and use it in GitHub Desktop.
Save freifrauvonbleifrei/2a2953b56cf9b61caa0a7aa01a15cae4 to your computer and use it in GitHub Desktop.
Combined tensorflow loss to avoid negative outputs
# custom combined loss cf https://towardsdatascience.com/custom-tensorflow-loss-functions-for-advanced-machine-learning-f13cdd1d188a
loss_1 = tf.losses.huber_loss
def loss_2(labels, predictions):
k = tf.clip_by_value(predictions, -np.inf, 0)
# k = tf.cond(predictions < 0, lambda: 1 * -predictions, lambda: 0)
loss = tf.reduce_sum(-k)
return loss
negativity_loss_rate = 0.1
def loss_combined(labels, predictions):
# can also normalize the losses for stability but not done in this case
norm = 1 #tf.reduce_sum(loss_1 + loss_2)
loss = loss_1(labels, predictions) / norm + negativity_loss_rate * loss_2(labels, predictions) / norm
return loss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment