您的位置:首页 > 编程语言 > MATLAB

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

2017-12-23 21:22 816 查看
多分类在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属性较多,如下图所示。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  多分类 softmax fitcecoc
相关文章推荐