免疫遗传算法matlab代码
时间: 2023-07-09 17:43:07 浏览: 236
以下是一个简单的免疫遗传算法的 MATLAB 代码示例,用于最小化 Rosenbrock 函数:
```
function [best, best_fitness] = immune_genetic_algorithm()
% 初始化参数
pop_size = 50; % 种群大小
max_gen = 100; % 最大迭代次数
pc = 0.8; % 交叉概率
pm = 0.1; % 变异概率
clone_rate = 0.5; % 克隆率
suppress_rate = 0.01; % 抑制率
lb = -5; % 变量下界
ub = 5; % 变量上界
dim = 2; % 变量维数
% 初始化种群
pop = lb + (ub-lb)*rand(pop_size, dim);
fitness = rosenbrock(pop); % 计算适应度
% 迭代
for i = 1:max_gen
% 选择
[selected_pop, selected_fitness] = immune_selection(pop, fitness, clone_rate, suppress_rate);
% 交叉
offspring_pop = immune_crossover(selected_pop, pc);
% 变异
mutated_pop = immune_mutation(offspring_pop, pm, lb, ub);
% 合并种群
pop = [pop; mutated_pop];
fitness = [fitness; rosenbrock(mutated_pop)];
% 环境选择
[pop, fitness] = immune_environment_selection(pop, fitness, pop_size);
% 记录最优解
[best_fitness, idx] = min(fitness);
best = pop(idx, :);
% 显示迭代过程
fprintf('Generation %d: Best fitness = %f\n', i, best_fitness);
end
end
% 适应度函数
function f = rosenbrock(x)
f = sum(100*(x(:,2)-x(:,1).^2).^2 + (1-x(:,1)).^2, 2);
end
% 免疫选择
function [selected_pop, selected_fitness] = immune_selection(pop, fitness, clone_rate, suppress_rate)
n = size(pop, 1);
n_clone = round(clone_rate * n);
n_suppress = round(suppress_rate * n);
[~, idx] = sort(fitness, 'descend');
selected_pop = pop(idx(1:n_clone), :);
selected_fitness = fitness(idx(1:n_clone));
selected_pop = [selected_pop; pop(idx(n-n_suppress+1:n), :)];
selected_fitness = [selected_fitness; fitness(idx(n-n_suppress+1:n))];
end
% 免疫交叉
function offspring_pop = immune_crossover(selected_pop, pc)
n = size(selected_pop, 1);
idx = randperm(n);
n_crossover = round(pc * n/2) * 2;
offspring_pop = zeros(n_crossover, size(selected_pop, 2));
for i = 1:n_crossover
p1 = selected_pop(idx(mod(i-1, n)+1), :);
p2 = selected_pop(idx(mod(i, n)+1), :);
[c1, c2] = single_point_crossover(p1, p2);
offspring_pop(i,:) = c1;
offspring_pop(i+1,:) = c2;
end
end
% 单点交叉
function [c1, c2] = single_point_crossover(p1, p2)
n = length(p1);
idx = randi(n-1);
c1 = [p1(1:idx), p2(idx+1:end)];
c2 = [p2(1:idx), p1(idx+1:end)];
end
% 免疫变异
function mutated_pop = immune_mutation(offspring_pop, pm, lb, ub)
n = size(offspring_pop, 1);
n_mutated = round(pm * n);
mutated_pop = offspring_pop;
for i = 1:n_mutated
j = randi(n);
mutated_pop(j, :) = lb + (ub-lb) * rand(1, size(offspring_pop, 2));
end
end
% 免疫环境选择
function [pop, fitness] = immune_environment_selection(pop, fitness, pop_size)
n = size(pop, 1);
[~, idx] = sort(fitness, 'ascend');
pop = pop(idx(1:pop_size), :);
fitness = fitness(idx(1:pop_size));
end
```
该代码实现了免疫遗传算法的基本流程,包括初始化种群、选择、交叉、变异、环境选择等操作。其中,适应度函数使用了经典的 Rosenbrock 函数,可以根据实际需求进行修改。
阅读全文