如何在 TensorFlow 中实现 Kullback-Leibler 损失? [英] How can I implement the Kullback-Leibler loss in TensorFlow?

查看:108
本文介绍了如何在 TensorFlow 中实现 Kullback-Leibler 损失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要最小化 tensorflow 中的 KL 损失.

I need to minimize KL loss in tensorflow.

我试过这个函数tf.contrib.distributions.kl(di​​st_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 损失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆