Train Stacked Autoencoders for Image Classification
[train_x, train_y] = digitTrainCellArrayData;
% 并随机选择显示 100 副图像,
n = 100;
idx = randi([1, size(train_x, 2)], n);
for i=1:n
subplot(10, 10, i), imshow(train_x{idx(i)});
end
简单起见,这里仅给出一个具有一个单隐层(隐层的神经元节点数为 100)的堆栈式自编码器,
rng('default');
num_hid1 = 100;
% 因为是自编码器,也属于无监督学习算法,因此不需要目标值 train_y 的参与
ae1 = trainAutoencoder(train_x, num_hid1, ...
'MaxEpochs', 400, ...
'L2WeightRegularization', .004, ...
'SparsityRegularization', 4, ...
'SparsityProportion', .15, ...
'ScaleData', false);
定义网络拓扑结构的过程,也是训练的过程。
view(ae1)
plotWeights(ae1)
% 使用第一个自编码器得到其对应的压缩编码,
feat1 = encode(ae1, train_x);
num_hid2 = 50;
ae2 = trainAutoencoder(feat1, num_hid2, ...
'MaxEpochs', 100, ...
'L2WeightRegularization', .002, ...
'SparsityRegularization', 4, ...
'SparsityPropotion', .1, ...
'ScaleData', false);
view(ae2);
% 使用第二个自编码器得到其对应的压缩编码
feat2 = encode(ae2, feat1);
softnet = trainSoftmaxLayer(feat2, train_y, 'MaxEpochs', 400);
view(softnet)
deepnet = stack(ae1, ae2, softnet);
view(deepnet)