鸢尾花数据集分类的支持向量机实验matlab代码
时间: 2023-07-16 11:17:22 浏览: 129
支持向量机,实现源码,鸢尾花数据集分类
以下是鸢尾花数据集分类的支持向量机实验matlab代码:
```matlab
% 加载数据集
load fisheriris
% 取前两个特征作为二维数据进行可视化
X = meas(:,1:2);
Y = species;
% 将标签转化为数字
Y = grp2idx(Y);
% 划分训练集和测试集
cv = cvpartition(Y,'holdout',0.2);
idxTrain = training(cv);
idxTest = test(cv);
% 训练支持向量机模型
svmModel = fitcsvm(X(idxTrain,:),Y(idxTrain),'KernelFunction','rbf');
% 预测测试集
YTest = predict(svmModel,X(idxTest,:));
% 计算准确率
accuracy = sum(YTest == Y(idxTest))/numel(YTest)
% 绘制决策边界
d = 0.02;
[x1Grid,x2Grid] = meshgrid(min(X(:,1)):d:max(X(:,1)),...
min(X(:,2)):d:max(X(:,2)));
xGrid = [x1Grid(:),x2Grid(:)];
[~,scores] = predict(svmModel,xGrid);
figure;
h(1:2) = gscatter(X(idxTest,1),X(idxTest,2),Y(idxTest));
hold on
h(3) = plot(X(svmModel.IsSupportVector,1),X(svmModel.IsSupportVector,2),'ko','MarkerSize',10);
contour(x1Grid,x2Grid,reshape(scores(:,2),size(x1Grid)),[0 0],'k');
legend({'versicolor','virginica','Support Vectors'});
axis tight
title(sprintf('SVM Classification with RBF Kernel \n Accuracy = %0.2f%%',accuracy*100));
```
以上代码使用了径向基函数作为支持向量机的核函数,训练完成后绘制了决策边界和支持向量的位置。
阅读全文