人工水母搜索算法—matlab代码
clc clear foj = @ Sphere; Lb = -100; % 搜索空间下界 Ub = 100; % 搜索空间上界 N_iter = 1000; % 最大迭代次数 n_pop = 50; % 种群个数 d = 10; % 种群维度 beta = 3; gamma = 0.1; Z = zeros(n_pop, d); % 随机生成一个d维向量 Z(1, :) = rand(1, d); % 利用logistic生成n_pop个向量 for i=2:n_pop Z(i,:) = 4.0*Z(i-1,:).*(1-Z(i-1,:)); end % 将z的各个分量载波到对应变量的取值区间 pop = zeros(n_pop, d); fitness = zeros(n_pop, 1); for i=1:n_pop pop(i,:) = Lb + (Ub - Lb)*Z(i,:); fitness(i) = foj(pop(i,:)); end mu = mean(pop, 1); figure scatter(pop(:,1), pop(:,2), 'r*'); hold on scatter(mu(:,1), mu(:,2),'ko'); box on [bestScore, loc] = min(fitness); bestPop = pop(loc, :); % 当前种群中食物数目最多的位置 S = pop; % S是更新后的种群 fmin = zeros(N_iter,1); for t=1:N_iter for i=1:n_pop c = abs((1-t/N_iter)*(2*rand-1)); if c>=0.5 % 洋流位置更新公式 trend = bestPop - beta*rand*mu; % 洋流的方向,即论文中的公式.9 S(i,:) = pop(i,:) + rand(1,d).*trend; % 水母位置更新,即论文中的公式.11 else % 种群内部运动 if rand>(1-c) S(i,:) = pop(i,:) + gamma*rand(1,d).*(Ub - Lb); % 被动运动,即论文公式.12 else JK = randperm(n_pop); if foj(pop(JK(1)))>=foj(pop(JK(2))) Direction = pop(JK(2),:) - pop(JK(1),:); else Direction = pop(JK(1),:) - pop(JK(2),:); end Step = rand(1, d).*Direction; S(i,:) = pop(i,:) + Step; % 主动运动,论文公式.16 end end % 检查边界 S(i,:) = simpleBound(S(i,:), Lb, Ub); Fnew = foj(S(i,:)); % 判断是否更新相应位置和适应度值 if Fnew<fitness(i) fitness(i) = Fnew; pop(i,:) = S(i,:); end % 判断是否更新最优值 if Fnew<bestScore bestScore = Fnew; bestPop = S(i,:); end end fmin(t) = bestScore; % 命令窗口输出 disp(['Iteration ' num2str(t) ': Best Cost = ' num2str(bestScore)]); % disp(['Bestpop ' num2str(bestPop)]); end figure semilogy(fmin, 'r-.')
function x=simpleBound(x,Lb,Ub) % 函数名称:越界处理函数 % param x:水母 % param Lb:变量下界 % param Ub:变量上界 d = length(x); for i=1:d if x(i) > Ub x(i) = (x(d) - Ub) + Lb; elseif x(i) < Lb x(i) = (x(d) - Lb) + Ub; end end end
function [y] = Sphere(xx) d = length(xx); sum = 0; for ii = 1:d xi = xx(ii); sum = sum + xi^2; end y = sum; end