当前位置: 首页 > news >正文

MATLAB实现神经网络的OCR识别

使用说明:

  1. 运行要求‌:

    • MATLAB R2020b 或更新版本
    • 已安装 Deep Learning Toolbox
    • 推荐使用GPU加速(训练时在代码开头添加 gpuDevice(1)
  2. 代码特点‌:

    • 使用MATLAB自带的MNIST手写数字数据集
    • 包含数据可视化、网络架构、训练曲线和混淆矩阵
    • 最终测试准确率可达约98%
    • 包含单张图片预测演示

 

%% 神经网络OCR识别示例(MATLAB 2020b及以上版本)
% 需要安装 Deep Learning Toolbox%% 步骤1:加载和预处理数据
clc; clear; close all% 加载MATLAB自带的手写数字数据集
digitDatasetPath = fullfile(matlabroot, 'toolbox', 'nnet', 'nndemos', ...'nndatasets', 'DigitDataset');
imds = imageDatastore(digitDatasetPath, ...'IncludeSubfolders', true, 'LabelSource', 'foldernames');% 显示部分样本
figure
numImages = 10000;
perm = randperm(numImages, 20);
for i = 1:20subplot(4,5,i);imshow(imds.Files{perm(i)});
end% 分割数据集(70%训练,30%测试)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.7, 'randomized');%% 步骤2:构建神经网络
inputSize = [28 28 1]; % 输入图像尺寸layers = [imageInputLayer(inputSize, 'Name', 'input')   % 输入层convolution2dLayer(3, 16, 'Padding', 'same', 'Name', 'conv1') % 卷积层batchNormalizationLayer('Name', 'bn1')reluLayer('Name', 'relu1')maxPooling2dLayer(2, 'Stride', 2, 'Name', 'maxpool1') % 池化层convolution2dLayer(3, 32, 'Padding', 'same', 'Name', 'conv2')batchNormalizationLayer('Name', 'bn2')reluLayer('Name', 'relu2')fullyConnectedLayer(10, 'Name', 'fc')          % 全连接层softmaxLayer('Name', 'softmax')               % 分类层classificationLayer('Name', 'classification')];%% 步骤3:设置训练参数
options = trainingOptions('adam', ...'InitialLearnRate', 0.001, ...'MaxEpochs', 10, ...'Shuffle', 'every-epoch', ...'ValidationData', imdsTest, ...'ValidationFrequency', 30, ...'Verbose', true, ...'Plots', 'training-progress');%% 步骤4:调整图像大小并训练网络
augimdsTrain = augmentedImageDatastore(inputSize(1:2), imdsTrain);
augimdsTest = augmentedImageDatastore(inputSize(1:2), imdsTest);net = trainNetwork(augimdsTrain, layers, options);%% 步骤5:测试网络性能
[YPred, probs] = classify(net, augimdsTest);
accuracy = mean(YPred == imdsTest.Labels);
disp(['测试准确率: ', num2str(accuracy*100), '%'])% 显示混淆矩阵
figure
confusionchart(imdsTest.Labels, YPred)%% 步骤6:单张图片测试示例
% 随机选取测试集中的一个图像
testImage = readimage(imdsTest, randi(numel(imdsTest.Files)));% 预处理并预测
inputImg = imresize(testImage, inputSize(1:2));
[result, scores] = classify(net, inputImg);% 显示结果
figure
imshow(testImage)
title(['预测结果: ' char(result), '  真实标签: ' char(imdsTest.Labels(1))])
%% 神经网络OCR识别示例(MATLAB 2020b及以上版本)
% 需要安装 Deep Learning Toolbox%% 步骤1:加载和预处理数据
clc; clear; close all% 加载MATLAB自带的手写数字数据集
digitDatasetPath = fullfile(matlabroot, 'toolbox', 'nnet', 'nndemos', ...'nndatasets', 'DigitDataset');
imds = imageDatastore(digitDatasetPath, ...'IncludeSubfolders', true, 'LabelSource', 'foldernames');% 显示部分样本
figure
numImages = 10000;
perm = randperm(numImages, 20);
for i = 1:20subplot(4,5,i);imshow(imds.Files{perm(i)});
end% 分割数据集(70%训练,30%测试)
[imdsTrain, imdsTest] = splitEachLabel(imds, 0.7, 'randomized');%% 步骤2:构建神经网络
inputSize = [28 28 1]; % 输入图像尺寸layers = [imageInputLayer(inputSize, 'Name', 'input')   % 输入层convolution2dLayer(3, 16, 'Padding', 'same', 'Name', 'conv1') % 卷积层batchNormalizationLayer('Name', 'bn1')reluLayer('Name', 'relu1')maxPooling2dLayer(2, 'Stride', 2, 'Name', 'maxpool1') % 池化层convolution2dLayer(3, 32, 'Padding', 'same', 'Name', 'conv2')batchNormalizationLayer('Name', 'bn2')reluLayer('Name', 'relu2')fullyConnectedLayer(10, 'Name', 'fc')          % 全连接层softmaxLayer('Name', 'softmax')               % 分类层classificationLayer('Name', 'classification')];%% 步骤3:设置训练参数
options = trainingOptions('adam', ...'InitialLearnRate', 0.001, ...'MaxEpochs', 10, ...'Shuffle', 'every-epoch', ...'ValidationData', imdsTest, ...'ValidationFrequency', 30, ...'Verbose', true, ...'Plots', 'training-progress');%% 步骤4:调整图像大小并训练网络
augimdsTrain = augmentedImageDatastore(inputSize(1:2), imdsTrain);
augimdsTest = augmentedImageDatastore(inputSize(1:2), imdsTest);net = trainNetwork(augimdsTrain, layers, options);%% 步骤5:测试网络性能
[YPred, probs] = classify(net, augimdsTest);
accuracy = mean(YPred == imdsTest.Labels);
disp(['测试准确率: ', num2str(accuracy*100), '%'])% 显示混淆矩阵
figure
confusionchart(imdsTest.Labels, YPred)%% 步骤6:单张图片测试示例
% 随机选取测试集中的一个图像
testImage = readimage(imdsTest, randi(numel(imdsTest.Files)));% 预处理并预测
inputImg = imresize(testImage, inputSize(1:2));
[result, scores] = classify(net, inputImg);% 显示结果
figure
imshow(testImage)
title(['预测结果: ' char(result), '  真实标签: ' char(imdsTest.Labels(1))])

 

 

相关文章:

  • Web 基础与 HTTP 协议
  • STM32的SysTick
  • 学成在线。。。
  • 【爬虫】码上爬第2题:headersi请求头验证
  • 排序算法详解笔记
  • 详解UnityWebRequest类
  • Day15(贪心算法)——LeetCode121.买卖股票的最佳时机55.跳跃游戏
  • 文献阅读(一)植物应对干旱的生理学反应 | The physiology of plant responses to drought
  • 机器学习基础理论 - 目标函数,损失函数,代价函数
  • C++入门(namespace/输入输出)
  • docker存储
  • 23.C语言指针相关知识点2
  • C++代码随想录刷题知识分享-----面试题链表相交
  • 传统农耕展陈如何突破?数字多媒体能否重构文化体验边界?
  • 阿里云ftp服务器登录要怎么做?如何访问ftp服务器?
  • 记录一下QA(from deepseek)
  • 开发vue项目所需要安装的依赖包
  • Redis ⑦-set | Zset
  • Leetcode刷题 | Day49_图论01
  • 《冰雪传奇点卡版》:详细打金攻略!
  • 我国将出台稳就业稳经济推动高质量发展若干举措,将根据形势变化及时出台增量储备政策
  • 利物浦提前四轮英超夺冠,顶级联赛冠军数追平曼联
  • 商务部:将积极会同相关部门加快推进离境退税政策的落实落地
  • 2025年上海空间信息大会举行,重大项目集中签约
  • 手机号旧机主信用卡欠款、新机主被催收骚扰四年,光大银行济南分行回应
  • 生于1987年,万宏宇已任内蒙古鄂温克旗委常委