用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训练的过程

在这里插入图片描述

在这里插入图片描述

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

在这里插入图片描述

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



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]);


在这里插入图片描述

2021年12月22日
是GPU版本的问题。重新下了一个matlab2021的,使用cpu训练就没有出现问题了。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43666228/article/details/122074432