tf.math.log() is the inverse of tf.math.exp(), returning the exponent needed to raise e to in order to get the input value. Like NumPy's np.log(), it's only defined for positive real inputs — log(0) produces -inf, and log of a negative number produces nan, since the natural logarithm has no real result for non-positive numbers. It appears constantly in loss functions like cross-entropy, which fundamentally rely on the log of a predicted probability.
1Understanding tf.math.log()
tf.math.log() is the inverse of tf.math.exp(), returning the exponent needed to raise e to in order to get the input value. Like NumPy's np.log(), it's only defined for positive real inputs — log(0) produces -inf, and log of a negative number produces nan, since the natural logarithm has no real result for non-positive numbers. It appears constantly in loss functions like cross-entropy, which fundamentally rely on the log of a predicted probability.
Predicted probabilities from a model can sometimes be exactly 0 or very close to it due to floating-point rounding, and taking tf.math.log() of that produces -inf or a very large negative number — many loss functions add a tiny epsilon value internally specifically to avoid this, which is worth knowing if you're implementing a custom loss involving log() yourself.
import tensorflow as tf
x = tf.constant([1.0, 2.718281828, 7.389056])
print(tf.math.log(x))2Practical Example
Here is a real-world application of tf.math.log() showing how it is used in production TensorFlow code.
import tensorflow as tf
predicted_prob = tf.constant([0.9, 0.5, 0.1])
loss = -tf.math.log(predicted_prob)
print(loss)3Best Practices
Follow these guidelines when working with tf.math.log():
1. Add a small epsilon value before taking the log of a predicted probability in a custom loss function, to avoid -inf from an exact-zero prediction
2. Prefer TensorFlow's built-in loss functions, like categorical crossentropy, over a hand-written log()-based formula, since they already handle this numerical edge case internally
3. Use tf.math.log() together with tf.math.exp() for converting between a value and its log-space representation when numerical stability for very small or very large values matters
Tip: Predicted probabilities from a model can sometimes be exactly 0 or very close to it due to floating-point rounding, and taking tf.math.log() of that produces -inf or a very large negative number — many loss functions add a tiny epsilon value internally specifically to avoid this, which is worth knowing if you're implementing a custom loss involving log() yourself.
import tensorflow as tf
x = tf.constant([1.0, 2.718281828, 7.389056])
print(tf.math.log(x))