Skip to content

Instantly share code, notes, and snippets.

@applenob
Last active April 24, 2018 23:49
Show Gist options
  • Save applenob/4d35253764f1d6f16e2fe95a09ebd385 to your computer and use it in GitHub Desktop.
Save applenob/4d35253764f1d6f16e2fe95a09ebd385 to your computer and use it in GitHub Desktop.
Tensorflow Masked Softmax with mask after the exp operation.
import tensorflow as tf
def masked_softmax(logits, mask, axis):
"""softmax with mask after the exp operation"""
e_logits = tf.exp(logits)
masked_e = tf.multiply(e_logits, mask)
sum_masked_e = tf.reduce_sum(masked_e, axis, keep_dims=True)
# be careful when the sum is 0
ones = tf.ones_like(sum_masked_e)
sum_masked_e_safe = tf.where(tf.equal(sum_masked_e, 0), ones, sum_masked_e)
return masked_e / sum_masked_e_safe
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment