基于MATLAB的免疫遗传算法求解TSP实例
时间: 2023-10-27 14:06:30 浏览: 104
以下是MATLAB代码实现免疫遗传算法求解TSP问题的示例:
% TSP问题实例
city = [0, 0; 2, 3; 4, 3; 6, 1; 7, 5; 8, 0; 10, 2; 11, 6; 12, 4; 14, 5];
% 初始化参数
pop_size = 100; % 种群大小
max_gen = 200; % 最大迭代次数
p_crossover = 0.9; % 交叉概率
p_mutation = 0.1; % 变异概率
n_elite = 10; % 精英数量
n_imm = 10; % 免疫数量
n_sel = pop_size - n_elite - n_imm; % 选择数量
% 初始化种群
pop = zeros(pop_size, size(city, 1));
for i = 1:pop_size
pop(i, :) = randperm(size(city, 1));
end
% 迭代
for gen = 1:max_gen
% 计算适应度
fitness = zeros(pop_size, 1);
for i = 1:pop_size
fitness(i) = tsp_fitness(pop(i, :), city);
end
% 选择
[fitness_sorted, idx] = sort(fitness, 'ascend');
elite = pop(idx(1:n_elite), :);
imm = pop(idx(n_elite+1:n_elite+n_imm), :);
sel_idx = rws(fitness_sorted(n_elite+n_imm+1:end), n_sel);
sel = pop(idx(n_elite+n_imm+sel_idx), :);
% 交叉
offspring = zeros(size(sel));
for i = 1:size(sel, 1)/2
if rand < p_crossover
[offspring(2*i-1,:), offspring(2*i,:)] = tsp_crossover(sel(2*i-1,:), sel(2*i,:));
else
offspring(2*i-1,:) = sel(2*i-1,:);
offspring(2*i,:) = sel(2*i,:);
end
end
% 变异
for i = 1:size(offspring, 1)
if rand < p_mutation
offspring(i,:) = tsp_mutation(offspring(i,:));
end
end
% 合并种群
pop = [elite; imm; offspring];
end
% 计算最优路径
fitness = zeros(pop_size, 1);
for i = 1:pop_size
fitness(i) = tsp_fitness(pop(i, :), city);
end
[~, idx] = min(fitness);
best_path = pop(idx, :);
best_fitness = fitness(idx);
% 绘图
figure;
plot(city(:,1), city(:,2), 'o');
hold on;
plot(city(best_path,1), city(best_path,2), '-');
title(sprintf('Best Fitness = %f', best_fitness));
% TSP适应度函数
function fitness = tsp_fitness(path, city)
fitness = 0;
for i = 1:length(path)-1
fitness = fitness + norm(city(path(i),:) - city(path(i+1),:));
end
fitness = fitness + norm(city(path(end),:) - city(path(1),:));
end
% TSP交叉函数
function [offspring1, offspring2] = tsp_crossover(parent1, parent2)
len = length(parent1);
pt1 = randi(len-1);
pt2 = randi([pt1+1, len]);
mask = zeros(1, len);
mask(pt1:pt2) = 1;
offspring1 = zeros(1, len);
offspring2 = zeros(1, len);
offspring1(mask==1) = parent1(mask==1);
offspring2(mask==1) = parent2(mask==1);
idx1 = find(~ismember(parent2, offspring1));
idx2 = find(~ismember(parent1, offspring2));
offspring1(idx2) = parent2(idx1);
offspring2(idx1) = parent1(idx2);
end
% TSP变异函数
function offspring = tsp_mutation(parent)
len = length(parent);
pt1 = randi(len);
pt2 = randi(len);
while pt2 == pt1
pt2 = randi(len);
end
offspring = parent;
offspring([pt1 pt2]) = offspring([pt2 pt1]);
end
% 轮盘赌选择函数
function idx = rws(fitness, n_select)
total_fitness = sum(fitness);
p = fitness / total_fitness;
c = cumsum(p);
idx = zeros(n_select, 1);
for i = 1:n_select
r = rand;
j = find(c>=r, 1);
idx(i) = j;
end
end
阅读全文