matlab实现CNN代码test_example_CNN_MNIST.m注释版

该代码是MATLAB环境下实现的CNN(卷积神经网络)用于MNIST手写数字识别的示例。通过加载和预处理MNIST数据集,设置CNN网络结构(包括输入层、卷积层、池化层),并配置训练参数,最终训练和测试模型,得到约11%的错误率。随着训练次数增加,错误率可以降低到1.2%左右。
摘要由CSDN通过智能技术生成


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率

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值