svm支持向量机matlab代码
时间: 2023-10-07 15:07:20 浏览: 50
以下是一个简单的SVM MATLAB示例代码:
% 生成数据集
X = [1 2; 2 3; 3 1; 4 4; 5 5; 6 4; 7 2; 8 1];
Y = [-1 -1 -1 1 1 1 1 1];
% 训练SVM
svmModel = fitcsvm(X, Y);
% 可视化数据和决策边界
figure;
gscatter(X(:,1), X(:,2), Y,'rgb','osd');
hold on;
h = gca;
xlim = h.XLim;
ylim = h.YLim;
[x1Grid,x2Grid] = meshgrid(linspace(xlim(1),xlim(2),100),linspace(ylim(1),ylim(2),100));
xGrid = [x1Grid(:),x2Grid(:)];
[~,scores] = predict(svmModel,xGrid);
contour(x1Grid,x2Grid,reshape(scores(:,2),size(x1Grid)),[0 0],'k');
title('SVM决策边界');
% 对新数据进行预测
newX = [3 3.5; 4 2.5];
[label,score] = predict(svmModel,newX);
disp(label);
disp(score);
相关问题
Svm支持向量机Matlab 代码
以下是一个简单的SVM二分类器的Matlab代码示例:
```matlab
% 准备数据
load fisheriris
X = meas(:,1:2);
Y = species;
Y = categorical(Y);
rng(1); % 设置随机数种子
% 划分训练集和测试集
cv = cvpartition(Y,'HoldOut',0.2);
idx = cv.test;
Xtrain = X(~idx,:);
Ytrain = Y(~idx);
Xtest = X(idx,:);
Ytest = Y(idx);
% 训练SVM分类器
SVMModel = fitcsvm(Xtrain,Ytrain);
% 预测测试集
Ypred = predict(SVMModel,Xtest);
% 计算分类准确率
Accuracy = sum(Ypred == Ytest)/numel(Ytest)
```
这个示例使用鸢尾花数据集,其中包含150个样本,每个样本有4个特征和一个类别标签。我们只使用前两个特征,并将类别标签转换为分类变量。然后,使用“HoldOut”方法将数据集分为训练集和测试集。使用`fitcsvm`函数训练SVM分类器,并使用`predict`函数预测测试集。最后,计算分类准确率。
使用svmtrain写svm支持向量机matlab代码
下面是使用svmtrain函数写svm支持向量机matlab代码的示例:
```matlab
% 载入数据
load fisheriris
X = meas(51:end,3:4); % 取后100个样本的后两个特征
y = (1:50)'>25; % 标签,前50个样本为0,后50个样本为1
% 训练svm模型
svmModel = svmtrain(X, y, 'Kernel_Function', 'rbf', 'BoxConstraint', Inf);
% 预测
Xnew = [5.9 3.0; 6.0 3.4; 6.1 2.9];
ynew = svmclassify(svmModel,Xnew);
% 绘制决策边界和支持向量
sv = svmModel.SupportVectors;
figure
scatter(X(:,1),X(:,2),'filled')
hold on
scatter(sv(:,1),sv(:,2),'ro')
contourf(xx,yy,reshape(scores(:,2),size(xx)),[0 0],'LineStyle','none')
colorbar
```
其中,X和y分别为特征和标签,svmtrain函数的第一个参数为特征,第二个参数为标签,第三个参数为一些参数的设定。svmclassify函数用于预测新的样本标签。绘制决策边界和支持向量可以使用contourf函数。
相关推荐
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)