# matlab svmtrain和svmclassify函数使用示例

```clear; close all; clc;

1、对于线性分类问题，我们选取线性核函数，原始数据包括训练数据和测试数据两部分。

```data = meas(51:end,3:4);                % column 3,column 4作为特征值
group = species(51:end);                % 类别
idx = randperm(size(data,1));
N = length(idx);

% SVM train
T = floor(N*0.9);                       % 90组数据作为训练数据
xdata = data(idx(1:T),:);
xgroup = group(idx(1:T));
svmStr = svmtrain(xdata,xgroup,'Showplot',true);```

```% SVM predict
P = floor(N*0.1);                       % 10组预测数据
ydata = data(idx(T+1:end),:);
ygroup = group(idx(T+1:end));
pgroup = svmclassify(svmStr,ydata,'Showplot',true);     % svm预测
hold on;
plot(ydata(:,1),ydata(:,2),'bs','Markersize',12);
accuracy1 = sum(strcmp(pgroup,ygroup))/P*100;            % 预测准确性
hold off;```

2、对于非线性分类问题，我们选取高斯核函数RBF，原始数据包括训练数据和测试数据两部分。

```data = meas(51:end,1:2);                % column 1,column 2作为特征值
group = species(51:end);                % 类别
idx = randperm(size(data,1));
N = length(idx);

% SVM train
T = floor(N*0.9);                       % 90组数据作为训练数据
xdata = data(idx(1:T),:);
xgroup = group(idx(1:T));```

```% different sigma
figure;
sigma = 0.5;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','rbf_sigma',...
sigma,'showplot',true);
title('sigma = 0.5');
figure;
sigma = 1;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','rbf_sigma',...
sigma,'showplot',true);
title('sigma = 1');
figure;
sigma = 3;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','rbf_sigma',...
sigma,'showplot',true);
title('sigma = 3');```

```% different C
figure;
C = 1;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','boxconstraint',...
C,'showplot',true);
title('C = 0.1');
figure;
C = 8;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','boxconstraint',...
C,'showplot',true);
title('C = 1');
figure;
C = 64;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','boxconstraint',...
C,'showplot',true);
title('C = 10');```

```% SVM predict
P = floor(N*0.1);                       % 10组预测数据
ydata = data(idx(T+1:end),:);
ygroup = group(idx(T+1:end));
% sigma = 1,C = 1,default
figure;
svmStr = svmtrain(xdata,xgroup,'kernel_function','rbf','showplot',true);
pgroup = svmclassify(svmStr,ydata,'Showplot',true);     % svm预测
hold on;
plot(ydata(:,1),ydata(:,2),'bs','Markersize',12);
accuracy2 = sum(strcmp(pgroup,ygroup))/P*100;            % 预测准确性
hold off;```

0 条评论

2017

5186

2201

1701

67710

5393

1024

1956

4456

4379