h叫乌鸦的少年 2021-12-21 21:57 采纳率: 62.5%
浏览 36
已结题

用matlab卷积神经网络遇到的问题——gpu和cpu的结果不一样,最后的预测结果也有问题

用官方的帮助文档的程序识别手写数字集test里面的图片

以下是代码:

clc;clear;close all;
digitDatasetPath = fullfile('C:\Users\86151\Desktop\mnist_data_jpg\新建文件夹');
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
% % splitEachLabel 将 digitData 中的图像文件拆分为两个新的数据存储,imdsTrain 和 imdsTest。
numTrainingFiles = 750;
[imdsTrain,imdsTest] = splitEachLabel(imds,numTrainingFiles,'randomize');

% % 定义卷积神经网络架构。
layers = [ ...
    imageInputLayer([28 28 1])
    convolution2dLayer(5,20)
    reluLayer
    maxPooling2dLayer(2,'Stride',2)
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];
% % 将选项设置为具有动量的随机梯度下降的默认设置。 将最大 epoch 数设置为 20,并以 0.0001 的初始学习率开始训练。
options = trainingOptions('sgdm', ...
    'MaxEpochs',20,...
    'InitialLearnRate',1e-4, ...
    'Verbose',false, ...
    'ExecutionEnvironment','cpu',...
    'Plots','training-progress');
% % 训练网络
net = trainNetwork(imdsTrain,layers,options);
save('CNNshuzi','net');%保存训练好的神经网络
% % 在未用于训练网络的测试集上运行经过训练的网络,并预测图像标签(数字)。
YPred = classify(net,imdsTest);
YTest = imdsTest.Labels;
% % 计算精度。 准确率是测试数据中与分类匹配的真实标签数量与测试数据中图像数量的比值。
accuracy = sum(YPred == YTest)/numel(YTest)

这是分别用GPU和CPU训练的过程

img

img

还有就是最后预测精度那里每次准确率accuracy都是百分之十几,YPred里面的标签都是1,明明训练的时候验证的正确率都很高

img

img

最后写了一个测试的程序,基本也都能识别出来



clc;clear
%%Load the train model
load('CNNshuzi','net');
%%See details of the architecture
net.Layers
%%Read the image to classify
[file,path]=uigetfile('*');
image=fullfile(path,file);
I=imresize(imread(image),[28,28]);
file


tic
%Adjust size of the image
sz=net.Layers(1).InputSize;
%I=I(1:sz(1),1:sz(2),1:sz(3));

%Classify the image 
label = classify(net,I)
%Show the image and the classification results
figure('Name','识别结果','NumberTitle','off');
imshow(I);

title(['\bf',label]),xlabel(['\bf',label]);

img

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月29日
    • 修改了问题 12月21日
    • 修改了问题 12月21日
    • 修改了问题 12月21日
    • 展开全部

    悬赏问题

    • ¥15 Questasim Error: (vcom-13)
    • ¥15 船舶旋回实验matlab
    • ¥30 SQL 数组,游标,递归覆盖原值
    • ¥15 为什么我的数据接收的那么慢呀有没有完整的 hal 库并 代码呀有的话能不能发我一份并且我用 printf 函数显示处理之后的数据,用 debug 就不能运行了呢
    • ¥15 有关于推荐系统jupyter
    • ¥20 gitlab 中文路径,无法下载
    • ¥15 用动态规划算法均分纸牌
    • ¥30 udp socket,bind 0.0.0.0 ,如何自动选取用户访问的服务器IP来回复数据
    • ¥15 关于树的路径求解问题
    • ¥15 yolo在训练时候出现File "D:\yolo\yolov5-7.0\train.py"line 638,in <module>