csci5521/assignments/hwk02/Back_Project.m

31 lines
939 B
Mathematica
Raw Normal View History

2023-10-12 23:51:06 +00:00
% implements the Back Projection algorithm, returns nothing but displays
% the first 5 eigenfaces of the training data after being 'back-projected'
% using the first 10, 50, and 100 eigenvectors of the data.
function [] = Back_Project(training_data, test_data, n_components)
% stack data
2023-10-22 04:32:00 +00:00
data = vertcat(training_data, test_data);
2023-10-12 23:51:06 +00:00
2023-10-22 06:04:22 +00:00
% perform PCA
2023-10-25 10:20:44 +00:00
[coeff, score] = pca(data);
2023-10-12 23:51:06 +00:00
% for each number of principal components
2023-10-22 06:04:22 +00:00
for n_idx = 1:length(n_components)
n = n_components(n_idx);
2023-10-12 23:51:06 +00:00
2023-10-25 10:20:44 +00:00
% perform the back projection algorithm using the first n_components(n) principal components
2023-10-22 06:04:22 +00:00
W = coeff(:,1:n);
2023-10-25 10:20:44 +00:00
z = score(:,1:n);
sample_mean = mean(data);
reconstruction = W * z' + sample_mean';
2023-10-12 23:51:06 +00:00
2023-10-25 10:20:44 +00:00
% plot first 5 images back projected using the first
2023-10-22 04:32:00 +00:00
% n_components(n) principal components
2023-10-25 10:20:44 +00:00
for i = 1:5
subplot(3,2,i)
imagesc(reshape(reconstruction(:,i),32,30)');
end
2023-10-12 23:51:06 +00:00
end
end % Function end