最近在学习卷积神经网络,其中遇到了信息熵和交叉熵,对此理解的一知半解,现记录一下信息熵、相对熵、交叉熵公式及tensorflow代码,供以后参考。
假设概率分布中,真实分布: 假设分布:
- 信息量公式:
- 信息熵公式:
- 相对熵公式:
- 交叉熵公式:
借助于tensorflow框架,根据以上几个公式进行试验:
#coding:utf-8
"""
Created by cheng star at 2018/8/19 12:04
@email : [email protected]
"""
import tensorflow as tf
# 真实分布概率
p = [i/10 for i in range(1 , 10)]
# 假设分布概率
q = [1 - prob for prob in p]
print(p)
print(q)
# x = tf.constant(value=p , dtype=tf.float32)
with tf.Session() as sess :
sess.run(tf.global_variables_initializer())
# 信息量
case_1 = -tf.log(p)
print(sess.run(case_1))
# 信息熵
case_2 = -tf.reduce_sum(p * tf.log(p))
print(sess.run(case_2))
# 相对熵
case_3 = tf.reduce_sum(p * tf.log(p) - p * tf.log(q))
print(sess.run(case_3))
# 交叉熵
case_4 = -tf.reduce_sum(p * tf.log(q))
print(sess.run(case_4))
代码输入、输出结果如下:
输入:
p = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
q = [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.30000000000000004, 0.19999999999999996, 0.09999999999999998]
输出:
信息量:[ 2.30258512 1.60943794 1.20397282 0.9162907 0.69314718 0.51082557 0.35667497 0.22314353 0.10536055]
信息熵:2.45594
相对熵:3.00957
交叉熵:5.4655