GWO(灰狼優化)演算法MATLAB原始碼逐行中文註解
阿新 • • 發佈:2019-01-11
tic % 計時器
%% 清空環境變數
close all
clear
clc
format compact
%% 資料提取
% 載入測試資料wine,其中包含的資料為classnumber = 3,wine:178*13的矩陣,wine_labes:178*1的列向量
load wine.mat
% 選定訓練集和測試集
% 將第一類的1-30,第二類的60-95,第三類的131-153做為訓練集
train_wine = [wine(1:30,:);wine(60:95,:);wine(131:153,:)];
% 相應的訓練集的標籤也要分離出來
train_wine_labels = [wine_labels(1 :30);wine_labels(60:95);wine_labels(131:153)];
% 將第一類的31-59,第二類的96-130,第三類的154-178做為測試集
test_wine = [wine(31:59,:);wine(96:130,:);wine(154:178,:)];
% 相應的測試集的標籤也要分離出來
test_wine_labels = [wine_labels(31:59);wine_labels(96:130);wine_labels(154:178)];
%% 資料預處理
% 資料預處理,將訓練集和測試集歸一化到[0,1]區間
[mtrain,ntrain] = size (train_wine);
[mtest,ntest] = size(test_wine);
dataset = [train_wine;test_wine];
% mapminmax為MATLAB自帶的歸一化函式
[dataset_scale,ps] = mapminmax(dataset',0,1);
dataset_scale = dataset_scale';
train_wine = dataset_scale(1:mtrain,:);
test_wine = dataset_scale( (mtrain+1):(mtrain+mtest),: );
%% 利用灰狼演算法選擇最佳的SVM引數c和g
SearchAgents_no=10; % 狼群數量,Number of search agents
Max_iteration=10; % 最大迭代次數,Maximum numbef of iterations
dim=2; % 此例需要優化兩個引數c和g,number of your variables
lb=[0.01,0.01]; % 引數取值下界
ub=[100,100]; % 引數取值上界
% v = 5; % SVM Cross Validation引數,預設為5
% initialize alpha, beta, and delta_pos
Alpha_pos=zeros(1,dim); % 初始化Alpha狼的位置
Alpha_score=inf; % 初始化Alpha狼的目標函式值,change this to -inf for maximization problems
Beta_pos=zeros(1,dim); % 初始化Beta狼的位置
Beta_score=inf; % 初始化Beta狼的目標函式值,change this to -inf for maximization problems
Delta_pos=zeros(1,dim); % 初始化Delta狼的位置
Delta_score=inf; % 初始化Delta狼的目標函式值,change this to -inf for maximization problems
%Initialize the positions of search agents
Positions=initialization(SearchAgents_no,dim,ub,lb);
Convergence_curve=zeros(1,Max_iteration);
l=0; % Loop counter迴圈計數器
% Main loop主迴圈
while l<Max_iteration % 對迭代次數迴圈
for i=1:size(Positions,1) % 遍歷每個狼
% Return back the search agents that go beyond the boundaries of the search space
% 若搜尋位置超過了搜尋空間,需要重新回到搜尋空間
Flag4ub=Positions(i,:)>ub;
Flag4lb=Positions(i,:)<lb;
% 若狼的位置在最大值和最小值之間,則位置不需要調整,若超出最大值,最回到最大值邊界;
% 若超出最小值,最回答最小值邊界
Positions(i,:)=(Positions(i,:).*(~(Flag4ub+Flag4lb)))+ub.*Flag4ub+lb.*Flag4lb; % ~表示取反
% 計算適應度函式值
cmd = [' -c ',num2str(Positions(i,1)),' -g ',num2str(Positions(i,2))];
model=svmtrain(train_wine_labels,train_wine,cmd); % SVM模型訓練
[~,fitness]=svmpredict(test_wine_labels,test_wine,model); % SVM模型預測及其精度
fitness=100-fitness(1); % 以錯誤率最小化為目標
% Update Alpha, Beta, and Delta
if fitness<Alpha_score % 如果目標函式值小於Alpha狼的目標函式值
Alpha_score=fitness; % 則將Alpha狼的目標函式值更新為最優目標函式值,Update alpha
Alpha_pos=Positions(i,:); % 同時將Alpha狼的位置更新為最優位置
end
if fitness>Alpha_score && fitness<Beta_score % 如果目標函式值介於於Alpha狼和Beta狼的目標函式值之間
Beta_score=fitness; % 則將Beta狼的目標函式值更新為最優目標函式值,Update beta
Beta_pos=Positions(i,:); % 同時更新Beta狼的位置
end
if fitness>Alpha_score && fitness>Beta_score && fitness<Delta_score % 如果目標函式值介於於Beta狼和Delta狼的目標函式值之間
Delta_score=fitness; % 則將Delta狼的目標函式值更新為最優目標函式值,Update delta
Delta_pos=Positions(i,:); % 同時更新Delta狼的位置
end
end
a=2-l*((2)/Max_iteration); % 對每一次迭代,計算相應的a值,a decreases linearly fron 2 to 0
% Update the Position of search agents including omegas
for i=1:size(Positions,1) % 遍歷每個狼
for j=1:size(Positions,2) % 遍歷每個維度
% 包圍獵物,位置更新
r1=rand(); % r1 is a random number in [0,1]
r2=rand(); % r2 is a random number in [0,1]
A1=2*a*r1-a; % 計算係數A,Equation (3.3)
C1=2*r2; % 計算係數C,Equation (3.4)
% Alpha狼位置更新
D_alpha=abs(C1*Alpha_pos(j)-Positions(i,j)); % Equation (3.5)-part 1
X1=Alpha_pos(j)-A1*D_alpha; % Equation (3.6)-part 1
r1=rand();
r2=rand();
A2=2*a*r1-a; % 計算係數A,Equation (3.3)
C2=2*r2; % 計算係數C,Equation (3.4)
% Beta狼位置更新
D_beta=abs(C2*Beta_pos(j)-Positions(i,j)); % Equation (3.5)-part 2
X2=Beta_pos(j)-A2*D_beta; % Equation (3.6)-part 2
r1=rand();
r2=rand();
A3=2*a*r1-a; % 計算係數A,Equation (3.3)
C3=2*r2; % 計算係數C,Equation (3.4)
% Delta狼位置更新
D_delta=abs(C3*Delta_pos(j)-Positions(i,j)); % Equation (3.5)-part 3
X3=Delta_pos(j)-A3*D_delta; % Equation (3.5)-part 3
% 位置更新
Positions(i,j)=(X1+X2+X3)/3;% Equation (3.7)
end
end
l=l+1;
Convergence_curve(l)=Alpha_score;
end
bestc=Alpha_pos(1,1);
bestg=Alpha_pos(1,2);
bestGWOaccuarcy=Alpha_score;
%% 列印引數選擇結果
disp('列印選擇結果');
str=sprintf('Best Cross Validation Accuracy = %g%%,Best c = %g,Best g = %g',bestGWOaccuarcy*100,bestc,bestg);
disp(str)
%% 利用最佳的引數進行SVM網路訓練
cmd_gwosvm = ['-c ',num2str(bestc),' -g ',num2str(bestg)];
model_gwosvm = svmtrain(train_wine_labels,train_wine,cmd_gwosvm);
%% SVM網路預測
[predict_label,accuracy] = svmpredict(test_wine_labels,test_wine,model_gwosvm);
% 列印測試集分類準確率
total = length(test_wine_labels);
right = sum(predict_label == test_wine_labels);
disp('列印測試集分類準確率');
str = sprintf( 'Accuracy = %g%% (%d/%d)',accuracy(1),right,total);
disp(str);
%% 結果分析
% 測試集的實際分類和預測分類圖
figure;
hold on;
plot(test_wine_labels,'o');
plot(predict_label,'r*');
xlabel('測試集樣本','FontSize',12);
ylabel('類別標籤','FontSize',12);
legend('實際測試集分類','預測測試集分類');
title('測試集的實際分類和預測分類圖','FontSize',12);
grid on
snapnow
%% 顯示程式執行時間
toc
% This function initialize the first population of search agents
function Positions=initialization(SearchAgents_no,dim,ub,lb)
Boundary_no= size(ub,2); % numnber of boundaries
% If the boundaries of all variables are equal and user enter a signle
% number for both ub and lb
if Boundary_no==1
Positions=rand(SearchAgents_no,dim).*(ub-lb)+lb;
end
% If each variable has a different lb and ub
if Boundary_no>1
for i=1:dim
ub_i=ub(i);
lb_i=lb(i);
Positions(:,i)=rand(SearchAgents_no,1).*(ub_i-lb_i)+lb_i;
end
end
(廣告)歡迎掃描關注微信公眾號:Genlovhyy的資料小站(Gnelovy212)