You are on page 1of 7

12

4.
clear
close all
[x1,x2] = meshgrid([0:0.1:5;0:0.1:5]);
w1 = 1;
w2 = 1;
b = 1;
y_true = w1*x1+w2*x2+b; % the true plane
figure,mesh(x1,x2,y_true);

y = y_true+1*randn(size(x1)); % add noise


figure,scatter3(x1(:),x2(:),y(:),'.');
X=[x1(:),x2(:)];
Mdl=fitrsvm(X,y(:))

RegressionSVM

ResponseName: 'Y'

CategoricalPredictors: []

ResponseTransform: 'none'
Alpha: [8433×1 double]

Bias: 0.9236
KernelParameters: [1×1 struct]

NumObservations: 10404

BoxConstraints: [10404×1 double]

ConvergenceInfo: [1×1 struct]

IsSupportVector: [10404×1 logical]

Solver: 'SMO'

Properties, Methods

w1_p=Mdl.Beta(1);w2_p=Mdl.Beta(2);b_p=Mdl.Bias;
y_predict = w1_p*x1+w2_p*x2+b_p; % the predicted plane
figure,mesh(x1,x2,y_predict);
[w1_p,w2_p,b_p] %w1 w2 b

ans = 1×3
1.0113 1.0232 0.9236

5.

clear
close all
load fisheriris %载入数据集
inds=~strcmp(species,'setosa'); %提取不是setosa类的数据
X=meas(inds,3:4); %利用后两个特征(花瓣长度和花瓣宽度)
y=species(inds); %剔除‘setosa’类后变成二分类问题
SVMModel=fitcsvm(X,y)

SVMModel =
ClassificationSVM

ResponseName: 'Y'

CategoricalPredictors: []

ClassNames: {'versicolor' 'virginica'}

ScoreTransform: 'none'
NumObservations: 100

Alpha: [24×1 double]

Bias: -14.4149

KernelParameters: [1×1 struct]

BoxConstraints: [100×1 double]

ConvergenceInfo: [1×1 struct]

IsSupportVector: [100×1 logical]

Solver: 'SMO'

sv=SVMModel.SupportVectors; %支持向量
gscatter(X(:,1),X(:,2),y,'br','*p'); %按标签y绘制散点图
hold on
plot(sv(:,1),sv(:,2),'ko','MarkerSize',9); %画出支持向量
legend('versicolor','virginica','Support Vector')
hold on
w=SVMModel.Beta';
b=SVMModel.Bias;
X1=[3:0.1:7];
plot(X1,(w(1)*X1+b)/(-w(2)));
plot(X1,(w(1)*X1+b+1)/(-w(2)));
plot(X1,(w(1)*X1+b-1)/(-w(2)));
legend('versicolor','virginica','Support Vector',"w'x+b=0","w'x+b=-1","w'x+b=1")
hold off

You might also like