matlab算法svm代码实现
时间: 2023-09-06 15:12:00 浏览: 69
以下是MATLAB中使用SVM(支持向量机)算法的简单示例代码:
```
% 导入数据
load fisheriris
X = meas(:, 3:4);
Y = species;
% 划分训练集和测试集
cv = cvpartition(Y,'HoldOut',0.3);
idx = cv.test;
Xtrain = X(~idx,:);
Ytrain = Y(~idx,:);
Xtest = X(idx,:);
Ytest = Y(idx,:);
% 训练SVM模型
SVMModel = fitcsvm(Xtrain,Ytrain);
% 预测测试集并计算准确率
Ypredict = predict(SVMModel,Xtest);
Accuracy = sum(Ypredict == Ytest)/length(Ytest);
disp(['Accuracy: ' num2str(Accuracy)]);
% 可视化分类结果
h = figure;
gscatter(Xtest(:,1),Xtest(:,2),Ytest);
hold on;
ezpolar(@(x)1);
ezpolar(@(x)2);
title('SVM Classification');
legend('Versicolor','Virginica','Boundary','Support Vectors');
hold off;
```
该代码使用了鸢尾花数据集作为示例数据,将其前两个测量值作为特征,将品种作为标签。使用`fitcsvm`函数训练SVM模型,使用`predict`函数预测测试集,并计算准确率。最后使用`gscatter`函数和`ezpolar`函数可视化分类结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)