function nmi = compute_nmi(label, result);
% compute Normalized Mutual Information (NMI) for cluster analysis
% He Zhang, July 2011
% Ref: A. Strehl et al.: Cluster Ensembles: A Knowledge Reuse Framework 
% for Combining Multiple Partitions, JMLR 2002

label = label(:); 
result = result(:);
n = length(label);

cl = unique(label); 
cr = unique(result);

nl = length(cl);
nr = length(cr);

ncl = []; ncr = [];
ncl = (repmat(label, 1, nl)==repmat(cl', n, 1));
ncr = (repmat(result, 1, nr)==repmat(cr', n, 1));
ncl = sum(ncl); ncr = sum(ncr);

nclr = [];
for i = 1:nl
    for j = 1:nr
        nclr(i, j) = length(find(label==cl(i)&result==cr(j)));
    end
end

nom = []; 
for i = 1:nl
    for j = 1:nr
        nom(i, j) = nclr(i, j)*log((n*nclr(i, j))/(ncl(i)*ncr(j))+eps);
    end
end
% if I(X, Y) = 0, return nmi = 0;
if (sum(nom(:))<1e-5)
    nmi = 0;
    return;
end

denom = [];
denom_1 = -ncl.*log((ncl/n)+eps);
denom_2 = -ncr.*log((ncr/n)+eps);

nmi = sum(nom(:))/sqrt(sum(denom_1(:))*sum(denom_2(:))+eps);










