SVM二分类问题matlab代码
时间: 2023-12-26 22:45:44 浏览: 24
以下是SVM二分类问题的Matlab代码示例:
```matlab
% 加载数据
load fisheriris;
% 取前100个数据集作为训练集
train_data = [meas(1:50,:); meas(51:100,:)];
train_label = [ones(50,1); -ones(50,1)];
% 取后50个数据集作为测试集
test_data = meas(101:150,:);
test_label = [ones(50,1); -ones(50,1)];
% 训练模型
model = fitcsvm(train_data, train_label, 'KernelFunction', 'linear');
% 预测测试集
predict_label = predict(model, test_data);
% 计算准确率
accuracy = sum(predict_label == test_label) / length(test_label);
disp(['准确率为:', num2str(accuracy)]);
```
以上代码使用了线性核函数进行分类。你可以根据自己的需要选择不同的核函数,如高斯核函数。
相关问题
SVM二分类的matlab代码
以下是一个简单的SVM二分类的Matlab代码:
% 生成样本数据
rng(1); % 设置随机数种子
N = 100; % 样本数量
X = randn(N,2); % 生成N个二维正态分布样本
Y = sign(X(:,1).*X(:,2)); % 确定标签(Y = 1或-1)
% 训练SVM模型
model = fitcsvm(X,Y); % 使用默认参数训练SVM模型
% 绘制决策边界
figure;
h = 0.02; % 网格步长
[x1Grid,x2Grid] = meshgrid(min(X(:,1)):h:max(X(:,1)),...
min(X(:,2)):h:max(X(:,2)));
xGrid = [x1Grid(:),x2Grid(:)];
[~,scores] = predict(model,xGrid);
contour(x1Grid,x2Grid,reshape(scores(:,2),size(x1Grid)),[0 0],'k');
hold on;
gscatter(X(:,1),X(:,2),Y,'rb','+x')
title('SVM决策边界')
xlabel('特征 1')
ylabel('特征 2')
legend('决策边界','Y = 1','Y = -1','Location','Best')
axis tight
hold off
以上代码中,我们首先生成了100个二维正态分布样本,并根据它们的特征值的乘积确定了它们的标签(1或-1)。接着,我们使用fitcsvm函数训练SVM模型,并使用contour函数绘制了SVM的决策边界。最后,我们使用gscatter函数将样本点可视化。
svm支持向量机matlab代码 二分类
以下是一个简单的支持向量机二分类的Matlab代码示例:
```
% 生成数据
x1 = randn(50,2)+ones(50,2);
x2 = randn(50,2)-ones(50,2);
X = [x1;x2];
Y = [ones(50,1);-ones(50,1)];
% 训练SVM模型
svmModel = fitcsvm(X,Y,'KernelFunction','linear','BoxConstraint',1);
% 绘制决策边界和支持向量
figure;
gscatter(X(:,1),X(:,2),Y,'rb','.');
hold on;
h = ezplot(@(x1,x2)predict(svmModel,[x1,x2]),[-3,3,-3,3]);
h.Color = 'k';
h.LineWidth = 2;
title('SVM二分类');
legend('正样本','负样本','决策边界','支持向量');
hold off;
```
代码中使用了`fitcsvm`函数来训练SVM模型,其中`KernelFunction`指定了核函数为线性核,`BoxConstraint`指定了正则化参数的值为1。
在绘制决策边界和支持向量时,使用了`ezplot`函数来绘制二维平面上的曲线。