机器学习十大算法之Matlab-2SVM
- SVM
-
- Matlab代码
-
- 例子1-系统fitcsvm做二分类
- 例子2-系统fitcsvm做多分类
SVM
Matlab代码
例子1-系统fitcsvm做二分类
%支持向量机二分类示例
load fisheriris %载入鸢尾属植物数据集
inds = ~strcmp(species,'setosa'); %提取不是'setosa'类的数据
X = meas(inds,3:4); %利用后两个特征(花瓣长度和宽度)
y = species(inds); %剔除'setosa'类后变成二分类问题
SVM = fitcsvm(X,y),
sv = SVM.SupportVectors; %支持向量
gscatter(X(:,1),X(:,2),y,'br','*p'); %按标签y绘制散点图
hold on
plot(sv(:,1),sv(:,2),'ko','MarkerSize',10); %画出支持向量
legend('versicolor','virginica','Support Vector')
hold off
例子2-系统fitcsvm做多分类
%支持向量机多分类示例
load fisheriris %载入Iris数据集
X = meas(:,3:4); %为了可视化, 取数据集的后两个特征
Y = species; %标签
figure (1)
g=gscatter(X(:,1),X(:,2),Y,'mrb','*po'); hold on
a = gca; %当前坐标轴
lims = [a.XLim a.YLim]; %提取x轴和y轴的极限
title('{鸢尾属植物散点图}');
xlabel('花瓣长度 (cm)');
ylabel('花瓣宽度 (cm)');
legend(g,{'setosa','versicolor','virginica'},'Location','Northwest');
SVMModels = cell(3,1);
%SVMModels是一个3×1的元胞数组, 每个单元包含一个ClassificationSVM分类器.
%对于每个细胞, 正类分别是setosa,versicolor和virginica
Cls = unique(Y);
%Cls=unique(Y)表示去掉Y中的重复数据,并按从小到大排序返回给Cls.
rng(1); %可重复性
for j = 1:numel(Cls)
indx = strcmp(Y,Cls(j)); %为每个分类器创建二分类
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(Cls)); %存储得分
for j = 1:numel(Cls)
[~,score] = predict(SVMModels{j},xGrid);
Scores(:,j) = score(:,2); %第二列包含正类分数
end
%定义一个精细的网格, 并将坐标视为来自训练数据分布的新观察值, 使用每个分类器估计新观察值
%的得分. 每一行的分数包含三个分数, 得分最大的元素的索引是新类观察最可能所属的类的索引.
[~,maxScore] = max(Scores,[ ],2);
%根据相应的新观察结果所属的类,在图中的区域上色。
figure (2)
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,'kkk','*po');
title('{鸢尾属植物分类区域}');
xlabel('花瓣长度(cm)'); ylabel('花瓣宽度(cm)');
legend(h,{'setosa region','versicolor region','virginica region',...
'observed setosa','observed versicolor','observed virginica'},...
'Location','Northwest');
axis tight
hold off