Matlab图像识别/检索系列(4)—10行代码完成多分类功能

多分类在Matlab2016中有几种实现方式:构建多个SVM的1对多分类模型;使用softmax分类功能;使用自带的fitcecoc函数。

1.基于SVM的多分类
%exam1.m
load fisheriris
X = meas(:,3:4);
Y = species;
figure
gscatter(X(:,1),X(:,2),Y);
h = gca;
lims = [h.XLim h.YLim]; % Extract the x and y axis limits
title('{\bf Scatter Diagram of Iris Measurements}');
xlabel('Petal Length (cm)');
ylabel('Petal Width (cm)');
legend('Location','Northwest');
%创建保存SVM模型的变量
SVMModels = cell(3,1);
%获取类别标签
classes = unique(Y);
rng('default')
%为每个类训练一对多模型
for j = 1:numel(classes);
    indx = strcmp(Y,classes(j)); % Create binary classes for each classifier
    SVMModels{j} = fitcsvm(X,indx,'ClassNames',[false true],'Standardize',true, 'KernelFunction','rbf','BoxConstraint',1);
end
d = 0.02;
%生成测试数据
[x1Grid,x2Grid] = meshgrid(min(X(:,1)):d:max(X(:,1)),...
    min(X(:,2)):d:max(X(:,2)));
xGrid = [x1Grid(:),x2Grid(:)];
N = size(xGrid,1);
Scores = zeros(N,numel(classes));
%预测测试数据属于每个类的概率
for j = 1:numel(classes);
    [~,score] = predict(SVMModels{j},xGrid);
    Scores(:,j) = score(:,2); % Second column contains positive-class scores
end
%将预测概率中的最大值作为最终预测结果
[~,maxScore] = max(Scores,[],2);
figure
h(1:3) = gscatter(xGrid(:,1),xGrid(:,2),maxScore,...
    [0.1 0.5 0.5; 0.5 0.1 0.5; 0.5 0.5 0.1]);
hold on
h(4:6) = gscatter(X(:,1),X(:,2),Y);
title('{\bf Iris Classification Regions}');
xlabel('Petal Length (cm)');
ylabel('Petal Width (cm)');
legend(h,{'setosa region','versicolor region','virginica region',...
    'observed setosa','observed versicolor','observed virginica'},...
    'Location','Northwest');
axis tight
hold off

这段程序关键代码只有几行,主要是使用 fitcsvm函数训练多个分类模型,然后使用predict预测测试数据属于每个类的概率。

2.使用softmax分类功能。
%exam2.m
[X,T] = iris_dataset;
net = trainSoftmaxLayer(X,T);
Y = net(X);
plotconfusion(T,Y);

这四行代码就实现了对X的分类。主要是trainSoftmaxLayernet两个函数。

net = trainSoftmaxLayer(X,T,Name,Value)

的功能是根据输入数据X和标签T训练出softmax分类层,NameValue用来指定损失函数的类型和门限值。返回值net表示训练结果,并可用来给出数据属于个类别的概率Y。该函数属于Neural Network Toolbox

3. 使用fitcecoc函数

该函数属于Statistics and Machine Learning Toolbox,用来训练多分类ECOC(error-correcting output codes) 模型。

load fisheriris
X = meas(:,3:4);
Y = species;
rng(1); 
%返回多分类学习器模板
t = templateSVM('Standardize',1,'KernelFunction','gaussian');
%训练ECOC多分类器
Mdl = fitcecoc(X,Y,'Learners',t,'FitPosterior',1,...
    'ClassNames',{'setosa','versicolor','virginica'}, 'Verbose',2);
%预测X的类标记、后验概率
[label,~,~,Posterior] = resubPredict(Mdl,'Verbose',1);
idx = randsample(size(X,1),10,1);
table(Y(idx),label(idx),Posterior(idx,:),...
    'VariableNames',{'TrueLabel','PredLabel','Posterior'});

fitcecoc的返回值Mdl属性较多,如下图所示。
Matlab图像识别/检索系列(4)—10行代码完成多分类功能

转载于:https://blog.51cto.com/8764888/2053910

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值