【图像分类】基于卷积神经网络实现花朵图像分类附matlab代码

本文介绍了如何使用Matlab进行图像分类,包括基于CNN的基础分类器、数据增强技术以及迁移学习的应用。通过创建ImageDataStore,训练和验证数据集,以及使用预训练的AlexNet进行迁移学习,对比了不同方法对分类准确率的影响。数据增强提高了模型的泛化能力,而迁移学习则显著提升了模型在有限数据上的表现。
摘要由CSDN通过智能技术生成

✅作者简介:热爱科研的Matlab仿真开发者,修心和技术同步精进,matlab项目合作可私信。

🍎个人主页:Matlab科研工作室

🍊个人信条:格物致知。

更多Matlab仿真内容点击👇

智能优化算法  神经网络预测 雷达通信  无线传感器

信号处理 图像处理 路径规划 元胞自动机 无人机  电力系统

⛄ 内容介绍

在图片搜索应用中,与基于时间,地点或关键词查找等成熟的搜索方式相比,基于图片内容的搜索具有更加直观快捷的特点.因此,利用图像分类技术实现基于图像内容的搜索成为一个日益受到关注的研究领域.一般地,机器学习中的分类算法可以分为两类:基于人为构造特征的分类方法,如K近邻算法,支持向量机等;以及以卷积神经网络为基础的,不需要人为设计特征的深度学习方法.

⛄ 部分代码

%% Flower Classifier using a CNN and data augmentation

%% PART 1: Baseline Classifier

%% Create image data store

imds = imageDatastore(fullfile('Flowers'),...

'IncludeSubfolders',true,'FileExtensions','.jpg','LabelSource','foldernames');

% Count number of images per label and save the number of classes

labelCount = countEachLabel(imds);

numClasses = height(labelCount);

%% Create training and validation sets

[imdsTrainingSet, imdsValidationSet] = splitEachLabel(imds, 0.7, 'randomize');

%% Build a simple CNN 

imageSize = [227 227 3];

% Specify the convolutional neural network architecture.

layers = [

    imageInputLayer(imageSize)

    

    convolution2dLayer(3,8,'Padding','same')

    batchNormalizationLayer

    reluLayer   

    

    maxPooling2dLayer(2,'Stride',2)

    

    convolution2dLayer(3,16,'Padding','same')

    batchNormalizationLayer

    reluLayer   

    

    maxPooling2dLayer(2,'Stride',2)

    

    convolution2dLayer(3,32,'Padding','same')

    batchNormalizationLayer

    reluLayer   

    

    fullyConnectedLayer(4)

    softmaxLayer

    classificationLayer];

%% Specify training options 

options = trainingOptions('sgdm', ...

    'MiniBatchSize',10, ...

    'MaxEpochs',6, ...

    'InitialLearnRate',1e-4, ...

    'Shuffle','every-epoch', ...

    'ValidationData',imdsValidationSet, ...

    'ValidationFrequency',3, ...

    'Verbose',false, ...

    'Plots','training-progress');

%% Train the network

net1 = trainNetwork(imdsTrainingSet,layers,options);

%% Report accuracy of baseline classifier on validation set

YPred = classify(net1,imdsValidationSet);

YValidation = imdsValidationSet.Labels;

imdsAccuracy = sum(YPred == YValidation)/numel(YValidation);

%% Plot confusion matrix

figure, plotconfusion(YValidation,YPred)

%% PART 2: Baseline Classifier with Data Augmentation

%% Create augmented image data store

% Specify data augmentation options and values/ranges

imageAugmenter = imageDataAugmenter( ...

    'RandRotation',[-20,20], ...

    'RandXTranslation',[-5 5], ...

    'RandYTranslation',[-5 5]);

% Apply transformations (using randomly picked values) and build augmented

% data store

augImds = augmentedImageDatastore(imageSize,imdsTrainingSet, ...

    'DataAugmentation',imageAugmenter);

% (OPTIONAL) Preview augmentation results 

batchedData = preview(augImds);

figure, imshow(imtile(batchedData.input))

    

%% Train the network. 

net2 = trainNetwork(augImds,layers,options);

%% Report accuracy of baseline classifier with image data augmentation

YPred = classify(net2,imdsValidationSet);

YValidation = imdsValidationSet.Labels;

augImdsAccuracy = sum(YPred == YValidation)/numel(YValidation);

%% Plot confusion matrix

figure, plotconfusion(YValidation,YPred)

%% PART 3: Transfer Learning without Data Augmentation

%% Load pretrained AlexNet

net = alexnet;

%% Replace final layers

layersTransfer = net.Layers(1:end-3);

layers = [

    layersTransfer

    fullyConnectedLayer(numClasses,'WeightLearnRateFactor',20,'BiasLearnRateFactor',20)

    softmaxLayer

    classificationLayer];

%% Train network

options = trainingOptions('sgdm', ...

    'MiniBatchSize',10, ...

    'MaxEpochs',6, ...

    'InitialLearnRate',1e-4, ...

    'Shuffle','every-epoch', ...

    'ValidationData',imdsValidationSet, ...

    'ValidationFrequency',3, ...

    'Verbose',false, ...

    'Plots','training-progress');

netTransfer1 = trainNetwork(imdsTrainingSet,layers,options);

%% Compute accuracy and plot confusion matrix

YPred = classify(netTransfer1,imdsValidationSet);

YValidation = imdsValidationSet.Labels;

netTransfer1BaselineAccuracy = sum(YPred == YValidation)/numel(YValidation);

figure, plotconfusion(YValidation,YPred)

%% PART 4: Transfer Learning with Data Augmentation

%% Train network

netTransfer2 = trainNetwork(augImds,layers,options);

%% Compute accuracy and plot confusion matrix

YPred = classify(netTransfer2,imdsValidationSet);

YValidation = imdsValidationSet.Labels;

netTransfer2BaselineAccuracy = sum(YPred == YValidation)/numel(YValidation);

figure, plotconfusion(YValidation,YPred)

⛄ 运行结果

⛄ 参考文献

[1]李晓普. 基于卷积神经网络的图像分类[D]. 大连理工大学, 2015.

⛄ 完整代码

❤️部分理论引用网络文献,若有侵权联系博主删除

❤️ 关注我领取海量matlab电子书和数学建模资料

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
基于Matlab卷积神经网络(Convolutional Neural Networks, CNN图像分类代码可以使用Matlab的深度学习工具箱(Deep Learning Toolbox)来实现。下面是一个简单的示例代码: 1. 数据预处理:首先,需要将图像数据准备为CNN所需的格式。可以使用`imageDatastore`函数创建图像数据存储对象。 ```matlab imds = imageDatastore('path_to_images', 'IncludeSubfolders', true, 'LabelSource', 'foldernames'); ``` 其中,`path_to_images`是存放图像的文件夹路径,`IncludeSubfolders`参数设置为`true`表示包含子文件夹中的图像,`LabelSource`参数设置为`foldernames`表示使用文件夹的名称作为类别标签。 2. 构建CNN模型:使用`LayerGraph`对象创建CNN的网络结构。 ```matlab layers = [ imageInputLayer([32 32 3]) convolution2dLayer(3, 16, 'Padding', 'same') reluLayer() maxPooling2dLayer(2, 'Stride', 2) fullyConnectedLayer(10) softmaxLayer() classificationLayer() ]; lgraph = layerGraph(layers); ``` 上述代码中的网络结构包含了输入图像层、卷积层、ReLU激活层、池化层、全连接层、Softmax层和分类层。这只是一个简单的示例,实际应用中可以根据需要调整网络结构。 3. 训练CNN模型:使用`trainNetwork`函数对CNN模型进行训练。 ```matlab options = trainingOptions('sgdm', 'MaxEpochs', 10, 'InitialLearnRate', 0.001); trainedNet = trainNetwork(imds, lgraph, options); ``` 上述代码中的`trainingOptions`函数指定了优化器为随机梯度下降(stochastic gradient descent, SGD),训练时的最大轮数为10,初始学习率为0.001。可以根据需求进行更多的配置。 4. 图像分类:使用训练好的CNN模型对新的图像进行分类。 ```matlab im = imread('path_to_test_image'); im = imresize(im, [32 32]); label = classify(trainedNet, im); ``` 其中,`path_to_test_image`为待分类的图像路径。`imresize`函数将图像调整为与训练集相同的大小,`classify`函数根据训练好的网络对图像进行分类,并返回预测的标签。 这只是一个基于Matlab卷积神经网络图像分类代码的简单示例,可以根据具体需求进行代码的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

matlab科研助手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值