kullback-leibler distance的计算(matlab)

KL-distance是用来计算两组离散数值的信息量(相对熵)的,一般针对的是离散数据。可以用来做特征筛选。但如果是连续数据,则先要离散化求每个bin内的frequency后再计算KL-distance。
KL-distance的解释:
(1)http://en.wikipedia.org/wiki/Kullback–Leibler_divergence
(2)http://mathworld.wolfram.com/RelativeEntropy.html

那么具体用matlab或者R都可以实现KL-distance的计算。R中有entropy的包,不再介绍。这里重点说明用matlab如何计算KL-distance。
参考资料:
(1)http://www.mathworks.com/matlabcentral/fileexchange/20688-kullback-leibler-divergence
这个帖子里面提供了一个KLDiv.m的代码,但是输入得是已经求好概率或者frequency的数据。
经过测试,可以使用,但是我没有看懂它的计算方法,测试后的结果都是0,放弃。

(2)http://blog.sina.com.cn/s/blog_64e045400101o8ln.html
这个帖子中作者粘贴了一个更加详细的code,尚未测试。

(3)http://stackoverflow.com/questions/13370229/kullback-leibler-kl-distance-between-histograms-matlab
在stackoverflow上有一些相关的帖子,其中这个人问如何由两个histogram数据中(只有bin和每个bin里面的count)计算KL-distance,这个跟我的要求最相近。

因此,决定参考上述(1)(2)(3)中的代码自己写一个从连续值做histogram,然后利用每个bin的frequency求KL-distance的代码,如下所示:

function dist=KLDiv_v2(P,Q)

if size(P,2)~=size(Q,2)
    error('the number of columns in P and Q should be the same');
end

if sum(~isfinite(P(:))) + sum(~isfinite(Q(:)))
   error('the inputs contain non-finite values!') 
end

dist = zeros(size(P));

%# create an index of the "good" data points
goodIdx = P>0 & Q>0; %# bin counts <0 are not good, either

d1 = sum(P(goodIdx) .* log(P(goodIdx) ./Q(goodIdx)));
d2 = sum(Q(goodIdx) .* log(Q(goodIdx) ./P(goodIdx)));

%# overwrite d only where we have actual data
%# the rest remains zero
dist(goodIdx) = d1 + d2;
end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

℡folk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值