Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions edward2/tensorflow/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,12 +171,13 @@ def logit_kl_divergence(logits_1, logits_2):
return tf.reduce_mean(vals)


def kl_divergence(p, q):
def kl_divergence(p, q, clip=True):
"""Generalized KL divergence [1] for unnormalized distributions.

Args:
p: tf.Tensor.
q: tf.Tensor
q: tf.Tensor.
clip: bool.

Returns:
tf.Tensor of the Kullback-Leibler divergences per example.
Expand All @@ -187,7 +188,10 @@ def kl_divergence(p, q):
matrix factorization." Advances in neural information processing systems.
2001.
"""
return tf.reduce_sum(p * tf.math.log(p / q) - p + q, axis=-1)
if clip:
p = tf.clip_by_value(p, tf.keras.backend.epsilon(), 1)
q = tf.clip_by_value(q, tf.keras.backend.epsilon(), 1)
return tf.reduce_sum(p * tf.math.log(p / q), axis=-1)


def lp_distance(x, y, p=1):
Expand Down Expand Up @@ -229,7 +233,7 @@ def average_pairwise_diversity(probs, num_models, error=None):
# TODO(ghassen): we could also return max and min pairwise metrics.
average_disagreement = tf.reduce_mean(tf.stack(pairwise_disagreement))
if error is not None:
average_disagreement /= (error + tf.keras.backend.epsilon())
average_disagreement /= (1 - error + tf.keras.backend.epsilon())
average_kl_divergence = tf.reduce_mean(tf.stack(pairwise_kl_divergence))
average_cosine_distance = tf.reduce_mean(tf.stack(pairwise_cosine_distance))

Expand Down