MATLAB实现神经网络的OCR识别

使用说明:

  1. 运行要求‌:

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

    • 使用MATLAB自带的MNIST手写数字数据集
    • 包含数据可视化、网络架构、训练曲线和混淆矩阵
    • 最终测试准确率可达约98%
    • 包含单张图片预测演示
Matlab 复制代码
%% 神经网络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:20
    subplot(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:20
    subplot(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))])
相关推荐
卧式纯绿11 小时前
卷积神经网络基础(九)
人工智能·python·深度学习·神经网络·机器学习·cnn
LetsonH11 小时前
PyTorch Geometric(PyG):基于PyTorch的图神经网络(GNN)开发框架
人工智能·pytorch·神经网络
C+ 安口木18 小时前
纯前端实现图文识别 OCR
前端·javascript·ocr
烦恼归林19 小时前
永磁同步电机高性能控制算法(22)——基于神经网络的转矩脉动抑制算法&为什么低速时的转速波动大?
人工智能·神经网络·电机·电力电子·电机控制·simulink仿真
姜丝辣嘴19 小时前
Matlab简单优化模型应用
matlab
每天都要写算法(努力版)20 小时前
【神经网络与深度学习】GAN 生成对抗训练模型在实际训练中很容易判别器收敛,生成器发散
深度学习·神经网络·生成对抗网络
zzc92120 小时前
怎么用Origin画出MATLAB效果的3D时频图
开发语言·matlab
IoT小趴菜20 小时前
电脑A和电脑B都无法ping通电脑C网络,电脑C可以ping通电脑A和B,使用新系统测试正常,排除硬件问题。
神经网络·计算机网络·电脑
Vizio<21 小时前
基于MNIST数据集的手写数字识别(CNN)
人工智能·笔记·深度学习·神经网络·cnn
Mr.Winter`1 天前
深度强化学习 | 基于SAC算法的移动机器人路径跟踪(附Pytorch实现)
人工智能·pytorch·深度学习·神经网络·机器人·自动驾驶·ros