EUAdvancer

机器学习-自编码网络(Autoencoder)


最近在学习UFLDL的DL相关算法,因为以前写过BP神经网络,所以写自编码还是比较轻松的,因为自编码主要是增加了一个稀疏性参数。实现过程中当然不同于以往的BP,我这次不再是遍历数据集了,而是通过矢量化的运算了,所以运算速度还是很快的。这里我主要记录我的实现代码,对于算法细节我会简单的说一说,详细大家看讲义会更清楚

自编码网络

自编码网络是一种无监督学习,它让目标值等于输入值,然后进行BP训练,从而从输入数据中获取隐含着一些特定的结构,也就是发现输入数据中的这些相关性。

我们限定隐藏层中神经元个数少于输入层,自编码网络就会去学习输入数据的压缩表示。例如:输入x是10*10图片的像素灰度值,即x是100维向量。输入层大小n=100。我们令隐藏层大小 s_2=50 ,那么隐藏层的输出a2是一个50维向量,网络的输出层必须使用这个50维向量来重建100维的输入。即实现了数据压缩.

当然对于每一个一个输入x都是一个跟其它特征完全无关的独立同分布高斯随机变量,网络很难学习出一个有效的压缩,所以数据压缩的前提就是数据具有相关性,当然我们现在的图片,语音等都是具有这个特点的

稀疏性限制

同样对于隐藏层神经元比较多的网络(甚至比输入x个数还多),为了保证网络同样能数据压缩,自编码网络为隐藏层加入了稀疏性限制

稀疏性可以被简单地解释如下。如果当神经元的输出接近于1的时候我们认为它被激活,而输出接近于0的时候认为它被抑制,那么使得神经元大部分的时间都是被抑制的限制则被称作稀疏性限制

我们以所有训练样本在某一神经元的的激活度的平均值作为该神经元的激活度,所以我们得到以下公式

为了保证大部分神经元被抑制,所以我们增加一个稀疏性参数rho,通常是一个接近于0的较小的值,我们希望能将每个神经元的激活度尽量接近稀疏性参数rho

为了得到这一效果,我们在优化目标函数(代价函数)中加入一个额外的惩罚因子

这个函数效果就是当神经元平均激活度靠近稀疏性参数rho时,惩罚值比较小,最小值为0,而当它们相距很远时,则惩罚值会很大。比如稀疏性rho=0.2时

具体实现步骤

自编码网络的实现基本和BP神经网络类似,主要步骤在于反向传播算法

  1. 首先进行前向传播,对每一层网络,我们都计算它的输入加权和以及激活值

  2. 对输出层,计算残差

  3. 对于隐藏层,计算残差。 注意这里,不同于BP神经网络的公式,这里还要额外计算一项

  4. 对于每个数据,我们都计算它的偏导项(如果是矢量化编程,其实4,5步是可以合在一起的计算的)

  5. 将所有数据的偏导项都加起来,对于W权重我们还要增加一项

    W =

    B =

另:因为在计算残差时我们会需要计算每个神经元的平均激活度,所以我们在反向传播算法前需要先前向遍历从而获取平均激活度,而如果我们不使用矢量化编程,在反向传播过程中我们还需要对每一个样本进行一次前向传播,所以速度会比较慢(当然当训练样本特别大以至于内存不够时也只能这样做)

同时无论是用于优化算法还是可视化梯度下降效果我们都需要计算代价函数,公式如下

对于自编码网络就是多了第三个公式的惩罚因子(从公式可以看出我们在前向传播结束就可以计算代价函数了)

代码

练习主要分以下几步

  1. 从10张512*512的图片中,随机选择10000张8x8的小图块,并进行归一化,得到训练集patches作为训练集
  2. 计算整个网络的偏导项(用于梯度下降或L-BFGS)和代价函数 Jsparse(W,b)【算法核心部分】
  3. 梯度检测(注意,在检测算法正确后注释该代码,而在调试过程中,可以先将隐藏层神经元个数调整到1-2个,输入x样本10个左右即可)
    • checkNumericalGradient.m这个函数会首先检查你写的梯度检测是否正确,然后你再用梯度检测检查你的反向传播算法
  4. 用L-BFGS算法训练自编码网络(算法不用自己实现)
  5. 可视化权值W1,可以看到自编码网络获取到了哪些特征

sampleIMAGES.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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
index = 1;
for i=1:10
[row, col] = size(IMAGES(:, :, i));
for j=1:1000
xPos = randi([1, row - patchsize + 1]);
yPos = randi([1, col - patchsize + 1]);
patches(:, index) = reshape(IMAGES(xPos:xPos + 7, yPos:yPos + 7, i), 64, 1);
index = index + 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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.
%

% m为数据集个数
% 64 * 10000
[n, m] = size(data);

% 前向传播算法
% 偏置结点等于输出+1,所以为每个隐藏层结点输出加1
% 25 * 10000(b1 = 25 * 1)
z2 = W1 * data + repmat(b1, 1, m);
a2 = sigmoid(z2);
% 64 * 10000(b2 = 64 * 1)
z3 = W2 * a2 + repmat(b2, 1, m);
a3 = sigmoid(z3);

% 计算代价函数
Jcost = sum(sum((a3 - data) .^ 2) ./ 2) / m;
Jweight = lambda / 2 * (sum(sum(W1 .^ 2)) + sum(sum(W2 .^ 2)));
% 25 * 1
rho = sum(a2, 2) ./ m;
Jsparse = beta * sum(sparsityParam * log(sparsityParam ./ rho) + (1 - sparsityParam) * log((1 - sparsityParam) ./ (1 - rho)));
cost = Jcost + Jweight + Jsparse;

% 反向传播算法
% 64 * 10000
delta3 = -(data - a3) .* sigmoidInv(z3);
% 25 * 1
delta2_sparse = beta * (-sparsityParam ./ rho + (1 - sparsityParam) ./ (1 - rho));
% 25 * 10000
delta2 = (W2' * delta3 + repmat(delta2_sparse, 1, m)) .* sigmoidInv(z2);

%计算W_Gred, B_Gred
% 25 * 64
W1grad = delta2 * data' ./ m + lambda * W1;
% 25 * 1
b1grad = sum(delta2, 2) ./ m;
% 64 * 25
W2grad = delta3 * a2' ./ m + lambda * W2;
% 64 * 1
b2grad = sum(delta3, 2) ./ m;


%-------------------------------------------------------------------
% 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


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

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

computeNumericalGradient.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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;
for i=1:size(theta)
theta_plus = theta;
theta_minu = theta;
theta_plus(i) = theta_plus(i) + epsilon;
theta_minu(i) = theta_minu(i) - epsilon;
numgrad(i) = (J(theta_plus) - J(theta_minu)) / (2 * epsilon);
end


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

效果

这样的结果应该是正确的(具体你可以看看练习结尾部分的正确图片和一系列错误图片)

结语

尽管之前写过BP神经网络,但是写自编码网络还是用了很长时间,特别是调试过程很需要耐心,毕竟矢量化实现公式总有出错的可能性。好好调试过程喽!哈哈!