您的位置:首页 > 编程语言 > MATLAB

kullback-leibler distance的计算(matlab)

2016-09-25 08:38 309 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: