-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathMutualInfo.m
57 lines (49 loc) · 1.11 KB
/
MutualInfo.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
function MIhat = MutualInfo(L1,L2)
% mutual information
%
% version 2.0 --May/2007
% version 1.0 --November/2003
%
% Written by Deng Cai (dengcai AT gmail.com)
%===========
L1 = L1(:);
L2 = L2(:);
if size(L1) ~= size(L2)
error('size(L1) must == size(L2)');
end
Label = unique(L1);
nClass = length(Label);
Label2 = unique(L2);
nClass2 = length(Label2);
if nClass2 < nClass
% smooth
L1 = [L1; Label];
L2 = [L2; Label];
elseif nClass2 > nClass
% smooth
L1 = [L1; Label2];
L2 = [L2; Label2];
end
G = zeros(nClass);
for i=1:nClass
for j=1:nClass
G(i,j) = sum(L1 == Label(i) & L2 == Label(j));
end
end
sumG = sum(G(:));
P1 = sum(G,2); P1 = P1/sumG;
P2 = sum(G,1); P2 = P2/sumG;
if sum(P1==0) > 0 || sum(P2==0) > 0
% smooth
error('Smooth fail!');
else
H1 = sum(-P1.*log2(P1));
H2 = sum(-P2.*log2(P2));
P12 = G/sumG;
PPP = P12./repmat(P2,nClass,1)./repmat(P1,1,nClass);
PPP(abs(PPP) < 1e-12) = 1e-12; %
MI = sum(P12(:) .* log2(PPP(:)));
MIhat = MI / max(H1,H2);
%%%%%%%%%%%%% why complex ? %%%%%%%%
MIhat = real(MIhat);
end