稀疏自动编码之练习

从10幅图像中采样出10000幅小图像块,每个小图像块大小是8*8,利用采样出的图像作为样本学习,利用LBFGS进行优化.

下面是对10幅图像白化之后的结果:

train.m

%% CS294A/CS294W Programming Assignment Starter Code

%  Instructions
%  ------------
%
%  This file contains code that helps you get started on the
%  programming assignment. You will need to complete the code in sampleIMAGES.m,
%  sparseAutoencoderCost.m and computeNumericalGradient.m.
%  For the purpose of completing the assignment, you do not need to
%  change the code in this file.
%
%%======================================================================
%% STEP 0: Here we provide the relevant parameters values that will
%  allow your sparse autoencoder to get good filters; you do not need to
%  change the parameters below.
clear all;clc;
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       

%%======================================================================
%% STEP 1: Implement sampleIMAGES
%
%  After implementing sampleIMAGES, the display_network command should
%  display a random sample of 200 patches from the dataset

patches = sampleIMAGES;
display_network(patches(:,randi(size(patches,2),200,1)),8);

%  Obtain random parameters theta
theta = initializeParameters(hiddenSize, visibleSize);

%%======================================================================
%% STEP 2: Implement sparseAutoencoderCost
%
%  You can implement all of the components (squared error cost, weight decay term,
%  sparsity penalty) in the cost function at once, but it may be easier to do
%  it step-by-step and run gradient checking (see STEP 3) after each step.  We
%  suggest implementing the sparseAutoencoderCost function using the following steps:
%
%  (a) Implement forward propagation in your neural network, and implement the
%      squared error term of the cost function.  Implement backpropagation to
%      compute the derivatives.   Then (using lambda=beta=0), run Gradient Checking
%      to verify that the calculations corresponding to the squared error cost
%      term are correct.
%
%  (b) Add in the weight decay term (in both the cost function and the derivative
%      calculations), then re-run Gradient Checking to verify correctness.
%
%  (c) Add in the sparsity penalty term, then re-run Gradient Checking to
%      verify correctness.
%
%  Feel free to change the training settings when debugging your
%  code.  (For example, reducing the training set size or
%  number of hidden units may make your code run faster; and setting beta
%  and/or lambda to zero may be helpful for debugging.)  However, in your
%  final submission of the visualized weights, please use parameters we
%  gave in Step 0 above.

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

%%======================================================================
%% STEP 3: Gradient Checking
%
% Hint: If you are debugging your code, performing gradient checking on smaller models
% and smaller training sets (e.g., using only 10 training examples and 1-2 hidden
% units) may speed things up.

% First, lets make sure your numerical gradient computation is correct for a
% simple function.  After you have implemented computeNumericalGradient.m,
% run the following:
checkNumericalGradient();

% Now we can use it to check your cost function and derivative calculations
% for the sparse autoencoder.
numgrad = computeNumericalGradient( @(x) sparseAutoencoderCost(x, visibleSize, ...
                                    hiddenSize, lambda,sparsityParam,...
                                    beta,patches), theta);

% Use this to visually compare the gradients side by side
disp([numgrad grad]); 

% Compare numerically computed gradients with the ones obtained from backpropagation
diff = norm(numgrad-grad)/norm(numgrad+grad);
disp(diff); % Should be small. In our implementation, these values are
            % usually less than 1e-9.

            % When you got this working, Congratulations!!! 

%%======================================================================
%% STEP 4: After verifying that your implementation of
%  sparseAutoencoderCost is correct, You can start training your sparse
%  autoencoder with minFunc (L-BFGS).

%  Randomly initialize the parameters
theta = initializeParameters(hiddenSize, visibleSize);

%  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 

sampleIMAGES.m,进行图像采集

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

load IMAGES;    % load images from disk
% figure;
% imagesc(IMAGES(:,:,6));
% colormap gray;
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
[m,n] = size(IMAGES(:,:,1));
for i = 1:10
    image = IMAGES(:, :, i);
    for j = 1:1000
        row_id     = randi([1 (m - patchsize + 1)]);
        column_id  = randi([1 (n - patchsize + 1)]);
        patches(:,(i-1)*1000+j) = reshape(image(row_id:(row_id+patchsize-1), column_id:(column_id+patchsize-1)),...
            patchsize*patchsize, 1);
    end
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
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.
%
Jcost = 0;   % 预测误差项
Jweight = 0; % 权重衰减项
Jsparse = 0; % 稀疏惩罚项
[n,m] = size(data); %m是样本个数,n是样本特征数

%前向传播计算神经网络每个神经元的激活值
Z2 = W1 * data + repmat(b1, 1, m); %b1扩展成1行m列,因为对每个样本的每个隐单元的激活值都要加上偏置项
a2 = sigmoid(Z2);
Z3 = W2 * a2 + repmat(b2, 1, m);
a3 = sigmoid(Z3);

%计算预测产生的误差项
Jcost = (0.5 / m) * sum(sum((a3 - data).^2));

%计算权重衰减项
Jweight = 0.5 * (sum(sum(W1.^2)) + sum(sum(W2.^2)));

%计算稀疏惩罚项
rho = (1 / m) .* sum(a2, 2);
Jsparse = sum(sparsityParam .* log(sparsityParam ./ rho) + ...
        (1- sparsityParam) .* log((1- sparsityParam) ./ (1 - rho)));
%代价函数
cost = Jcost + lambda * Jweight + beta * Jsparse;

%反向传播求出每个节点的误差
d3 = -(data - a3) .* (sigmoid(Z3) .* (1 - sigmoid(Z3)));%注意sigmoid函数的求导f(1-f)
sparseterm = beta * (-sparsityParam ./ rho + ...
            (1- sparsityParam) ./ (1 - rho)); %稀疏项导数
d2 = (W2‘ * d3 + repmat(sparseterm,1,m)).*(sigmoid(Z2) .* (1 - sigmoid(Z2)));

%计算W1grad
W1grad = W1grad + d2 * data‘;
W1grad = (1/m) * W1grad + lambda * W1;

%计算W2grad
W2grad = W2grad+d3*a2‘;
W2grad = (1/m) * W2grad + lambda * W2;

%计算b1grad
b1grad = b1grad+sum(d2,2);
b1grad = (1/m)*b1grad;%注意b的偏导是一个向量,所以这里应该把每一行的值累加起来

%计算b2grad
b2grad = b2grad+sum(d3,2);
b2grad = (1/m)*b2grad;

%-------------------------------------------------------------------
% 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
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 = 1e-4;
n = size(theta,1);
E = eye(n);
for i = 1:n
    delta = E(:,i)*epsilon;
    numgrad(i) = (J(theta+delta)-J(theta-delta))/(epsilon*2.0);
end

%% ---------------------------------------------------------------
end
function [] = checkNumericalGradient()
% This code can be used to check your numerical gradient implementation
% in computeNumericalGradient.m
% It analytically evaluates the gradient of a very simple function called
% simpleQuadraticFunction (see below) and compares the result with your numerical
% solution. Your numerical gradient implementation is incorrect if
% your numerical solution deviates too much from the analytical solution.

% Evaluate the function and gradient at x = [4; 10]; (Here, x is a 2d vector.)
x = [4; 10];
[value, grad] = simpleQuadraticFunction(x);

% Use your code to numerically compute the gradient of simpleQuadraticFunction at x.
% (The notation "@simpleQuadraticFunction" denotes a pointer to a function.)
numgrad = computeNumericalGradient(@simpleQuadraticFunction, x);

% Visually examine the two gradient computations.  The two columns
% you get should be very similar.
disp([numgrad grad]);
fprintf(‘The above two columns you get should be very similar.\n(Left-Your Numerical Gradient, Right-Analytical Gradient)\n\n‘);

% Evaluate the norm of the difference between two solutions.
% If you have a correct implementation, and assuming you used EPSILON = 0.0001
% in computeNumericalGradient.m, then diff below should be 2.1452e-12
diff = norm(numgrad-grad)/norm(numgrad+grad);
disp(diff);
fprintf(‘Norm of the difference between numerical and analytical gradient (should be < 1e-9)\n\n‘);
end

function [value,grad] = simpleQuadraticFunction(x)
% this function accepts a 2D vector as input.
% Its outputs are:
%   value: h(x1, x2) = x1^2 + 3*x1*x2
%   grad: A 2x1 vector that gives the partial derivatives of h with respect to x1 and x2
% Note that when we pass @simpleQuadraticFunction(x) to computeNumericalGradients, we‘re assuming
% that computeNumericalGradients will use only the first returned value of this function.

value = x(1)^2 + 3*x(1)*x(2);

grad = zeros(2, 1);
grad(1)  = 2*x(1) + 3*x(2);
grad(2)  = 3*x(1);

end
function [h, array] = display_network(A, opt_normalize, opt_graycolor, cols, opt_colmajor)
% This function visualizes filters in matrix A. Each column of A is a
% filter. We will reshape each column into a square image and visualizes
% on each cell of the visualization panel.
% All other parameters are optional, usually you do not need to worry
% about it.
% opt_normalize: whether we need to normalize the filter so that all of
% them can have similar contrast. Default value is true.
% opt_graycolor: whether we use gray as the heat map. Default is true.
% cols: how many columns are there in the display. Default value is the
% squareroot of the number of columns in A.
% opt_colmajor: you can switch convention to row major for A. In that
% case, each row of A is a filter. Default value is false.
warning off all

if ~exist(‘opt_normalize‘, ‘var‘) || isempty(opt_normalize)
    opt_normalize= true;
end

if ~exist(‘opt_graycolor‘, ‘var‘) || isempty(opt_graycolor)
    opt_graycolor= true;
end

if ~exist(‘opt_colmajor‘, ‘var‘) || isempty(opt_colmajor)
    opt_colmajor = false;
end

% rescale
A = A - mean(A(:));

if opt_graycolor, colormap(gray); end

% compute rows, cols
[L M]=size(A);
sz=sqrt(L);
buf=1;
if ~exist(‘cols‘, ‘var‘)
    if floor(sqrt(M))^2 ~= M
        n=ceil(sqrt(M));
        while mod(M, n)~=0 && n<1.2*sqrt(M), n=n+1; end
        m=ceil(M/n);
    else
        n=sqrt(M);
        m=n;
    end
else
    n = cols;
    m = ceil(M/n);
end

array=-ones(buf+m*(sz+buf),buf+n*(sz+buf));

if ~opt_graycolor
    array = 0.1.* array;
end

if ~opt_colmajor
    k=1;
    for i=1:m
        for j=1:n
            if k>M,
                continue;
            end
            clim=max(abs(A(:,k)));
            if opt_normalize
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;
            else
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/max(abs(A(:)));
            end
            k=k+1;
        end
    end
else
    k=1;
    for j=1:n
        for i=1:m
            if k>M,
                continue;
            end
            clim=max(abs(A(:,k)));
            if opt_normalize
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz)/clim;
            else
                array(buf+(i-1)*(sz+buf)+(1:sz),buf+(j-1)*(sz+buf)+(1:sz))=reshape(A(:,k),sz,sz);
            end
            k=k+1;
        end
    end
end

if opt_graycolor
    h=imagesc(array,‘EraseMode‘,‘none‘,[-1 1]);
else
    h=imagesc(array,‘EraseMode‘,‘none‘,[-1 1]);
end
axis image off

drawnow;

warning on all

进行梯度检验,两种不同的方式计算出的梯度相差 7.2299e-11,远小于1e-9.

随机展示出所有采样图像中的200幅:

本程序主要耗时间的地方是梯度检验,大约4-5分钟.

最终学习出的权重可视化结果如下:

时间: 2024-10-21 18:48:21

稀疏自动编码之练习的相关文章

稀疏自动编码之反向传播算法(BP)

假设给定m个训练样本的训练集,用梯度下降法训练一个神经网络,对于单个训练样本(x,y),定义该样本的损失函数: 那么整个训练集的损失函数定义如下: 第一项是所有样本的方差的均值.第二项是一个归一化项(也叫权重衰减项),该项是为了减少权连接权重的更新速度,防止过拟合. 我们的目标是最小化关于 W 和 b 的函数J(W,b). 为了训练神经网络,把每个参数 和初始化为很小的接近于0的随机值(例如随机值由正态分布Normal(0,ε2)采样得到,把 ε 设为0.01), 然后运用批量梯度下降算法进行优

稀疏自动编码之梯度检验

众所周知,反向传播算法很难调试和得到正确结果,特别是在执行过程中存在许多细小难以察觉的错误.这里介绍一种方法来确定代码中导数的计算是否正确.使用这里所述求导检验方法,可以帮助提升写正确代码的信心. 假设我们想最小化关于  的函数   . 对于这个例子,假设 ,所以 . 在一维空间,梯度下降的一次迭代公式如下: 假设我们已经实现了某个函数  去计算 ,那么梯度下降时参数更新就可以这样:. 该如何检验我们编写的函数  是正确的呢? 回忆导数的定义: 对于任意的  ,可以用如下公式来从数值上近似导数值

稀疏自动编码之自动编码器和稀疏性

到目前为止,已经叙述了神经网络的监督学习,即学习的样本都是有标签的.现在假设我们有一个没有标签的训练集,其中. 自动编码器就是一个运用了反向传播进行无监督学习的神经网络,学习的目的就是为了让输出值和输入值相等,即.下面就是一个自动编码器: 自动编码器试图学习一个函数. 换句话说,它试图逼近一个等式函数,使得该函数的输出  和输入  很近似.举一个具体的例子,假设输入  是来自一个  图像(共100个像素点)像素点的灰度值,在  层有  个隐层节点. 注意输出 . 由于隐层节点只有50个,所以网络

稀疏自动编码之可视化自动编码器

对于训练出的一个稀疏自动编码器,现在想看看学习出的函数到底是什么样子.对于训练一个的图像,.计算每一个隐层节点    的输出值: 我们要可视化的函数,就是这个以一副2D图像为输入,以 为参数(忽略偏置项),由隐层节点  计算出来的函数.特别是,我们把  看作是输入  的非线性特征.我们很想知道:什么样的的图像  能使得  成为最大程度的激励? 还有一个问题,就是必须对  加上约束.如果假设输入的范数约束是,可以证明,能够使得隐层神经元得到最大程度激活的像素输入   (所有100个像素点,): 展

稀疏自动编码之神经网络

考虑一个监督学习问题,现在有一些带标签的训练样本(x(i),y(i)).神经网络就是定义一个复杂且非线性的假设hW,b(x),其中W,b 是需要拟合的参数. 下面是一个最简单的神经网络结构,只含有一个神经元,后面就用下图的形式代表一个神经元: 把神经元看作是一个计算单元,左边的x1,x2,x3 (和 截距+1 )作为计算单元的输入,输出为:,其中,函数被称为激活函数,在这里我们的激活函数是sigmoid函数: 还有一种激活函数是正切函数(tanh function): 下面是两种激活函数图像:

Sparse Autoencoder稀疏自动编码

本系列文章都是关于UFLDL Tutorial的学习笔记 Neural Networks 对于一个有监督的学习问题,训练样本输入形式为(x(i),y(i)).使用神经网络我们可以找到一个复杂的非线性的假设h(x(i))可以拟合我们的数据y(i).我们先观察一个神经元的机制: 每个神经元是一个计算单元,输入为x1,x2,x3,输出为: 其中f()是激活函数,常用的激活函数是S函数: S函数的形状如下,它有一个很好的性质就是导数很方便求:f'(z) = f(z)(1 ? f(z)): 还有一个常见的

Deep Learning 12_深度学习UFLDL教程:Sparse Coding_exercise(斯坦福大学深度学习教程)

前言 理论知识:UFLDL教程.Deep learning:二十六(Sparse coding简单理解).Deep learning:二十七(Sparse coding中关于矩阵的范数求导).Deep learning:二十九(Sparse coding练习) 实验环境:win7, matlab2015b,16G内存,2T机械硬盘 本节实验比较不好理解也不好做,我看很多人最后也没得出好的结果,所以得花时间仔细理解才行. 实验内容:Exercise:Sparse Coding.从10张512*51

Dictionary Learning(字典学习、稀疏表示以及其他)

第一部分 字典学习以及稀疏表示的概要 字典学习(Dictionary Learning)和稀疏表示(Sparse Representation)在学术界的正式称谓应该是稀疏字典学习(Sparse Dictionary Learning).该算法理论包含两个阶段:字典构建阶段(Dictionary Generate)和利用字典(稀疏的)表示样本阶段(Sparse coding with a precomputed dictionary).这两个阶段(如下图)的每个阶段都有许多不同算法可供选择,每种

算法导论——所有点对最短路径:稀疏图Johnson算法

package org.loda.graph; import org.loda.structure.Stack; import org.loda.util.In; /** * * @ClassName: Johnson 时间复杂度:EVlgV * @Description: 稀疏图上的johnson算法,由于稀疏图的数据结构推荐使用邻接链表,所以这里也采用邻接链表,该算法也是给稀疏图使用的,如果是密集图,推荐使用实现较为简单的FloydWashall算法,可以保证V^3的时间复杂度 * * Jo