全部版块 我的主页
论坛 计量经济学与统计论坛 五区 计量经济学与统计软件 经管代码库
2175 2
2016-06-22
仅供学习参考哈!!!


最近在学习相对熵,发现论坛里面关于这方面的资料很少,于是就找了一些大家共同学习进步啦






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

来源:http://blog.sina.com.cn/s/blog_4a0824490102v847.html


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

全部回复
2016-6-22 13:28:38
谢谢分享
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

2016-11-2 22:29:38
楼主,stata中能不能做?谢谢!
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群