UFLDL Sparse Autoencoder

来源:互联网 发布:php判断来路域名 编辑:程序博客网 时间:2024/05/23 20:43

Reference:
[1]http://www.stanford.edu/class/cs294a/cs294a_2011-assignment.pdf
[2]http://nlp.stanford.edu/~socherr/sparseAutoencoder_2011new.pdf
[3]http://www.cnblogs.com/tornadomeet/archive/2013/03/20/2970724.html
[4]http://ufldl.stanford.edu/tutorial/unsupervised/Autoencoders/

稀疏自编码其实是实现了这样的一个东西,就是训练一个神经网络,输出和输入的数量是相同的,那么目的其实就是为了重构图片,其实可以看作是一种非线性的压缩变换。但是第一层和第二层的权重实际上是不一样的。之前有一个误区就是压缩和重构的变换也许具有某种关系,但是实现了这个稀疏自编码之后发现其实可以没有任何关系。

在实现的过程中,其实主要就是三个函数,一个是暴力算梯度,根据cost来进行计算的。

还有就是sampltIMAGES,其实就是从照片中截取patches。

最重要的就是sparseAutoencoderCost.m,通过了数值计算梯度的测试之后,我发现一个很关键的问题,就是最后训练训练就不走了,step太小了。

without_lambda

我猜测原因是因为过拟合了。。。。

但是为啥呢?后来检查代码才发现,是在更新的时候正则化项写错了。。。其实在update W的时候是需要进行lambda×W的更新的,但是我这种方式来实现的时候,并没有加入,或者也除以图片的数目了,这样导致正则化项几乎没有作用。

但是在数值检查梯度的时候,确实影响非常小,所以能够通过。。。

调整了正则化项之后再看学习到的feature就非常好了。

with_lambda0.0001

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. % hidden = sigmoid(W1*data + repmat(b1,1,size(data,2)));data_recon = sigmoid(W2*hidden + repmat(b2,1,size(data,2)));Jcost = sum(sum( (data - data_recon).^2)) / (2*size(data,2));Jweight = (sum(sum(W1.^2))+sum(sum(W2.^2))) *lambda / 2;activations = sum(hidden,2) ./ size(data,2);Jsparse = sparsityParam.*log(sparsityParam ./ activations) + ...    ((1-sparsityParam).*log( (1-sparsityParam) ./ (1-activations) ) );Jsparse = sum(Jsparse)*beta;cost = Jcost+Jweight+Jsparse;delta = (data_recon - data).*data_recon.*(1-data_recon);b2grad = sum(delta,2) / size(data,2);W2grad = (delta * hidden'./size(data,2)) + lambda * W2 ;sparseGrad = beta * (-sparsityParam./activations + (1-sparsityParam) ./ (1-activations));delta = W2'*delta;delta = delta + repmat(sparseGrad,1,size(delta,2));delta =  delta .* hidden .* (1-hidden);b1grad = sum(delta,2) ./ size(data,2);W1grad = delta * data' ./ size(data,2)  + lambda * W1;%-------------------------------------------------------------------% 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

sampleIMAGES.m

function patches = sampleIMAGES()% sampleIMAGES% Returns 10000 patches for trainingload 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);%64*10000%% ---------- 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 1imageDim = size(IMAGES,1);for imageNum = 1:10    rows = int64(rand(1000,1)*(imageDim - patchsize))+1;    cols = int64(rand(1000,1)*(imageDim - patchsize))+1;    for i = 1:1000        row = rows(i);        col = cols(i);%         fprintf('%d %d\n',row,col);        image = IMAGES(row:row+7,col:col+7,imageNum);        patches(:,1000*(imageNum-1)+i) = image(:);    endend%% ---------------------------------------------------------------% 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 1pstd = 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

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 zerosnumgrad = 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 = 1e-4; for i = 1:length(numgrad)    val_old = theta(i);    val_plus = theta(i)+epsilon;    val_minus = theta(i)-epsilon;    theta(i) = val_plus;    [cost_plus , ~] = J(theta);    theta(i) = val_minus;    [cost_minus , ~] = J(theta);    theta(i) = val_old;    numgrad(i) = (cost_plus - cost_minus) / (2*epsilon);end%% ---------------------------------------------------------------end
0 0