-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpcaExample.m
More file actions
43 lines (33 loc) · 863 Bytes
/
pcaExample.m
File metadata and controls
43 lines (33 loc) · 863 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
%% Initialization
m = 500; % training data count
n = 100; % number of input features
X = rand(m,n); % bogus data
target = 0.95; % target retained variance
%% Zero-mean normalization and feature scaling
mu = mean(X);
sigma = std(X);
X = (X - mu) ./ sigma;
%% Algorithm
% Covariance Matrix
Sigma = 1/m * (X' * X);
% Compute eigenvectors
[U,S,V] = svd(Sigma);
%% Find number of components for desired variance
S_diag = diag(S);
S_trace = trace(S);
% find the smallest number of principal components that meets our target
% retained variance
k = 0;
variance = 0;
while variance < target
k = k + 1;
variance = sum(S_diag(1:k)) / S_trace;
end
% Change of basis matrix
P = U(:, 1:k);
%% Compress a high dimensional input datum
x = rand(n,1);
x = (x - mu') ./ sigma';
z = P' * x;
%% Decompress a low dimensional output datum
x_ = P * z;