目录
数据集:
实验代码:alexnet版
如果你的matlab不是正版,先看这里:
数据集结构:
训练代码:
训练结果:
图形界面:
界面展示:
其他:
输出结果:
实验思路是使用预训练神经网络对图片进行特征提取,然后再使用SVM对得到的特征进行处理。
写完后试过基于形态学分类,可能是数据集的原因,用了面积、周长、最小外接矩形的长和宽、离心率、灰度均值、HSV均值,方差等作为特征,结果并不理想。
用的matlab2021a,老师那要的(没法发安装包,只能线下找我)低版本不确定能用。
数据集:
自己搞得,不太行,还是建议你用其他的网上数据集
实验代码:alexnet版
如果你的matlab不是正版,先看这里:
如果你的matlab不是正版,无法下载Deep Learning Toolbox Model for AlexNet Network来获得已经训练好的神经网络可以去官网下载,或者在我这花1积分下载Deep Learning Toolbox Model for AlexNet Network - File Exchange - MATLAB CentralDownload and share free MATLAB code, including functions, models, apps, support packages and toolboxeshttps://ww2.mathworks.cn/matlabcentral/fileexchange/59133-deep-learning-toolbox-model-for-alexnet-network?s_tid=ta_fx_results
如果是在b站上下载的2022版有可能会崩溃,提前做好心理准备(偶然现象)
下载完后(如果是压缩包的话先解压),将安装包拖进matlab的工作目录
然后双击工作目录里的这个安装包来运行它,会弹出这个界面
按提示操作
输入完毕后验证电子邮件
设置密码
就开始下载了
下载完就能用已经训练好的alexnet了
数据集结构:
数据集下载 我这个数据集很一般,建议从网上找数据集
apple数据集,里面的每个文件夹是一个类别(名字随便写,不过最好不是中文),图片是哪一种就放在那个文件夹里
训练代码:
file是数据集所在文件夹
训练完会有提示,让你选择保存不保存数据集
报错说alexnet什么的看上面-------如果你的matlab不是正版
clc;
clear;
file = 'D:/apple';
% 读取file中所有图片,以文件夹名作为标签
appleData = imageDatastore(file, 'IncludeSubfolders', true, 'LabelSource', 'foldernames')
% 调整大小适应后来的AlexNet模型输入
appleData.ReadFcn = @(x) imresize(imread(x), [227 227]);
% 划分测试集训练集,会打乱
[trainImds, testImds] = splitEachLabel(appleData, 0.8, 'randomized');
net = alexnet;% 加载AlexNet模型
% 特征提取
% 使用activations函数对训练集和测试集的图像进行特征提取
% 输出第七层的特征
featuresTrain = activations(net, trainImds, 'fc7', 'OutputAs', 'rows');
featuresTest = activations(net, testImds, 'fc7', 'OutputAs', 'rows');
fprintf('开始训练');
% 训练SVM,fitcecoc任数训练SVM分类器
svmModel = fitcecoc(featuresTrain,trainImds.Labels);
% 在测试集计算准确率
fprintf('预测值:');
predictedLabels = predict(svmModel, featuresTest);
fprintf('真实值:');
testImds.Labels
fprintf('正确率:');
accuracy = mean(predictedLabels == testImds.Labels)
x = input('是否保存svmModel已训练模型(y/n)',"s") ;
if(x=='y')save svm_Model svmModelfprintf('模型已保存到svm_Model.mat')
end
训练结果:
appleData = ImageDatastore - 属性:Files: {'D:\apple\1\1.jpeg';'D:\apple\1\1.jpg';'D:\apple\1\10.jpg'... and 197 more}Folders: {'D:\apple'}Labels: [1; 1; 1 ... and 197 more categorical]AlternateFileSystemRoots: {}ReadSize: 1SupportedOutputFormats: ["png" "jpg" "jpeg" "tif" "tiff"]DefaultOutputFormat: "png"ReadFcn: @readDatastoreImage开始训练预测值:真实值:
ans = 41×1 categorical 数组1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 3 3 正确率:
accuracy =0.9512是否保存svmModel已训练模型(y/n)y
模型已保存到svm_Model.mat>>
图形界面:
用matlab自带的设计app做的
我主要就写了一个按钮的回调,一定要记着保存SVM模型后再用,没做读取错误报错。
classdef apple < matlab.apps.AppBase% Properties that correspond to app componentsproperties (Access = public)UIFigure matlab.ui.FigureEditField_2 matlab.ui.control.EditFieldEditField_2Label matlab.ui.control.LabelEditField matlab.ui.control.EditFieldLabel matlab.ui.control.LabelImage matlab.ui.control.ImageButton matlab.ui.control.Buttonend% Callbacks that handle component eventsmethods (Access = private)% Button pushed function: Buttonfunction ButtonPushed(app, event)global svmModel net;% 模型% 如果没有模型,加载模型if(exist('svmModel','var')&&exist('net','var'))net = alexnet;% 加载AlexNet模型load svm_Model svmModel% 加载已训练模型end% 打开文件对话框 禁止多选[file,path]=uigetfile('*.*',' Multiselect ' ,'off');if(file==0) % 没读文件returnend% 更改路径文本file = [path,file];app.EditField.Value = file;app.Image.ImageSource = imread(file);% 更改图像显示% 创建需要读取特征的数据appleData = imageDatastore(file);% 调整大小适应后来的AlexNet模型输入appleData.ReadFcn = @(x) imresize(imread(x), [227 227]);appleData = activations(net, appleData, 'fc7', 'OutputAs', 'rows');Labels = predict(svmModel, appleData);app.EditField_2.Value = string(Labels);endend% Component initializationmethods (Access = private)% Create UIFigure and componentsfunction createComponents(app)% Create UIFigure and hide until all components are createdapp.UIFigure = uifigure('Visible', 'off');app.UIFigure.Position = [100 100 415 393];app.UIFigure.Name = 'MATLAB App';% Create Buttonapp.Button = uibutton(app.UIFigure, 'push');app.Button.ButtonPushedFcn = createCallbackFcn(app, @ButtonPushed, true);app.Button.FontSize = 20;app.Button.Position = [36 21 100 34];app.Button.Text = '选择文件';% Create Imageapp.Image = uiimage(app.UIFigure);app.Image.Position = [86 134 237 237];% Create Labelapp.Label = uilabel(app.UIFigure);app.Label.HorizontalAlignment = 'right';app.Label.FontSize = 20;app.Label.Position = [23 68 125 26];app.Label.Text = '图片文件路径';% Create EditFieldapp.EditField = uieditfield(app.UIFigure, 'text');app.EditField.Editable = 'off';app.EditField.Position = [157 61 230 36];% Create EditField_2Labelapp.EditField_2Label = uilabel(app.UIFigure);app.EditField_2Label.HorizontalAlignment = 'right';app.EditField_2Label.FontSize = 20;app.EditField_2Label.Position = [209 22 65 26];app.EditField_2Label.Text = '级别:';% Create EditField_2app.EditField_2 = uieditfield(app.UIFigure, 'text');app.EditField_2.Editable = 'off';app.EditField_2.Position = [273 23 50 24];% Show the figure after all components are createdapp.UIFigure.Visible = 'on';endend% App creation and deletionmethods (Access = public)% Construct appfunction app = apple% Create UIFigure and componentscreateComponents(app)% Register the app with App DesignerregisterApp(app, app.UIFigure)if nargout == 0clear appendend% Code that executes before app deletionfunction delete(app)% Delete UIFigure when app is deleteddelete(app.UIFigure)endend
end
界面展示:
其他:
如果觉着一个网络不好的话,这里还有一种操作:
或者你们还可以使用 Adaboost
Adaboost是一种迭代算法,其核心思想是针对同一个训练集训练不同的分类器(弱分类器),然后把这些弱分类器集合起来,构成一个更强的最终分类器(强分类器)。
这几个网络都可以再之前的官网下载
clc;
clear;
file = 'D:/apple';
% 读取file中所有图片,以文件夹名作为标签
appleData = imageDatastore(file, 'IncludeSubfolders', true, 'LabelSource', 'foldernames')
% 调整大小适应后来的AlexNet模型输入
appleData.ReadFcn = @(x) imresize(imread(x), [227 227]);
% 划分测试集训练集,会打乱
[trainImds, testImds] = splitEachLabel(appleData, 0.8, 'randomized');
fprintf("\n开始加载预训练模型");
net1 = alexnet;% 加载预训练模型
net2 = vgg16;
net3 = resnet18;
% 特征提取
% 使用activations函数对训练集和测试集的图像进行特征提取
% alexnet,他有8层神经网络,
% 其中前5层是卷积层,后3层是全连接层。其中fc7层是全连接层的第2个,它包含4096个神经元
% 该层可以提取图像的高级语义特征,这些特征已经经过多次卷积和池化操作,
% 能够捕捉到图像的基本形状和纹理信息,同时又不会过于抽象
% 输出第七层的特征,按行输出,
fprintf("\n开始使用预训练模型提取特征");
featuresTrain1 = activations(net1, trainImds, 'fc7', 'OutputAs', 'channels');
featuresTrain2 = activations(net2, trainImds, 'fc7', 'OutputAs', 'channels');
featuresTrain3 = activations(net3, trainImds, 'pool5', 'OutputAs', 'channels');
fprintf("\n已经提取训练集特征提取特征");
featuresTest1 = activations(net1, testImds, 'fc7', 'OutputAs', 'channels');
featuresTest2 = activations(net2, testImds, 'fc7', 'OutputAs', 'channels');
featuresTest3 = activations(net3, testImds, 'pool5', 'OutputAs', 'channels');
fprintf("\n已经提取测试集特征提取特征");
featuresTrain1 = reshape(featuresTrain1, [], size(featuresTrain1, 4))';
featuresTrain2 = reshape(featuresTrain2, [], size(featuresTrain2, 4))';
featuresTrain3 = reshape(featuresTrain3, [], size(featuresTrain3, 4))';
featuresTest1 = reshape(featuresTest1, [], size(featuresTest1, 4))';
featuresTest2 = reshape(featuresTest2, [], size(featuresTest2, 4))';
featuresTest3 = reshape(featuresTest3, [], size(featuresTest3, 4))';
fprintf('\n开始训练');
% 训练SVM,fitcecoc任数训练SVM分类器
svmModel_1 = fitcecoc(featuresTrain1,trainImds.Labels);
svmModel_2 = fitcecoc(featuresTrain2,trainImds.Labels);
svmModel_3 = fitcecoc(featuresTrain3,trainImds.Labels);
% 在测试集计算准确率
predictedLabels1 = predict(svmModel_1, featuresTest1);
predictedLabels2 = predict(svmModel_2, featuresTest2);
predictedLabels3 = predict(svmModel_3, featuresTest3);
fprintf('alexnet 正确率:');
mean(predictedLabels1 == testImds.Labels)
fprintf('vgg16 正确率:');
mean(predictedLabels2 == testImds.Labels)
fprintf('resnet18 正确率:');
mean(predictedLabels3 == testImds.Labels)
% 返回一组数据中出现最频繁的元素
predictedLabels = mode([predictedLabels1, predictedLabels2, predictedLabels3], 2);
% 计算投票分类正确率
fprintf('投票正确率:');
accuracy = mean(predictedLabels == testImds.Labels)x = input('是否保存已训练模型(y/n)',"s") ;
if(x=='y')save svm_Model_3 svmModel_1 svmModel_2 svmModel_3fprintf('模型已保存到 svm_Model_3.mat')
end
输出结果:
这个1就很晃眼,大概率不是真的。
appleData = ImageDatastore - 属性:Files: {'D:\apple\1\1.jpeg';'D:\apple\1\1.jpg';'D:\apple\1\10.jpg'... and 197 more}Folders: {'D:\apple'}Labels: [1; 1; 1 ... and 197 more categorical]AlternateFileSystemRoots: {}ReadSize: 1SupportedOutputFormats: ["png" "jpg" "jpeg" "tif" "tiff"]DefaultOutputFormat: "png"ReadFcn: @readDatastoreImage开始加载预训练模型
开始使用预训练模型提取特征
已经提取训练集特征提取特征
已经提取测试集特征提取特征
开始训练alexnet 正确率:
ans =0.9512vgg16 正确率:
ans =0.9024resnet18 正确率:
ans =0.9512投票正确率:
accuracy =1是否保存已训练模型(y/n)y
模型已保存到 svm_Model_3.mat>>