function test_example_CNN
addpath(‘CNN/’);
load mnist_uint8;
train_x = double(reshape(train_x’,28,28,60000))/255;%训练集使用minist数据,将图像进行归一化,图像大小28*28,总共60000张图像,除以255是将图像的像素值规约到0-1的范围内
test_x = double(reshape(test_x’,28,28,10000))/255;%将测试图像进行归一化
train_y = double(train_y’);%强制类型转换,转换为double型,训练标签大小为10*60000,因为数据集为手写体数字,总共有10类,60000张图像
test_y = double(test_y’);%测试集标签,大小为10*10000,共有10000张图像为测试集
%% ex1 Train a 6c-2s-12c-2s Convolutional neural network
%will run 1 epoch in about 200 second and get around 11% error.
%With 100 epochs you’ll get around 1.2% error
rand(‘state’,0)
cnn.layers = {
struct(‘type’, ‘i’) %input layer
struct(‘type’, ‘c’, ‘outputmaps’, 6, ‘kernelsize’, 5) %convolution layer,outputmaps卷积核个数6,kenelsize卷积核大小5*5
struct(‘type’, ‘s’, ‘scale’, 2) %sub sampling layer,scale滑动窗口大小2*2
struct(‘type’, ‘c’, ‘outputmaps’, 12, ‘kernelsize’, 5) %convolution layer,outputmaps卷积核个数6,kenelsize卷积核大小5*5
struct(‘type’, ‘s’, ‘scale’, 2) %subsampling layer
};
opts.alpha = 0.1;%学习率
%每次挑出一个batchsize(一批数据的大小)的batch(一批数据)来训练,也就是每用batchsize个样本就调整一次权值
opts.batchsize = 50;%每批数据的样本数
opts.numepochs = 2;%迭代次数
cnn = cnnsetup(cnn, train_x, train_y);%这里把cnn的设置给cnnsetup
cnn = cnntrain(cnn, train_x, train_y, opts);%训练cnn
[er, bad] = cnntest(cnn, test_x, test_y);%用测试样本进行测试
%plot mean squared error,输出均方误差图
figure; plot(cnn.rL);
%assert(er<0.12, ‘Too big error’);%断言函数,在程序中确保某些条件成立,否则调用系统error函数终止运行。
disp([num2str(er*100) ‘%error’]);%画图显示error率