直方图之间的Kullback-Leibler(KL)距离-matlab

直方图之间的Kullback-Leibler(KL)距离-matlab,matlab,image-processing,Matlab,Image Processing,我的问题是,无论何时h1(i)或h2(i)=0,我都会得到预期的inf。然而,在KL距离中,每当它们h1或h2==0时,我假设返回0。我如何在不使用循环的情况下返回0?为避免在任何计数为0时出现问题,我建议您创建一个标记“良好”数据点的索引: function [ d ] = hcompare_KL( h1,h2 ) %This routine evaluates the Kullback-Leibler (KL) distance between histograms. %

我的问题是,无论何时h1(i)或h2(i)=0,我都会得到预期的inf。然而,在KL距离中,每当它们h1或h2==0时,我假设返回0。我如何在不使用循环的情况下返回0?

为避免在任何计数为0时出现问题,我建议您创建一个标记“良好”数据点的索引:

function [ d ] = hcompare_KL( h1,h2 )
%This routine evaluates the Kullback-Leibler (KL) distance between histograms. 
%             Input:      h1, h2 - histograms
%             Output:    d – the distance between the histograms.
%             Method:    KL is defined as: 
%             Note, KL is not symmetric, so compute both sides.
%             Take care not to divide by zero or log zero: disregard entries of the sum      for which with H2(i) == 0.

temp = sum(h1 .* log(h1 ./ h2));
temp( isinf(temp) ) = 0; % this resloves where h1(i) == 0 
d1 = sum(temp);

temp = sum(h2 .* log(h2 ./ h1)); % other direction of compare since it's not symetric
temp( isinf(temp) ) = 0;
d2 = sum(temp);

d = d1 + d2;

end
%#您可能需要进行一些输入测试,例如h1和h2是否正确
%#同样大小
%#预先分配输出
d=零(尺寸(h1));
%#创建“良好”数据点的索引

goodIdx=h1>0&h2>0;%#bin counts我发现您的实现中存在一些错误。请按log2编辑日志

尝试使用

%# you may want to do some input testing, such as whether h1 and h2 are
%# of the same size

%# preassign the output
d = zeros(size(h1));

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

d1 = sum(h1(goodIdx) .* log(h1(goodIdx) . /h2(goodIdx)));
d2 = sum(h2(goodIdx) .* log(h2(goodIdx) . /h1(goodIdx)));

%# overwrite d only where we have actual data
%# the rest remains zero
d(goodIdx) = d1 + d2;
请注意,KL(h1,h2)与KL(h2,h1)不同。你的例子是KL(h1,h2),对吗? 我认为你的实施是错误的。它不是h1和h2之间的距离。定义了h1和h2之间的KL距离

 d=sum(h1.*log2(h1+eps)-h1.*log2(h2+eps))
因此,必须正确实施

KL(h1,h2)=sum(h1.log(h1/h2))=sum(h1.logh1-h2.logh2). 


如果你不提出更好的问题,就很难帮助你。如果我不知道程序首先应该做什么,我也找不到你的错误。请提供一个输入示例,告诉我们您期望的输出以及出现的问题。函数是否抛出错误?函数是否不返回您想要的内容?我对你的问题投了反对票,但如果问题有所改善,我很高兴修改我的投票。嗨@Jonas谢谢你每天的回答,你可以看到我在学习。稍后让我详细说明我的问题,对不起,谢谢you@jonas我已经编辑了我的问题,你能看一下吗,假设我们有h1=[0:9]和h2=[1:10]作为输入,当我有0作为输入时,我会得到一个错误。。log(0)现在这是一个更清楚的问题。希望我的回答有帮助。
 d=sum(h1.*log2(h1+eps)-h1.*log2(h2+eps)) %KL(h1,h2)
 d=sum(h2.*log2(h2+eps)-h2.*log2(h1+eps)) %KL(h2,h1)