# 深度学习笔记：稀疏自编码器（4）——稀疏自编码器代码练习

本文是ufldl稀疏自编码器教程中的练习，详细的练习要求参见Exercise:Sparse Autoencoder，笔者将练习中要求实现的三个文件代码记录在此，并作了详细的注释。

% sampleIMAGES.m
function patches = sampleIMAGES() % 函数返回64*10000的矩阵patches
% sampleIMAGES
% Returns 10000 patches for training

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

%% 注释译文：
%   指导：用IMAGES中提取出的数据填充变量"patches"
%
%   IMAGES是一个包含10个图片的3D向量
%   举个栗子：
%   IMAGES(:,:,6)是一个包含第6张图片的512*512的向量，
%   输入“imagesc(IMAGES(:,:,6)),colormap gray;”能显示出该图片。
%   图片对比度比较低，因为图片经过了白化预处理，教程笔记中有关于白化的更多细节
%   第二个栗子：
%   IMAGES(21:30,21:30,1)是第1张图片里从像素点(21,21)到(30,30)的像素块组成的图像片

%%
for imageNum = 1:10 % 在每张图片中选取1000个patch，共10000个patch
[rowNum, colNum] = size(IMAGES(:, :, imageNum)); % 返回每张图片的尺寸，保存在rowNum和colNum中
for patchNum = 1:1000 % 每个patch的尺寸为8*8
xPos = randi([1, rowNum-patchsize+1]); % 设置xPos为1和图像最大行数之间的一个随机数
yPos = randi([1, colNum-patchsize+1]); % 设置yPos为1和图像最大列数之间的一个随机数
patches(:, (imageNum-1)*1000+patchNum) =  reshape(IMAGES(xPos:xPos+7, yPos:yPos+7, imageNum), 64, 1);
% reshape将提取出的8*8的图像变形为64*1的列向量
% patches选中矩阵patches相应的列放入64*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


% 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"). 隐藏层期望激活度，在教程中用rho表示
% beta: weight of sparsity penalty term 稀疏性惩罚项的权重，在教程中用beta表示
% 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).
% 输入的theta是向量
% theta是由所有参数组合起来的一个s1*s2+s2*s3+s2+s3维的向量
% 之所以要将参数转换成这样的格式，是因为要满足minFunc函数的参数

% We first convert theta to the (W1, W2, b1, b2) matrix/vector format, so that this
% follows the notation convention（记符惯例） of the lecture notes.
% 我们先将theta转换为(W1,W2,b1,b2)的矩阵/向量格式，符合教程笔记的记符惯例

W1 = reshape(theta(1:hiddenSize*visibleSize), hiddenSize, visibleSize);
% 将theta中第1到第s1*s2个元素变形组合成s2*s1维的矩阵，变形时使用向量按列开始填充
W2 = reshape(theta(hiddenSize*visibleSize+1:2*hiddenSize*visibleSize), visibleSize, hiddenSize);
% 将第s1*s2+1到第2*s2*s3个元素变形组合成s3*s3维矩阵，这里有s1=s3
b1 = theta(2*hiddenSize*visibleSize+1:2*hiddenSize*visibleSize+hiddenSize);
% 类似上面，初始化输入层偏置项向量b1
b2 = theta(2*hiddenSize*visibleSize+hiddenSize+1:end);
% 初始化第二层偏置项向量b2

% Cost and gradient variables (your code needs to compute these values).
% Here, we initialize them to zeros.
cost = 0; % 将代价值初始化为0

%% ---------- YOUR CODE HERE --------------------------------------
%  Instructions: Compute the cost/optimization objective J_sparse(W,b) for the Sparse Autoencoder,
%
% 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
%
% 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.
%

%%
%
%注释译文
%
% 参见课件Section2.2最后一块的伪代码
% 换句话说，如果我们使用批量梯度下降法去最小化参数，
%

% J_sparse(W,b)共有三项
Jcost = 0; % 样本均方误差项
Jweight = 0; % 权重衰减项
Jsparse = 0; % 稀疏性惩罚项
[n m] = size(data); % n表示样本特征数，m表示样本个数

% 前向算法计算各神经网络节点的线性组合值和active值
z2 = W1*data + repmat(b1, 1, m); % 第二层输入值，即隐藏层中各节点输入值矩阵，repmat函数将矩阵进行重复并组合起来
a2 = sigmoid(z2); % 第二层输出值（激活值），注意sigmoid函数在本文件164行定义
z3 = W2*a2 + repmat(b2, 1, m); % 第三层输入值
a3 = sigmoid(z3); % 输出层各节点输出值（激活值）矩阵

% 计算样本均方误差项
Jcost = (0.5/m)*sum(sum((a3-data).^2));

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

% 计算稀疏性惩罚项
rho = (1/m).*sum(a2, 2); % 求出教程中的rho，即隐藏层（第二层）神经元的平均活跃度，
% 在训练集上取隐藏层每个节点输出值的平均
Jsparse = sum(sparsityParam .* log(sparsityParam ./ rho) + ...
(1-sparsityParam) .* log((1-sparsityParam) ./ (1 - rho )));

% 代价函数总表达式
cost = Jcost+lambda*Jweight+beta*Jsparse;

% 计算残差
d3 = -(data-a3).*sigmoidInv(z3); % 输出层（第三层）残差，sigmoidInv为sigmoid导数，在第170行有定义
sterm = beta*(-sparsityParam./rho+(1-sparsityParam)./(1-rho)); % 隐藏层稀疏性规则项
d2 = (W2'*d3+repmat(sterm, 1, m)).*sigmoidInv(z2); % 隐藏层（第二层）残差，计算时要加入稀疏性规则项

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

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)).

% 定义sigmoid函数
function sigm = sigmoid(x)

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

% sigmoid函数求导
function sigmInv = sigmoidInv(x)

sigmInv = sigmoid(x).*(1-sigmoid(x));
end

% computeNumericalGradient.m
% theta: a vector of parameters
% J: a function that outputs a real-number. Calling y = J(theta) will return the
% function value at theta.

%% ---------- YOUR CODE HERE --------------------------------------
% Instructions:
% (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.

%% 注释译文
% 指导：
% （查看课程笔记的Section 2.3）
%