UFLDL Exercise:Sparse Autoencoder

之前雖然看了ufldl的教程,但是沒去做他的練習。作爲一個剛剛入門機器學習的學生,還是不能偷懶,所以趁今天有時間做了第一個練習題Sparse Autoencoder

下面貼下代碼 還有講下做的過程中發現的一些問題。

STEP 1: Implement sampleIMAGES

sampleIMAGES.m

function patches = sampleIMAGES()
% sampleIMAGES
% Returns 10000 patches for training

load IMAGES;    % load images from disk 

patchsize = 8;  % we'll use 8x8 patches 
numpatches = 10000;

% Initialize patches with zeros.  Your code will fill in this matrix--one
% column per patch, 10000 columns. 
patches = zeros(patchsize*patchsize, numpatches);

%% ---------- YOUR CODE HERE --------------------------------------
%  Instructions: Fill in the variable called "patches" using data 
%  from IMAGES.  
%  
%  IMAGES is a 3D array containing 10 images
%  For instance, IMAGES(:,:,6) is a 512x512 array containing the 6th image,
%  and you can type "imagesc(IMAGES(:,:,6)), colormap gray;" to visualize
%  it. (The contrast on these images look a bit off because they have
%  been preprocessed using using "whitening."  See the lecture notes for
%  more details.) As a second example, IMAGES(21:30,21:30,1) is an image
%  patch corresponding to the pixels in the block (21,21) to (30,30) of
%  Image 1
image_size = size(IMAGES); %圖像大小
for i=1:numpatches
    x = randi(image_size(1) - patchsize); %隨機得到patch的最小x座標
    y = randi(image_size(2) - patchsize); %隨機得到patch的最小y座標
    patches(:,i) = reshape(IMAGES(x:x+patchsize-1,y:y+patchsize-1,randi(image_size(3))),patchsize*patchsize,1); %隨機選擇一個張圖片用上面得到座標進行sample得到patch
end




%% ---------------------------------------------------------------
% For the autoencoder to work well we need to normalize the data
% Specifically, since the output of the network is bounded between [0,1]
% (due to the sigmoid activation function), we have to make sure 
% the range of pixel values is also bounded between [0,1]
patches = normalizeData(patches);

end


%% ---------------------------------------------------------------
function patches = normalizeData(patches)

% Squash data to [0.1, 0.9] since we use sigmoid as the activation
% function in the output layer

% Remove DC (mean of images). 
patches = bsxfun(@minus, patches, mean(patches));

% Truncate to +/-3 standard deviations and scale to -1 to 1
pstd = 3 * std(patches(:));
patches = max(min(patches, pstd), -pstd) / pstd;

% Rescale from [-1,1] to [0.1,0.9]
patches = (patches + 1) * 0.4 + 0.1;

end

測試下sampleIMAGES.m

patches = sampleIMAGES;
display_network(patches(:,randi(size(patches,2),200,1)),8);
得到如下的圖片,說明代碼沒問題大笑


step 3: Gradient Checking(建議先跳過step2,先實現梯度檢查代碼,再實現sparseAutoencoderCost代碼,這樣可以保證梯度檢查代碼沒錯情況下才來檢查sparseAutoencoderCost代碼)

computeNumericalGradient.m

function numgrad = computeNumericalGradient(J, theta)
% numgrad = computeNumericalGradient(J, theta)
% theta: a vector of parameters
% J: a function that outputs a real-number. Calling y = J(theta) will return the
% function value at theta. 
  
% Initialize numgrad with zeros
numgrad = zeros(size(theta));

%% ---------- YOUR CODE HERE --------------------------------------
% Instructions: 
% Implement numerical gradient checking, and return the result in numgrad.  
% (See Section 2.3 of the lecture notes.)
% You should write code so that numgrad(i) is (the numerical approximation to) the 
% partial derivative of J with respect to the i-th input argument, evaluated at theta.  
% I.e., numgrad(i) should be the (approximately) the partial derivative of J with 
% respect to theta(i).
%                
% Hint: You will probably want to compute the elements of numgrad one at a time. 
epsilon = 0.0001;
for i = 1:size(theta)
    theta_add = theta;
    theta_sub = theta;
    theta_add(i) = theta_add(i) + epsilon;
    theta_sub(i) = theta_sub(i) - epsilon;
    numgrad(i) = (J(theta_add) - J(theta_sub)) / (2 * epsilon);
end







%% ---------------------------------------------------------------
end

測試下代碼

checkNumericalGradient();
運行結果如下,說明代碼沒問題大笑


step 2:Implement sparseAutoencoderCost

sparseAutoencoderCost.m

function [cost,grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, ...
                                             lambda, sparsityParam, beta, data)

% visibleSize: the number of input units (probably 64) 
% hiddenSize: the number of hidden units (probably 25) 
% lambda: weight decay parameter
% sparsityParam: The desired average activation for the hidden units (denoted in the lecture
%                           notes by the greek alphabet rho, which looks like a lower-case "p").
% beta: weight of sparsity penalty term
% data: Our 64x10000 matrix containing the training data.  So, data(:,i) is the i-th training example. 
  
% The input theta is a vector (because minFunc expects the parameters to be a vector). 
% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this 
% follows the notation convention of the lecture notes. 

W1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);
W2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);
b1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);
b2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);

% Cost and gradient variables (your code needs to compute these values). 
% Here, we initialize them to zeros. 
cost = 0;
W1grad = zeros(size(W1)); 
W2grad = zeros(size(W2));
b1grad = zeros(size(b1)); 
b2grad = zeros(size(b2));

%% ---------- YOUR CODE HERE --------------------------------------
%  Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,
%                and the corresponding gradients W1grad, W2grad, b1grad, b2grad.
%
% W1grad, W2grad, b1grad and b2grad should be computed using backpropagation.
% Note that W1grad has the same dimensions as W1, b1grad has the same dimensions
% as b1, etc.  Your code should set W1grad to be the partial derivative of J_sparse(W,b) with
% respect to W1.  I.e., W1grad(i,j) should be the partial derivative of J_sparse(W,b) 
% with respect to the input parameter W1(i,j).  Thus, W1grad should be equal to the term 
% [(1/m) \Delta W^{(1)} + \lambda W^{(1)}] in the last block of pseudo-code in Section 2.2 
% of the lecture notes (and similarly for W2grad, b1grad, b2grad).
% 
% Stated differently, if we were using batch gradient descent to optimize the parameters,
% the gradient descent update to W1 would be W1 := W1 - alpha * W1grad, and similarly for W2, b1, b2. 
% 
a1 = sigmoid(bsxfun(@plus,W1 * data,b1)); %hidden層輸出
a2 = sigmoid(bsxfun(@plus,W2 * a1,b2)); %輸出層輸出
p = mean(a1,2); %隱藏神經元的平均活躍度
sparsity = sparsityParam .* log(sparsityParam ./ p) + (1 - sparsityParam) .* log((1 - sparsityParam) ./ (1.-p)); %懲罰因子
cost = sum(sum((a2 - data).^2)) / 2 / size(data,2) + lambda / 2 * (sum(sum(W1.^2)) + sum(sum(W2.^2))) + beta * sum(sparsity); %代價函數
delt2 = (a2 - data) .* a2 .* (1 - a2); %輸出層殘差
delt1 = (W2' * delt2 + beta .* repmat((-sparsityParam./p + (1-sparsityParam)./(1.-p)),1,size(data,2))) .* a1 .* (1 - a1); %hidden層殘差
W2grad = delt2 * a1' ./ size(data,2) + lambda * W2; 
W1grad = delt1 * data' ./ size(data,2) + lambda * W1;
b2grad = sum(delt2,2) ./ size(data,2);
b1grad = sum(delt1,2) ./ size(data,2);

%-------------------------------------------------------------------
% After computing the cost and gradient, we will convert the gradients back
% to a vector format (suitable for minFunc).  Specifically, we will unroll
% your gradient matrices into a vector.

grad = [W1grad(:) ; W2grad(:) ; b1grad(:) ; b2grad(:)];

end

%-------------------------------------------------------------------
% Here's an implementation of the sigmoid function, which you may find useful
% in your computation of the costs and the gradients.  This inputs a (row or
% column) vector (say (z1, z2, z3)) and returns (f(z1), f(z2), f(z3)). 

function sigm = sigmoid(x)
  
    sigm = 1 ./ (1 + exp(-x));
end

測試下代碼

visibleSize = 8*8;
hiddenSize = 25;     
sparsityParam = 0.01;   
lambda = 0.0001;         
beta = 3;              
patches = sampleIMAGES;
patches = patches(:,1:2); %建議用部分訓練數據測試即可
theta = initializeParameters(hiddenSize, visibleSize);
[cost, grad] = sparseAutoencoderCost(theta, visibleSize, hiddenSize, lambda, ...
                                     sparsityParam, beta, patches);
numgrad = computeNumericalGradient( @(x) sparseAutoencoderCost(x, visibleSize, ...
                                                          hiddenSize, lambda, ...
                                                          sparsityParam, beta, ...
                                                   patches), theta);

disp([numgrad grad]); 
diff = norm(numgrad-grad)/norm(numgrad+grad);
disp(diff); 

結果如下,誤差很小,代碼沒問題大笑


step4 & 5:train the sparse autoencoder & visualization

代碼如下

%% STEP 4: After verifying that your implementation of
%  sparseAutoencoderCost is correct, You can start training your sparse
%  autoencoder with minFunc (L-BFGS).
visibleSize = 8*8;   % number of input units 
hiddenSize = 25;     % number of hidden units 
sparsityParam = 0.01;   % desired average activation of the hidden units.
                     % (This was denoted by the Greek alphabet rho, which looks like a lower-case "p",
		     %  in the lecture notes). 
lambda = 0.0001;     % weight decay parameter       
beta = 3;            % weight of sparsity penalty term 
theta = initializeParameters(hiddenSize, visibleSize); %  Randomly initialize the parameters
patches = sampleIMAGES;
%  Use minFunc to minimize the function
addpath minFunc/
options.Method = 'lbfgs'; % Here, we use L-BFGS to optimize our cost
                          % function. Generally, for minFunc to work, you
                          % need a function pointer with two outputs: the
                          % function value and the gradient. In our problem,
                          % sparseAutoencoderCost.m satisfies this.
options.maxIter = 400;	  % Maximum number of iterations of L-BFGS to run 
options.display = 'on';


[opttheta, cost] = minFunc( @(p) sparseAutoencoderCost(p, ...
                                   visibleSize, hiddenSize, ...
                                   lambda, sparsityParam, ...
                                   beta, patches), ...
                              theta, options);

%%======================================================================
%% STEP 5: Visualization 

W1 = reshape(opttheta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);
display_network(W1', 12); 

print -djpeg weights.jpg   % save the visualization to a file 

最終結果如下


做的過程中發現,如果不加權重衰減和稀疏性限制,效果會很差,不能出現上面這樣的效果。

下圖是不加權重衰減和稀疏性限制訓練出來的效果




下圖是加了權重衰減但沒加稀疏性限制訓練出來的結果




下圖是加了稀疏性限制但沒加權重衰減訓練出來的結果



由此看出權重衰減和稀疏性對結果的影響挺大的,以後用神經網絡時要記得加上!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章