[spmatrix, tokenlist, category] = readMatrix('MATRIX.TEST');

testMatrix = full(spmatrix);
numTestDocs = size(testMatrix, 1);
numTokens = size(testMatrix, 2);

% Assume nb_train.m has just been executed, and all the parameters computed/needed
% by your classifier are in memory through that execution. You can also assume 
% that the columns in the test set are arranged in exactly the same way as for the
% training set (i.e., the j-th column represents the same token in the test data 
% matrix as in the original training data matrix).

% Write code below to classify each document in the test set (ie, each row
% in the current document word matrix) as 1 for SPAM and 0 for NON-SPAM.

% Construct the (numTestDocs x 1) vector 'output' such that the i-th entry 
% of this vector is the predicted class (1/0) for the i-th  email (i-th row 
% in testMatrix) in the test set.
output = zeros(numTestDocs, 1);

%------------------------------------------------------------
% Tony Hyun Kim
% CS 229, PS#2, Problem 3(a)
%------------------------------------------------------------

% The model parameters (from 'nb_train.m') are:
%   p_word(i,k): probability of word k occuring given
%                   i=1 (non-spam) or i=2 (spam) classification
%   p_prior:     class prior probability
% and their log-likelihood counterparts:
%   ll_word
%   ll_prior

for i = 1:numTestDocs % Select the document...
    ll = ll_prior; 
    for j = 1:numTokens % We then loop over all words, 
                        %   accumulating the log likelihoods
        ll = ll + testMatrix(i,j)*ll_word(:,j);
    end
    % Decide based on the accumulated likelihoods
    output(i) = (ll(1)<ll(2));
end
clear i j ll;

% Compute the error on the test set
error=0;
for i=1:numTestDocs
  if (category(i) ~= output(i))
    error=error+1;
  end
end

%Print out the classification error on the test set
fprintf('The classification error rate is %.2f%%\n',error/numTestDocs*100);
