106个样本数据,每个样本9个特征,标签:20个1,15个2,18个3,16个4,14个5,22个6。
matrix中106*9,每一行表示一个样本的9个特征输入数据。
训练数据svm-train中参数:
svm-train主要实现对训练数据集的训练,并可以获得SVM模型。用法: svm-train [options] training_set_file [model_file],其中options为操作参数,可用的选项即表示的涵义如下所示:
English:
libsvm_options:
-s svm_type : set type of SVM (default 0)
0 -- C-SVC
1 -- nu-SVC
2 -- one-class SVM
3 -- epsilon-SVR
4 -- nu-SVR
-t kernel_type : set type of kernel function (default 2)
0 -- linear: u'*v
1 -- polynomial: (gamma*u'*v + coef0)^degree
2 -- radial basis function: exp(-gamma*|u-v|^2)
3 -- sigmoid: tanh(gamma*u'*v + coef0)
4 -- precomputed kernel (kernel values in training_instance_matrix)
-d degree : set degree in kernel function (default 3)
-g gamma : set gamma in kernel function (default 1/k)
-r coef0 : set coef0 in kernel function (default 0)
-c cost : set the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
-n nu : set the parameter nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
-p epsilon : set the epsilon in loss function of epsilon-SVR (default 0.1)
-m cachesize : set cache memory size in MB (default 100)
-e epsilon : set tolerance of termination criterion (default 0.001)
-h shrinking: whether to use the shrinking heuristics, 0 or 1 (default 1)
-b probability_estimates: whether to train a SVC or SVR model for probability estimates, 0 or 1 (default 0)
-wi weight: set the parameter C of class i to weight*C, for C-SVC (default 1)
-v n: n-fold cross validation mode
==========================================================
Chinese:
Options:可用的选项即表示的涵义如下
-s svm类型:SVM设置类型(默认0) 分类用0-2,回归用3和4
0 -- C-SVC
1 --v-SVC
2 – 一类SVM
3 -- e -SVR
4 -- v-SVR
-t 核函数类型:核函数设置类型(默认2)
0 – 线性:u'v
1 – 多项式:(r*u'v + coef0)^degree
2 – RBF函数:exp(-r|u-v|^2)
3 –sigmoid:tanh(r*u'v + coef0)
-d degree:核函数中的degree设置(针对多项式核函数)(默认3)
-g r(gama):核函数中的gamma函数设置(针对多项式/rbf/sigmoid核函数)(默认1/ k), 本文设置为2^c(i,j)
-r coef0:核函数中的coef0设置(针对多项式/sigmoid核函数)((默认0)
-c cost:设置C-SVC,e -SVR和v-SVR的参数(损失函数)(默认1) 惩罚因子: 本文设置为2^c(i,j)
-n nu:设置v-SVC,一类SVM和v- SVR的参数(默认0.5)
-p p:设置e -SVR 中损失函数p的值(默认0.1)
-m cachesize:设置cache内存大小,以MB为单位(默认40)
-e eps:设置允许的终止判据(默认0.001)
-h shrinking:是否使用启发式,0或1(默认1)
-wi weight:设置第几类的参数C为weight*C(C-SVC中的C)(默认1)
-v n: n-fold交互检验模式,n为fold的个数,必须大于等于2
其中-g选项中的k是指输入数据中的属性数。option -v 随机地将数据剖分为n部分并计算交互检验准确度和均方根误差。以上这些参数设置可以按照SVM的类型和核函数所支持的参数进行任意组合,如果设置的参数在函数或SVM类型中没有也不会产生影响,程序不会接受该参数;如果应有的参数设置不正确,参数将采用默认值。
训练完了之后,我们就可以对数据进行预测了,但是,训练的数据未必是最优参数,所以需要进一步优化。LibSVM提供了优化工具,就是tools文件夹,其中包含了grid.py文件和easy.py文件,grid文件可以针对训练数据优选出最佳参数值,而easy则提供了对样本文件做了“一条龙服务”,从参数优选,到文件预测。
cmd = ['-v ',num2str(v),' -t 2',' -c ',num2str(2^c(i,j)),' -g ',num2str(2^g(i,j))];
cg(i,j) = svmtrain(train_label,Train_matrix,cmd); %返回一个数字。c(1,1)=25
103个样本数据,每个样本7个特征,标签:1103
其中,#iter为迭代次数,nu 是你选择的核函数类型的参数,obj为SVM文件转换为的二次规划求解得到的最小值,rho为判决函数的偏置项b,nSV 为标准支持向量个数(0
3、整体代码
%% I. 清空环境变量
clear all
clc
%% II. 导入数据
load BreastTissue_data.mat
%%
% 1. 随机产生训练集和测试集
n = randperm(size(matrix,1));
%%
% 2. 训练集——80个样本
train_matrix = matrix(n(1:80),:);
train_label = label(n(1:80),:);
%%
% 3. 测试集——26个样本
test_matrix = matrix(n(81:end),:);
test_label = label(n(81:end),:);
%% III. 数据归一化
%mapminmax函数是对每一行每一行进行归一化的,这里每一行是一个样本的特征数据,因此转置后9*80每一行表示不同样本相同的特征
%因此转置对每一种特征进行归一化
[Train_matrix,PS] = mapminmax(train_matrix');
Train_matrix = Train_matrix';
Test_matrix = mapminmax('apply',test_matrix',PS);
Test_matrix = Test_matrix';
%% IV. SVM创建/训练(RBF核函数)
%% 利用网格搜索法寻找最佳的c和g
% 1. 寻找最佳c/g参数——交叉验证方法
[c,g] = meshgrid(-10:0.2:10,-10:0.2:10); %-10到10,步长0.2,且C^T=G,101*101
[m,n] = size(c);
cg = zeros(m,n);
eps = 10^(-4);
v = 5; %交叉验证的次数
bestc = 1;
bestg = 0.1;
bestacc = 0;
for i = 1:m
for j = 1:n
% t=2径向基核函数rbf,c惩罚因子=2^c(i,j)
cmd = ['-v ',num2str(v),' -t 2',' -c ',num2str(2^c(i,j)),' -g ',num2str(2^g(i,j))];
cg(i,j) = svmtrain(train_label,Train_matrix,cmd); %返回一个数字。c(1,1)=25
if cg(i,j) > bestacc
bestacc = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
if abs( cg(i,j)-bestacc )<=eps && bestc > 2^c(i,j)
bestacc = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
end
end
%经过对每一个c(i,j)的训练得到最优的惩罚因子c和和参数gamma的值g
cmd = [' -t 2',' -c ',num2str(bestc),' -g ',num2str(bestg)];
%%
% 2. 创建/训练SVM模型
% model = svmtrain(train_label,train_matrix',libsvm_options');
model = svmtrain(train_label,Train_matrix,cmd);
%% V. SVM仿真测试
[predict_label_1,accuracy_1,preb] = svmpredict(train_label,Train_matrix,model);
[predict_label_2,accuracy_2,preb] = svmpredict(test_label,Test_matrix,model);
result_1 = [train_label predict_label_1];
result_2 = [test_label predict_label_2];
%% VI. 绘图
figure
plot(1:length(test_label),test_label,'r-*')
hold on
plot(1:length(test_label),predict_label_2,'b:o')
grid on
legend('真实类别','预测类别')
xlabel('测试集样本编号')
ylabel('测试集样本类别')
string = {'测试集SVM预测结果对比(RBF核函数)';
['accuracy = ' num2str(accuracy_2(1)) '%']};
title(string)
混凝土抗压强度测试:回归(libsvm VS BP神网)
1、使用数据说明:concrete_data.mat
matrix中7103,每一行表示每一个特征对一个不同样本的数值。
注意:神经网络中每一列代表一个样本,支持向量机中每一行代表一个样本,所以要转置2、整体代码
%% I. 清空环境变量
clear all
clc
%% II. 导入数据
load concrete_data.mat
%%
% 1. 随机产生训练集和测试集
n = randperm(size(attributes,2));
%%
% 2. 训练集——80个样本
p_train = attributes(:,n(1:80))';
t_train = strength(:,n(1:80))';
%%
% 3. 测试集——23个样本
p_test = attributes(:,n(81:end))';
t_test = strength(:,n(81:end))';
%% III. 数据归一化
%%
% 1. 训练集
[pn_train,inputps] = mapminmax(p_train');
pn_train = pn_train';
pn_test = mapminmax('apply',p_test',inputps);
pn_test = pn_test';
%%
% 2. 测试集
[tn_train,outputps] = mapminmax(t_train');
tn_train = tn_train';
tn_test = mapminmax('apply',t_test',outputps);
tn_test = tn_test';
%% IV. SVM模型创建/训练
%%
% 1. 寻找最佳c参数/g参数
[c,g] = meshgrid(-10:0.5:10,-10:0.5:10);
[m,n] = size(c);
cg = zeros(m,n);
eps = 10^(-4);
v = 5;
bestc = 0;
bestg = 0;
error = Inf;
for i = 1:m
for j = 1:n
% v=5折交叉验证,t=2 RBF内核;c,g;s=3是ε-SVR回归;-p设置SVR的损失函数中的e ,默认值为0.1
cmd = ['-v ',num2str(v),' -t 2',' -c ',num2str(2^c(i,j)),' -g ',num2str(2^g(i,j) ),' -s 3 -p 0.1'];
cg(i,j) = svmtrain(tn_train,pn_train,cmd);
if cg(i,j) < error
error = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
if abs(cg(i,j) - error) <= eps && bestc > 2^c(i,j)
error = cg(i,j);
bestc = 2^c(i,j);
bestg = 2^g(i,j);
end
end
end
cmd = [' -t 2',' -c ',num2str(bestc),' -g ',num2str(bestg),' -s 3 -p 0.01'];
%%
% 2. 创建/训练SVM
model = svmtrain(tn_train,pn_train,cmd);
%% V. SVM仿真预测
[Predict_1,error_1,pre] = svmpredict(tn_train,pn_train,model);
[Predict_2,error_2,pre] = svmpredict(tn_test,pn_test,model);
%%
% 1. 反归一化
predict_1 = mapminmax('reverse',Predict_1,outputps);
predict_2 = mapminmax('reverse',Predict_2,outputps);
%%
% 2. 结果对比
result_1 = [t_train predict_1];
result_2 = [t_test predict_2];
%% VI. 绘图
figure(1)
plot(1:length(t_train),t_train,'r-*',1:length(t_train),predict_1,'b:o')
grid on
legend('真实值','预测值')
xlabel('样本编号')
ylabel('耐压强度')
string_1 = {'训练集预测结果对比';
['mse = ' num2str(error_1(2)) ' R^2 = ' num2str(error_1(3))]};
title(string_1)
figure(2)
plot(1:length(t_test),t_test,'r-*',1:length(t_test),predict_2,'b:o')
grid on
legend('真实值','预测值')
xlabel('样本编号')
ylabel('耐压强度')
string_2 = {'测试集预测结果对比';
['mse = ' num2str(error_2(2)) ' R^2 = ' num2str(error_2(3))]};
title(string_2)
%% VII. BP神经网络 神经网络中每一列代表一个样本,支持向量机中每一行代表一个样本,所以要转置
%%
% 1. 数据转置
pn_train = pn_train';
tn_train = tn_train';
pn_test = pn_test';
tn_test = tn_test';
%%
% 2. 创建BP神经网络
net = newff(pn_train,tn_train,10);
%%
% 3. 设置训练参数
net.trainParam.epochs = 1000;
net.trainParam.goal = 1e-3;
net.trainParam.show = 10;
net.trainParam.lr = 0.1;
%%
% 4. 训练网络
net = train(net,pn_train,tn_train);
%%
% 5. 仿真测试
tn_sim = sim(net,pn_test);
%%
% 6. 均方误差
E = mse(tn_sim - tn_test);
%%
% 7. 决定系数
N = size(t_test,1);
R2=(N*sum(tn_sim.*tn_test)-sum(tn_sim)*sum(tn_test))^2/((N*sum((tn_sim).^2)-(sum(tn_sim))^2)*(N*sum((tn_test).^2)-(sum(tn_test))^2));
%%
% 8. 反归一化
t_sim = mapminmax('reverse',tn_sim,outputps);
%%
% 9. 绘图
figure(3)
plot(1:length(t_test),t_test,'r-*',1:length(t_test),t_sim,'b:o')
grid on
legend('真实值','预测值')
xlabel('样本编号')
ylabel('耐压强度')
string_3 = {'测试集预测结果对比(BP神经网络)';
['mse = ' num2str(E) ' R^2 = ' num2str(R2)]};
title(string_3)