DeepLearningtoolbox(2):cnnexample.m

来源:互联网 发布:matlab入门编程 编辑:程序博客网 时间:2024/06/06 17:31
clear all; close all; clc; load mnist_uint8;%导入数据集train_x = double(reshape(train_x',28,28,60000))/255; %使用MNIST数据集,将图像进行归一化test_x = double(reshape(test_x',28,28,10000))/255; %同理,将测试图像进行归一化 train_y=double(train_y'); %强制转换类型,为double型,大小为10*60000 test_y=double(test_y'); %大小为10*10000% 训练一个6c-2s-12c-2s形式的卷积神经网络rng(0)%rng(sd)用于生成随机数,这个地方为什么要有这个函数···留待···cnn.layers = {      struct('type', 'i') %input layer    struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer,输出6个特征图,卷积核的大小为5*5      struct('type', 's', 'scale', 2)%sub sampling layer,滑动窗口大小为2*2    struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer,输出12个特征图,卷积核的大小为5*5     struct('type', 's', 'scale', 2)%subsampling layer,滑动窗口大小为2*2};  % 这里把cnn的设置给cnnsetup,它会据此构建一个完整的CNN网络,并返回  cnn = cnnsetup(cnn, train_x, train_y);  % 学习率  opts.alpha = 0.1;  % 每次挑出一个batchsize的batch来训练,也就是每用batchsize个样本就调整一次权值,而不是  % 把所有样本都输入了,计算所有样本的误差了才调整一次权值  opts.batchsize = 50; % 训练次数,用同样的样本集  % 1的时候 11.41% error  % 5的时候 4.2% error  % 10的时候 2.73% error % 50的时候 1.89% erroropts.numepochs = 1; % 把训练样本给网络,开始训练这个CNN网络  cnn = cnntrain(cnn, train_x, train_y, opts);  %save CNN_5 cnn; % 用测试样本来测试  %load CNN_5 cnn;[er, bad] = cnntest(cnn, test_x, test_y); %输出均方误差figure,plot(cnn.rL);  %assert(er<0.12, 'Too big error');%画图显示disp([num2str(er*100) '% error']);
0 0