% Work through an example of principal component analysis (PCA)
% using singular value decomposition (SVD). Here we find "average faces"
% from a collection of portraits.
%
% Samuli Siltanen November 2012
% Plot parameters
msize = 15;
lwidth = 1.5;
fsize = 16;
% Number of pictures
Npics = 31;
% Initialize the data matrix
XT = zeros(Npics,80*128);
% Construct the data matrix where the data vectors appear as rows. There
% are as many rows as there are images.
for iii = 1:Npics
fname = ['portraits/im', num2str(iii), '.tif'];
im = imread(fname,'tif');
im = double(im);
XT(iii,:) = im(:).';
end
% Record image size for later use
[row,col] = size(im);
% Calculate non-negative matrix factorization
X = XT.'; % Taking the transpose
Fnum = 15;
[W,H] = nnmf(X,Fnum); % This factors X approximately into W*H
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Show the results
for iii = 1:Fnum
figure(1)
clf
pcomp = W(:,iii);
pcomp = reshape(pcomp,row,col);
imagesc(pcomp)
colormap gray
axis equal
axis off
drawnow
pause
end