SVM算法MATLAB代码,可视化显示
时间: 2023-12-14 09:14:54 浏览: 98
可以通过以下代码实现SVM算法的可视化显示:
% 加载数据集
load fisheriris
x = meas;
y = species;
% 将数据集分为训练集和测试集
cv = cvpartition(y,'holdout',0.2);
xtrain = x(cv.training,:);
ytrain = y(cv.training,:);
xtest = x(cv.test,:);
ytest = y(cv.test,:);
% 训练SVM模型
svmmodel = fitcsvm(xtrain,ytrain);
% 在测试集上进行预测
ypred = predict(svmmodel,xtest);
% 计算准确率
accuracy = sum(ypred == ytest)/size(ytest,1);
% 可视化显示
gscatter(xtest(:,1),xtest(:,2),ypred);
hold on
h = svmplot(svmmodel,xtrain);
legend(h,{'setosa','versicolor','virginica','Support Vectors'},'Location','Best');
title(sprintf('SVM Classification (Accuracy = %.2f%%)',accuracy*100));
hold off
% 定义svmplot函数
function h = svmplot(model,x)
h = [];
if model.NumClasses ~= 2
error('svmplot only works with two-class SVMs.');
end
if size(x,2) ~= 2
error('svmplot only works with 2D data.');
end
sv = model.SupportVectors;
alpha = model.Alpha;
bias = model.Bias;
kfun = model.KernelFunction;
kfunargs = model.KernelFunctionArgs;
if strcmp(func2str(kfun),'linear')
% 线性核函数
h(1) = plot(x(:,1),x(:,2),'k.','MarkerSize',10);
hold on
h(2) = plot(sv(:,1),sv(:,2),'ko','MarkerSize',12);
w = sv'*(repmat(alpha.*model.Y,1,size(sv,2)).*sv);
b = bias;
x1 = linspace(min(x(:,1)),max(x(:,1)),100);
x2 = -(w(1)*x1 + b)/w(2);
h(3) = plot(x1,x2,'k-','LineWidth',2);
h(4) = plot(x1,x2+1/w(2),'k--','LineWidth',1);
h(5) = plot(x1,x2-1/w(2),'k--','LineWidth',1);
xlim([min(x(:,1)) max(x(:,1))]);
ylim([min(x(:,2)) max(x(:,2))]);
xlabel('Feature 1');
ylabel('Feature 2');
hold off
else
% 非线性核函数
[x1,x2] = meshgrid(linspace(min(x(:,1)),max(x(:,1)),100),linspace(min(x(:,2)),max(x(:,2)),100));
xgrid = [x1(:),x2(:)];
[~,score] = predict(model,xgrid);
scoregrid = reshape(score(:,2),size(x1));
h(1) = contourf(x1,x2,scoregrid,[-inf 0 inf],'LineStyle','none');
hold on
h(2) = plot(x(:,1),x(:,2),'k.','MarkerSize',10);
h(3) = plot(sv(:,1),sv(:,2),'ko','MarkerSize',12);
xlim([min(x(:,1)) max(x(:,1))]);
ylim([min(x(:,2)) max(x(:,2))]);
xlabel('Feature 1');
ylabel('Feature 2');
hold off
end
end
阅读全文