1 tic % 计时器
2 %% 清空环境变量
3 close all
4 clear
5 clc
6 format compact
7 %% 数据提取
8 % 载入测试数据wine,其中包含的数据为classnumber = 3,wine:178*13的矩阵,wine_labes:178*1的列向量
9 load wine.mat
10 % 选定训练集和测试集
11 % 将第一类的1-30,第二类的60-95,第三类的131-153做为训练集
12 train_wine = [wine(1:30,:);wine(60:95,:);wine(131:153,:)];
13 % 相应的训练集的标签也要分离出来
14 train_wine_labels = [wine_labels(1:30);wine_labels(60:95);wine_labels(131:153)];
15 % 将第一类的31-59,第二类的96-130,第三类的154-178做为测试集
16 test_wine = [wine(31:59,:);wine(96:130,:);wine(154:178,:)];
17 % 相应的测试集的标签也要分离出来
18 test_wine_labels = [wine_labels(31:59);wine_labels(96:130);wine_labels(154:178)];
19 %% 数据预处理
20 % 数据预处理,将训练集和测试集归一化到[0,1]区间
21 [mtrain,ntrain] = size(train_wine);
22 [mtest,ntest] = size(test_wine);
23
24 dataset = [train_wine;test_wine];
25 % mapminmax为MATLAB自带的归一化函数
26 [dataset_scale,ps] = mapminmax(dataset',0,1);
27 dataset_scale = dataset_scale';
28
29 train_wine = dataset_scale(1:mtrain,:);
30 test_wine = dataset_scale( (mtrain+1):(mtrain+mtest),: );
31 %% 利用灰狼算法选择最佳的SVM参数c和g
32 SearchAgents_no=10; % 狼群数量,Number of search agents
33 Max_iteration=10; % 最大迭代次数,Maximum numbef of iterations
34 dim=2; % 此例需要优化两个参数c和g,number of your variables
35 lb=[0.01,0.01]; % 参数取值下界
36 ub=[100,100]; % 参数取值上界
37 % v = 5; % SVM Cross Validation参数,默认为5
38
39 % initialize alpha, beta, and delta_pos
40 Alpha_pos=zeros(1,dim); % 初始化Alpha狼的位置
41 Alpha_score=inf; % 初始化Alpha狼的目标函数值,change this to -inf for maximization problems
42
43 Beta_pos=zeros(1,dim); % 初始化Beta狼的位置
44 Beta_score=inf; % 初始化Beta狼的目标函数值,change this to -inf for maximization problems
45
46 Delta_pos=zeros(1,dim); % 初始化Delta狼的位置
47 Delta_score=inf; % 初始化Delta狼的目标函数值,change this to -inf for maximization problems
48
49 %Initialize the positions of search agents
50 Positions=initialization(SearchAgents_no,dim,ub,lb);
51
52 Convergence_curve=zeros(1,Max_iteration);
53
54 l=0; % Loop counter循环计数器
55
56 % Main loop主循环
57 while l<Max_iteration % 对迭代次数循环
58 for i=1:size(Positions,1) % 遍历每个狼
59
60 % Return back the search agents that go beyond the boundaries of the search space
61 % 若搜索位置超过了搜索空间,需要重新回到搜索空间
62 Flag4ub=Positions(i,:)>ub;
63 Flag4lb=Positions(i,:)<lb;
64 % 若狼的位置在最大值和最小值之间,则位置不需要调整,若超出最大值,最回到最大值边界;
65 % 若超出最小值,最回答最小值边界
66 Positions(i,:)=(Positions(i,:).*(~(Flag4ub+Flag4lb)))+ub.*Flag4ub+lb.*Flag4lb; % ~表示取反
67
68 % 计算适应度函数值
69 cmd = [' -c ',num2str(Positions(i,1)),' -g ',num2str(Positions(i,2))];
70 model=svmtrain(train_wine_labels,train_wine,cmd); % SVM模型训练
71 [~,fitness]=svmpredict(test_wine_labels,test_wine,model); % SVM模型预测及其精度
72 fitness=100-fitness(1); % 以错误率最小化为目标
73
74 % Update Alpha, Beta, and Delta
75 if fitness<Alpha_score % 如果目标函数值小于Alpha狼的目标函数值
76 Alpha_score=fitness; % 则将Alpha狼的目标函数值更新为最优目标函数值,Update alpha
77 Alpha_pos=Positions(i,:); % 同时将Alpha狼的位置更新为最优位置
78 end
79
80 if fitness>Alpha_score && fitness<Beta_score % 如果目标函数值介于于Alpha狼和Beta狼的目标函数值之间
81 Beta_score=fitness; % 则将Beta狼的目标函数值更新为最优目标函数值,Update beta
82 Beta_pos=Positions(i,:); % 同时更新Beta狼的位置
83 end
84
85 if fitness>Alpha_score && fitness>Beta_score && fitness<Delta_score % 如果目标函数值介于于Beta狼和Delta狼的目标函数值之间
86 Delta_score=fitness; % 则将Delta狼的目标函数值更新为最优目标函数值,Update delta
87 Delta_pos=Positions(i,:); % 同时更新Delta狼的位置
88 end
89 end
90
91 a=2-l*((2)/Max_iteration); % 对每一次迭代,计算相应的a值,a decreases linearly fron 2 to 0
92
93 % Update the Position of search agents including omegas
94 for i=1:size(Positions,1) % 遍历每个狼
95 for j=1:size(Positions,2) % 遍历每个维度
96
97 % 包围猎物,位置更新
98
99 r1=rand(); % r1 is a random number in [0,1]
100 r2=rand(); % r2 is a random number in [0,1]
101
102 A1=2*a*r1-a; % 计算系数A,Equation (3.3)
103 C1=2*r2; % 计算系数C,Equation (3.4)
104
105 % Alpha狼位置更新
106 D_alpha=abs(C1*Alpha_pos(j)-Positions(i,j)); % Equation (3.5)-part 1
107 X1=Alpha_pos(j)-A1*D_alpha; % Equation (3.6)-part 1
108
109 r1=rand();
110 r2=rand();
111
112 A2=2*a*r1-a; % 计算系数A,Equation (3.3)
113 C2=2*r2; % 计算系数C,Equation (3.4)
114
115 % Beta狼位置更新
116 D_beta=abs(C2*Beta_pos(j)-Positions(i,j)); % Equation (3.5)-part 2
117 X2=Beta_pos(j)-A2*D_beta; % Equation (3.6)-part 2
118
119 r1=rand();
120 r2=rand();
121
122 A3=2*a*r1-a; % 计算系数A,Equation (3.3)
123 C3=2*r2; % 计算系数C,Equation (3.4)
124
125 % Delta狼位置更新
126 D_delta=abs(C3*Delta_pos(j)-Positions(i,j)); % Equation (3.5)-part 3
127 X3=Delta_pos(j)-A3*D_delta; % Equation (3.5)-part 3
128
129 % 位置更新
130 Positions(i,j)=(X1+X2+X3)/3;% Equation (3.7)
131
132 end
133 end
134 l=l+1;
135 Convergence_curve(l)=Alpha_score;
136 end
137 bestc=Alpha_pos(1,1);
138 bestg=Alpha_pos(1,2);
139 bestGWOaccuarcy=Alpha_score;
140 %% 打印参数选择结果
141 disp('打印选择结果');
142 str=sprintf('Best Cross Validation Accuracy = %g%%,Best c = %g,Best g = %g',bestGWOaccuarcy*100,bestc,bestg);
143 disp(str)
144 %% 利用最佳的参数进行SVM网络训练
145 cmd_gwosvm = ['-c ',num2str(bestc),' -g ',num2str(bestg)];
146 model_gwosvm = svmtrain(train_wine_labels,train_wine,cmd_gwosvm);
147 %% SVM网络预测
148 [predict_label,accuracy] = svmpredict(test_wine_labels,test_wine,model_gwosvm);
149 % 打印测试集分类准确率
150 total = length(test_wine_labels);
151 right = sum(predict_label == test_wine_labels);
152 disp('打印测试集分类准确率');
153 str = sprintf( 'Accuracy = %g%% (%d/%d)',accuracy(1),right,total);
154 disp(str);
155 %% 结果分析
156 % 测试集的实际分类和预测分类图
157 figure;
158 hold on;
159 plot(test_wine_labels,'o');
160 plot(predict_label,'r*');
161 xlabel('测试集样本','FontSize',12);
162 ylabel('类别标签','FontSize',12);
163 legend('实际测试集分类','预测测试集分类');
164 title('测试集的实际分类和预测分类图','FontSize',12);
165 grid on
166 snapnow
167 %% 显示程序运行时间
168 toc