Skip to content

Commit

Permalink
pca and pcaPred are rewritten (not finished).
Browse files Browse the repository at this point in the history
  • Loading branch information
sth4nth committed Dec 18, 2015
1 parent b758026 commit ba6dd0e
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
13 changes: 13 additions & 0 deletions chapter06/pca.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function model = pca( X, p )
% Principal component analysis
% Written by Mo Chen ([email protected]).

Xo = bsxfun(@minus,X,mean(X,2));
S = Xo*Xo'/size(X,2); % 12.3
[U,A] = eig(S); % 12.5
[A,idx] = sort(diag(A),'descend');
U = U(:,idx(1:p));
A = A(1:p);

model.U = U;
model.A = A;
6 changes: 6 additions & 0 deletions chapter06/pcaPred.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
function = pcaPred( model, Xt )
% Prediction for PCA: project future data to principal subspace
% model: trained model structure
% Xt: d x n testing data
% Written by Mo Chen ([email protected]).

6 changes: 6 additions & 0 deletions chapter06/pcaPred.m~
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
function = pcaPred( model, Xt )
% Prediction for PCA: project future data to principal subspace
% model: trained model structure
% Xt: d x n testing data
% Written by Mo Chen ([email protected]).

40 changes: 40 additions & 0 deletions chapter12/pca.m~
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
function [V, A] = pca(X, p)
% Perform standard PCA (spectral method).
% X: d x n data matrix
% p: dimension of target space (p>=1) or ratio (0<p<1)
% Written by Mo Chen ([email protected]).

Xo = bsxfun(@minus,X,mean(X,2));


opts.disp = 0;
opts.issym = 1;
opts.isreal = 1;
opts.maxit = 500;

[d,n] = size(X);
if nargin == 1
p = min(d,n);
end


if 0<p && p<1 % given ratio
[V,A] = svd(X,'econ');
A = diag(A).^2;

S = cumsum(A);
idc = (S/S(end))<=p;
V = V(:,idc);
A = A(idc);
elseif p >= min(d,n) % full pca
[V,A] = svd(X,'econ');
A = diag(A).^2;
elseif d <= n % covariance based pca
[V,A] = eigs(X*X',p,'la',opts);
A = diag(A);
elseif d > n % inner product based pca
[U,A] = eigs(X'*X,p,'la',opts);
A = diag(A);
V = X*bsxfun(@times,U,1./sqrt(A)');
end

0 comments on commit ba6dd0e

Please sign in to comment.