% naive bayes test
function [I, hypo] = nb_ts(fea, lab, mean, var, pri, cn)
% mean var is trained from naivebayes_train
% prior is the prior probability

% return I is the error matrix, I==1 means this data is misclassified

if nargin == 5
    cn = 2;
elseif nargin < 5
    disp('nb_ts(fea, lab, mean, var, pri, [cn])');
    return;
end

vsize = size(fea, 1);
tsnum = size(fea, 2);
hypo = zeros(1, tsnum);

if cn == 2              % 2 classes
    for i = 1:tsnum
        d = fea(:,i) - mean(:,1);
        v1 = sum( -0.5 * d .* d ./ var(:,1) - 0.5 * log(var(:,1)), 1) + log(pri(1));
        d = fea(:,i) - mean(:,2);
        v2 = sum( -0.5 * d .* d ./ var(:,2) - 0.5 * log(var(:,2)), 1) + log(pri(2));
        if (v1 > v2)
            hypo(i) = 1;
        elseif (v1 < v2)
            hypo(i) = -1;
        else
            hypo(i) = sign(rand-0.5);
        end
    end

    I = (hypo ~= lab);
    
else                    % multiple classes
    for i = 1:tsnum
        feai = fea(:,i);
        v = zeros(cn,1);
        for k = 1:cn
            d = feai - mean(:,k);
            v(k) = sum(-0.5*d.*d./var(:,k) - 0.5*log(var(:,k)), 1) + log(pri(k));
        end
        [c,j] = max(v);
        hypo(i) = j;
    end
    
    I = (hypo ~= lab);
end