svm支持向量机matlab程序
时间: 2023-11-02 13:37:40 浏览: 102
以下是一个简单的SVM支持向量机的MATLAB程序:
% SVM支持向量机分类器
% 加载数据
load fisheriris.mat
X = meas(:,3:4);
Y = species;
% 将数据分成训练集和测试集
cv = cvpartition(size(X,1),'HoldOut',0.3);
X_train = X(cv.training,:);
Y_train = Y(cv.training,:);
X_test = X(cv.test,:);
Y_test = Y(cv.test,:);
% 训练SVM分类器
svm = fitcsvm(X_train,Y_train);
% 预测测试集
Y_pred = predict(svm,X_test);
% 计算准确率
accuracy = sum(Y_pred == Y_test)/length(Y_test)
% 绘制决策边界
figure
gscatter(X(:,1),X(:,2),Y)
hold on
h = svmplot(X_train,Y_train,svm);
title(sprintf('SVM Decision Boundary (Accuracy = %.2f%%)',accuracy*100))
legend(h,'Support Vector')
hold off
function h = svmplot(X,Y,svm)
% 绘制SVM决策边界
% 参考:https://www.mathworks.com/matlabcentral/answers/475023-how-to-plot-decision-boundaries-of-a-support-vector-machine-classifier-in-matlab
% 这个函数需要一个支持向量机分类器对象
% 获取支持向量和权重
alpha = svm.Alpha;
support_vectors = svm.SupportVectors;
bias = svm.Bias;
% 计算权重向量
w = support_vectors'*diag(alpha)*Y;
b = -bias;
% 计算决策边界
xl = get(gca,'XLim');
yl = get(gca,'YLim');
x1 = xl(1);
x2 = xl(2);
y1 = -(w(1)*x1 + b)/w(2);
y2 = -(w(1)*x2 + b)/w(2);
% 绘制决策边界
h = plot([x1 x2],[y1 y2],'k--','LineWidth',2);
end
阅读全文