matlab通过简单的步骤对自己数据集实现SVM

1、首先用简单的matlab提供的数据集进行测试

% 下载数据集:这里先用matlab自带的数据集
unzip('MerchData.zip');

imds = imageDatastore('MerchData',"IncludeSubfolders",true,'LabelSource','foldernames');
[imdsTrain,imdsTest] = splitEachLabel(imds,0.7,"randomized");

% 显示一些图像
numTrainImages = numel(imdsTrain.Labels);
% 随机返回16张图像
idx = randperm(numTrainImages,16);
figure
for i = 1:16
    subplot(4,4,i)
%     I = imread(imdsTrain.Files{i,1});
    I = readimage(imdsTrain,idx(i));
    imshow(I)
end

net = alexnet
net.Layers

% 输出训练网络的1000类中的前10个
net.Layers(end).Classes(1:10)

inputSize = net.Layers(1).InputSize
% 分析网络架构
analyzeNetwork(net)

% 也可以增加数据增强操作,增加训练的复杂度
% imageDataAugmenter = imageDataAugmenter(...
%     'RandRotation',[-20,20],...
%     'RandXTranslation',[-3,3],...
%     'RandYTranslation',[-3,3])
% augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain,"DataAugmentation",imageDataAugmenter);
augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain);
% 测试集就不需要添加增强操作了
augimdsTest = augmentedImageDatastore(inputSize(1:2),imdsTest);

% 较深层的特征
layer = 'fc7';
featuresTrain = activations(net,augimdsTrain,layer,'OutputAs','rows');
featuresTest = activations(net,augimdsTest,layer,'OutputAs','rows');

% 查看信息
whos featuresTrain

% 获取训练数据和测试数据的类标签
YTrain = imdsTrain.Labels
YTest = imdsTest.Labels

% 拟合图像分类器
classifier = fitcecoc(featuresTrain,YTrain)
% 对经过训练的SVM模型从测试图像中提取的特征对测试图像进行分类
YPred = predict(classifier,featuresTest);

% 返回一些图像
idx = [1 5 10 15];
figure
for i = 1:numel(idx)
    subplot(2,2,i)
    I = readimage(imdsTest,idx(i));
    label = YPred(idx(i));
    imshow(I)
    title(char(label))
end

% 针对测试集的分类准确度
accuracy = mean(YPred == YTest)

% 基于较浅特征训练分类器
layer = 'relu3';

% 这里就不需要下面的激活平均操作了,如果没有的话仍然需要下面的操作
featuresTrain = activations(net,augimdsTrain,layer,"OutputAs","rows");
featuresTest = activations(net,augimdsTest,layer,'OutputAs','rows');
whos featuresTrain

% % 手动对所有空间位置的激活区域求平均:最后要获得N*C形式的特征,其中N是观测值数目,C是特征数量
% 下面有对应的转置操作
% featuresTrain = squeeze(mean(featuresTrain,[1,2]))';
% featuresTest = squeeze(mean(featuresTest,[1,2]))';
% whos featuresTrain

% 训练SVM分类器
classifier = fitcecoc(featuresTrain,YTrain);
YPred = predict(classifier,featuresTest);
% 测试准确率
accuracy = mean(YPred == YTest)

输出结果:

 

net = 
  SeriesNetwork - 属性:

         Layers: [25×1 nnet.cnn.layer.Layer]
     InputNames: {'data'}
    OutputNames: {'output'}

ans = 
  具有以下层的 25x1 Layer 数组:

     1   'data'     图像输入      227x227x3 图像: 'zerocenter' 归一化
     2   'conv1'    卷积         96 11x11x3 卷积: 步幅 [4  4],填充 [0  0  0  0]
     3   'relu1'    ReLU         ReLU
     4   'norm1'    跨通道归一化   跨通道归一化: 每元素 5 个通道
     5   'pool1'    最大池化      3x3 最大池化: 步幅 [2  2],填充 [0  0  0  0]
     6   'conv2'    分组卷积      2 groups of 128 5x5x48 卷积: 步幅 [1  1],填充 [2  2  2  2]
     7   'relu2'    ReLU         ReLU
     8   'norm2'    跨通道归一化   跨通道归一化: 每元素 5 个通道
     9   'pool2'    最大池化      3x3 最大池化: 步幅 [2  2],填充 [0  0  0  0]
    10   'conv3'    卷积         384 3x3x256 卷积: 步幅 [1  1],填充 [1  1  1  1]
    11   'relu3'    ReLU         ReLU
    12   'conv4'    分组卷积      2 groups of 192 3x3x192 卷积: 步幅 [1  1],填充 [1  1  1  1]
    13   'relu4'    ReLU         ReLU
    14   'conv5'    分组卷积      2 groups of 128 3x3x192 卷积: 步幅 [1  1],填充 [1  1  1  1]
    15   'relu5'    ReLU         ReLU
    16   'pool5'    最大池化      3x3 最大池化: 步幅 [2  2],填充 [0  0  0  0]
    17   'fc6'      全连接        4096 全连接层
    18   'relu6'    ReLU         ReLU
    19   'drop6'    丢弃         50% 丢弃
    20   'fc7'      全连接        4096 全连接层
    21   'relu7'    ReLU         ReLU
    22   'drop7'    丢弃         50% 丢弃
    23   'fc8'      全连接        1000 全连接层
    24   'prob'     Softmax      softmax
    25   'output'   分类输出      crossentropyex: 具有 'tench' 和 999 个其他类

ans = 10×1 categorical 数组
tench                
goldfish             
great white shark    
tiger shark          
hammerhead           
electric ray         
stingray             
cock                 
hen                  
ostrich              

inputSize = 1×3
   227   227     3

 

  Name                Size               Bytes  Class     Attributes

  featuresTrain      55x4096            901120  single              

 

YTrain = 55×1 categorical 数组
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    
MathWorks Cap    

YTest = 20×1 categorical 数组
MathWorks Cap              
MathWorks Cap              
MathWorks Cap              
MathWorks Cap              
MathWorks Cube             
MathWorks Cube             
MathWorks Cube             
MathWorks Cube             
MathWorks Playing Cards    
MathWorks Playing Cards    

classifier = 
  ClassificationECOC
             ResponseName: 'Y'
    CategoricalPredictors: []
               ClassNames: [MathWorks Cap    MathWorks Cube    MathWorks Playing Cards    MathWorks Screwdriver    MathWorks Torch]
           ScoreTransform: 'none'
           BinaryLearners: {10×1 cell}
               CodingName: 'onevsone'


  Properties, Method

accuracy = 1
  Name                Size                  Bytes  Class     Attributes

  featuresTrain      55x64896            14277120  single              

accuracy = 0.9000

 2、再针对自己的数据集进行测试

现在开始对自己的数据集进行测试:Corel1K,网上能下载到,如果想要数据集的话,可以留言我看到发给你!

这个数据集总计10个类,每个类100张图像

Corel1Kdataset = imageDatastore('Corel1K');
labels = zeros(1000,1);
filename = dir('./Corel1K/*.jpg');
for i = 1:1000
    split = strsplit(filename(i).name,{'_','.'});
    labels(i) = str2double(split{1});
end
Corel1Kdataset.Labels = categorical(labels);

[imdsTrain,imdsTest] = splitEachLabel(Corel1Kdataset,0.7,"randomized");

% 显示一些图像
numTrainImages = numel(imdsTrain.Labels);
% 随机返回16张图像
idx = randperm(numTrainImages,16);
figure
for i = 1:16
    subplot(4,4,i)
%     I = imread(imdsTrain.Files{i,1});
    I = readimage(imdsTrain,idx(i));
    imshow(I)
end

net = vgg16;
net.Layers

net.Layers(end).Classes(1:10)

inputSize = net.Layers(1).InputSize
% 分析网络架构
analyzeNetwork(net)

augimdsTrain = augmentedImageDatastore(inputSize(1:2),imdsTrain);
% 测试集就不需要添加增强操作了
augimdsTest = augmentedImageDatastore(inputSize(1:2),imdsTest);

% 较深层的特征
layer = 'fc7';
featuresTrain = activations(net,augimdsTrain,layer,'OutputAs','rows',"ExecutionEnvironment","cpu");
featuresTest = activations(net,augimdsTest,layer,'OutputAs','rows','ExecutionEnvironment',"cpu");
whos featuresTrain

% 获取训练数据和测试数据的类标签
YTrain = imdsTrain.Labels;
YTest = imdsTest.Labels;

% 拟合图像分类器
classifier = fitcknn(featuresTrain,YTrain,"NumNeighbors",5);
% 对经过训练的SVM模型从测试图像中提取的特征对测试图像进行分类
YPred = predict(classifier,featuresTest);

% 返回一些图像
idx = [1 5 10 15];
figure
for i = 1:numel(idx)
    subplot(2,2,i)
    I = readimage(imdsTest,idx(i));
    label = YPred(idx(i));
    imshow(I)
    title(char(label))
end

% 针对测试集的分类准确度
accuracy = mean(YPred == YTest)

 输出结果:accuracy = 0.9667

 

你可能感兴趣的:(matlab-CV)