Skip to content

Instantly share code, notes, and snippets.

@tonyfast
Created November 30, 2014 13:31
Show Gist options
  • Select an option

  • Save tonyfast/026048727310298faceb to your computer and use it in GitHub Desktop.

Select an option

Save tonyfast/026048727310298faceb to your computer and use it in GitHub Desktop.
Iterative Principal Component Analysis
function [Un, mn, An, S, nr] = iPCA(x, U, m, A, max_dim)
% Execute incremental PCA analysis
% Input
% x - new input vector (Dx1)
% Uo - Last basis (Dxd)
% mo - last mean (Dx1)
% Ao - last coefficients (dxn)
% max_dim - maximum number of dimensions to consider, if this not
% prescribed or null then the function augments the basis accorindgly
% Choose the preffered dimensionality
reduce = 0;
if nargin == 5 && numel(max_dim) > 0
reduce = 1;
end
% Initialize on first, on first iteration define U,m, and A as null
if (numel(U) + numel(A) )== 0
Un = zeros(numel(x),1);
An = 0;
mn = x(:);
S = 0;
nr = 0;
disp('Initializing')
return
end
% This is from the second iteration on
x = x(:); % assure that x is a column vector
m = m(:); % assure that the mean is a column vector
% compute the new projection
if size(U,1) < size(U,2)
error('The dimensions of the basis are inconsistent with the algorithm');
end
a = U' * (x - m); % compute the new projection dx1
y = U * a + m; % Reconstruct input Dx1
r = x - y ; % Residual of reconstruction
nr = norm(r);
Up = [U, r./nr]; % D x d+1
Ap = [ A, a; zeros(1,size(A,2)), nr]; % d+1 x n+1
% batch PCA
mpp = mean(Ap,2); % mean of new projections dx1
Atemp = Ap - repmat( mpp, 1, size(Ap,2));
C = Atemp * Atemp'; % Mean centered covariance matrix
% batch PCA
[Upp, S] = eig(C);
% disp([sum(sum(Up.^2,2)) sum(sum(Up.^2,1))])
An = Upp' * ( Ap - mpp * ones(1, size(Atemp,2))); % Update coefficients
Un = Up * Upp; % Update basis
mn = m + Up*mpp; % Update mean
if reduce && size(S,1) > max_dim
Un(:,1) = []; S(1,:) = []; S(:,1) = []; An(1,:) = [];
end
@tonyfast

tonyfast commented Dec 1, 2014

Copy link
Copy Markdown
Author

No. I don't know if it works. I was hoping you could help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment