Exercise:PCA and Whitening 代码示例

Exercise:PCA and Whitening 代码示例

练习参考PCA and Whitening,与上一个练习基本一致。

 

更改图像数据的均值

 

[plain] view plaincopy
 
  1. avg = mean(x,1);  
  2. x = x - repmat(avg,size(x,1),1);  

 

Implement PCA to obtain xRot

 

[plain] view plaincopy
 
  1. xRot = zeros(size(x));  
  2. sigma = x * x' / size(x,2);    
  3. [u,s,v] = svd(sigma);   
  4. xRot = u' * x;   

 

Check your implementation of PCA

 

[plain] view plaincopy
 
  1. covar = zeros(size(x, 1));  
  2. covar = xRot * xRot' / size(xRot,2);  

 

Find k, the number of components to retain

 

[plain] view plaincopy
 
  1. k = 0; % Set k accordingly  
  2. all = sum(diag(s));    
  3. for i=1:size(s,1)   
  4.     if sum(diag(s(1:i,1:i))) / all >= 0.99    
  5.         k = i;    
  6.         break;    
  7.     end    
  8. end  

 

 

Implement PCA with dimension reduction

 

[plain] view plaincopy
 
  1. xHat = zeros(size(x));  
  2. xTilde = u(:,1:k)' * x;    
  3. xHat = u(:,1:k) * xTilde;  

 

 

Implement PCA with whitening and regularisation

 

[plain] view plaincopy
 
  1. epsilon = 0.1;  
  2. xPCAWhite = zeros(size(x));  
  3. xPCAWhite = diag(sqrt(1./(diag(s) + epsilon))) * xRot;  

 

 

Check your implementation of PCA whitening 

 

[plain] view plaincopy
 
  1. covar = xPCAWhite * xPCAWhite' / size(xPCAWhite,2)  

 

 

Implement ZCA whitening

 

[plain] view plaincopy
 
  1. xZCAWhite = zeros(size(x));  
  2. xZCAWhite = u * xPCAWhite;  
posted @ 2015-11-16 14:55  菜鸡一枚  阅读(115)  评论(0编辑  收藏  举报