csci5521/assignments/hwk02/KNN_Error.m
2023-10-22 01:04:22 -05:00

36 lines
No EOL
1.2 KiB
Matlab

% implements KNN_Error, returns nothing but prints out a table of test
% errors for k-nearest neighbors using different values of k.
function [] = KNN_Error(neigenvectors, ks, training_data, test_data, training_labels, test_labels)
% perform PCA
data = vertcat(training_data, test_data);
coeff = pca(data);
% project data using the number of eigenvectors defined by neigenvectors
eigenvectors = coeff(:,1:neigenvectors);
projected_data = data * eigenvectors;
% split matrix back out
training_rows = size(training_data, 1);
projected_training_data = projected_data(1:training_rows,:);
projected_test_data = projected_data(training_rows+1:end,:);
% compute test error for kNN with differents k's. Fill in
% test_errors with the results for each k in ks.
test_errors = zeros(1,length(ks));
for i = 1:length(ks)
k = ks(i);
test_errors(i) = KNN(k, projected_training_data, projected_test_data, training_labels, test_labels);
end
% print error table
fprintf("-----------------------------\n");
fprintf("| k | test error\n")
fprintf("-----------------------------\n");
for i = 1:length(ks)
fprintf("| %d | %.8f \n", ks(i), test_errors(i));
end
fprintf("-----------------------------\n");
end % Function end