问题描述
我需要最小化 tensorflow 中的 KL 损失.
I need to minimize KL loss in tensorflow.
我试过这个函数tf.contrib.distributions.kl(dist_a, dist_b, allow_nan=False, name=None)
,但我失败了.
I tried this function tf.contrib.distributions.kl(dist_a, dist_b, allow_nan=False, name=None)
, but I failed.
我尝试手动实现:
def kl_divergence(p,q):
return p* tf.log(p/q)+(1-p)*tf.log((1-p)/(1-q))
正确吗?
推荐答案
你有的是交叉熵,KL散度应该是这样的:
What you have there is the cross entropy, KL divergence should be something like:
def kl_divergence(p, q):
return tf.reduce_sum(p * tf.log(p/q))
这里假设 p 和 q 都是浮点数的一维张量,形状相同,并且对于每个张量,它们的值总和为 1.
This assumes that p and q are both 1-D tensors of float, of the same shape and for each, their values sum to 1.
如果 p 和 q 是符合上述约束的大小相同的一维张量小批量,它也应该有效.
It should also work if p and q are equally sized mini-batches of 1-D tensors that obey the above constraints.
这篇关于如何在 TensorFlow 中实现 Kullback-Leibler 损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!