gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:42:52 27 4
gpt4 key购买 nike

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(i) 或 h2(i) == 0 时,我都会得到符合预期的 inf。然而,在 KL 距离中,我假设只要它们 h1 或 h2 ==0 就返回 0 我怎么能在不使用循环的情况下做到这一点?

最佳答案

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

%# 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;

关于matlab - 直方图之间的 Kullback-Leibler (KL) 距离 - matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13370229/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com