遗传算法实现 但货郎问题(tsp)

声明,这个是组员的,不是我的,贴出来大家瞅瞅吧。不过是用matlab实现的

 

This is an introduction to genetic algorithm methods for optimization. Genetic algorithms were formally introduced in the United States in the 1970s by John Holland at University of Michigan. The continuing price/performance improvements of computational systems has made them attractive for some types of optimization. In particular, genetic algorithms work very well on mixed (continuous and discrete), combinatorial problems. They are less susceptible to getting 'stuck' at local optima than gradient search methods. But they tend to be computationally expensive.
To use a genetic algorithm, you must represent a solution to your problem as a genome (or chromosome). The genetic algorithm then creates a population of solutions and applies genetic operators such as mutation and crossover to evolve the solutions in order to find the best one(s).
This presentation outlines some of the basics of genetic algorithms. The three most important aspects of using genetic algorithms are: definition of the objective function, definition and implementation of the genetic representation, and definition and implementation of the genetic operators. Once these three have been defined, the generic genetic algorithm should work fairly well. Beyond that you can try many different variations to improve performance, find multiple optima, or parallelize the algorithms.
                  The description of the GA method
Step 1: Initialization, set up population's scale N, encodes the chromosome with the law of natural number; GenN∶= 0, Produce the initial population Pop (0)
Step 2: To every chromosome in the population, calculate the fitness and record the best solution (has the biggest fitness) at present;
Step 3: If the result fulfils the request of the problem, stop and output the result; otherwise transfer to step 5
Step 4: According to the elite and rim plate gamble back-and-forth method, chose Pop (N+1) from Pop (GenN), produce the next generation.
Step 5: Using crossover and mutation operator reproduce variations remake Pop (N+1).
Step 6: GenN ∶= GenN + 1; transfer to step3

 

 

code:

 

function gaTSP

CityNum=52;
[dislist,Clist]=tsp(CityNum);

inn=500; %Initial population size
gnmax=100;  %Max algebra
pc=0.8; %Crossover probability
pm=0.8; %Mutation probability

%produce initial population
for i=1:inn
    s(i,:)=randperm(CityNum);
end
[f,p]=objf(s,dislist);

gn=1;
while gn<gnmax+1
   for j=1:2:inn
      seln=sel(s,p);  %Choice operate
      scro=cro(s,seln,pc);  %Crossover operate
      scnew(j,:)=scro(1,:);
      scnew(j+1,:)=scro(2,:);
      smnew(j,:)=mut(scnew(j,:),pm);  %mutation operate
      smnew(j+1,:)=mut(scnew(j+1,:),pm);
   end
   s=smnew;  %produce the new group
   [f,p]=objf(s,dislist);  %compute the suitability of new group
   %enregister the average suitability of the optimal now
   [fmax,nmax]=max(f);
   ymean(gn)=1000/mean(f);
   ymax(gn)=1000/fmax;
   %Set down the optimal individual now
   x=s(nmax,:);
   drawTSP(Clist,x,ymax(gn),gn,0);
   gn=gn+1;
   %pause;
end
gn=gn-1;

figure(2);
plot(ymax,'r'); hold on;
plot(ymean,'b');grid;
title('Searching Process');
legend('The optimal solution','The average solution');
end

%------------------------------------------------
%Compute suitability fuction
function [f,p]=objf(s,dislist);

inn=size(s,1);  %read the size of group
for i=1:inn
   f(i)=CalDist(dislist,s(i,:));  %Compute fuction result,i.e suitablitiy
end
f=1000./f';
%Compute the probability of chioce
fsum=0;
for i=1:inn
   fsum=fsum+f(i)^15;
end
for i=1:inn
   ps(i)=f(i)^15/fsum;
end
%Compute the probability of cumulation
p(1)=ps(1);
for i=2:inn
   p(i)=p(i-1)+ps(i);
end
p=p';
end

%--------------------------------------------------
function pcc=pro(pc);

test(1:100)=0;
l=round(100*pc);
test(1:l)=1;
n=round(rand*99)+1;
pcc=test(n);  
end

%--------------------------------------------------
%“Choice”operate
function seln=sel(s,p);

inn=size(p,1);
%Choice two individuals from group
for i=1:2
   r=rand;  %get a radom number
   prand=p-r;
   j=1;
   while prand(j)<0
       j=j+1;
   end
   seln(i)=j; %The number of choiced individual
end
end

%------------------------------------------------
%“Crossover”Operate
function scro=cro(s,seln,pc);

bn=size(s,2);
pcc=pro(pc);  %According to the probability of crossover,decide whether to get the crossover operation,1 yes,0 no.
scro(1,:)=s(seln(1),:);
scro(2,:)=s(seln(2),:);
if pcc==1
   c1=round(rand*(bn-2))+1;  %produce a radom crossover point in [1,bn-1]
   c2=round(rand*(bn-2))+1;
   chb1=min(c1,c2);
   chb2=max(c1,c2);
   middle=scro(1,chb1+1:chb2);
   scro(1,chb1+1:chb2)=scro(2,chb1+1:chb2);
   scro(2,chb1+1:chb2)=middle;
   for i=1:chb1
       while find(scro(1,chb1+1:chb2)==scro(1,i))
           zhi=find(scro(1,chb1+1:chb2)==scro(1,i));
           y=scro(2,chb1+zhi);
           scro(1,i)=y;
       end
       while find(scro(2,chb1+1:chb2)==scro(2,i))
           zhi=find(scro(2,chb1+1:chb2)==scro(2,i));
           y=scro(1,chb1+zhi);
           scro(2,i)=y;
       end
   end
   for i=chb2+1:bn
       while find(scro(1,1:chb2)==scro(1,i))
           zhi=find(scro(1,1:chb2)==scro(1,i));
           y=scro(2,zhi);
           scro(1,i)=y;
       end
       while find(scro(2,1:chb2)==scro(2,i))
           zhi=find(scro(2,1:chb2)==scro(2,i));
           y=scro(1,zhi);
           scro(2,i)=y;
       end
   end
end
end

%--------------------------------------------------
%“mutation”operate
function snnew=mut(snew,pm);

bn=size(snew,2);
snnew=snew;

pmm=pro(pm);  %According to the probability of mutation,decide whether to get the crossover operation,1 yes,0 no.
if pmm==1
   c1=round(rand*(bn-2))+1;  %produce a radom mutation point in [1,bn-1]
   c2=round(rand*(bn-2))+1;
   chb1=min(c1,c2);
   chb2=max(c1,c2);
   x=snew(chb1+1:chb2);
   snnew(chb1+1:chb2)=fliplr(x);
end
end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的遗传算法实现货郎问题的代码: ```python import random # 城市坐标 CITIES = {"A": (0, 0), "B": (1, 5), "C": (5, 2), "D": (8, 3), "E": (6, 8)} # 遗传算法参数 POPULATION_SIZE = 50 ELITISM_RATE = 0.1 MUTATION_RATE = 0.1 GENERATIONS = 100 # 计算两个城市之间的距离 def distance(city1, city2): x1, y1 = CITIES[city1] x2, y2 = CITIES[city2] return ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 # 生成一个随机的个体(城市排列) def generate_individual(): cities = list(CITIES.keys()) random.shuffle(cities) return cities # 计算一个个体的适应度(路线总长度) def fitness(individual): return sum(distance(individual[i], individual[i+1]) for i in range(len(individual)-1)) + distance(individual[-1], individual[0]) # 选择下一代个体 def select(population): elites_size = int(ELITISM_RATE * len(population)) elites = sorted(population, key=lambda x: fitness(x))[:elites_size] parents = population[elites_size:] total_fitness = sum(fitness(p) for p in parents) probabilities = [fitness(p) / total_fitness for p in parents] selected = [] for i in range(len(parents)): selected.append(random.choices(parents, probabilities)[0]) return elites + selected # 交叉两个个体,生成新的个体 def crossover(individual1, individual2): start = random.randint(0, len(individual1) - 1) end = random.randint(start, len(individual1) - 1) child = individual1[start:end] for city in individual2: if city not in child: child.append(city) return child # 变异一个个体 def mutate(individual): if random.random() < MUTATION_RATE: i = random.randint(0, len(individual) - 1) j = random.randint(0, len(individual) - 1) individual[i], individual[j] = individual[j], individual[i] # 遗传算法主函数 def genetic_algorithm(): population = [generate_individual() for _ in range(POPULATION_SIZE)] for _ in range(GENERATIONS): population = select(population) new_population = [] while len(new_population) < POPULATION_SIZE: parent1, parent2 = random.sample(population, 2) child = crossover(parent1, parent2) mutate(child) new_population.append(child) population = new_population best_individual = sorted(population, key=lambda x: fitness(x))[0] return best_individual, fitness(best_individual) # 测试遗传算法 best_individual, best_fitness = genetic_algorithm() print(f"最短路线: {' -> '.join(best_individual)}") print(f"总长度: {best_fitness}") ``` 该代码使用遗传算法求解五个城市之间的最短路线,其中`CITIES`定义了五个城市的坐标,`POPULATION_SIZE`定义了每一代的个体数量,`ELITISM_RATE`定义了保留精英的比例,`MUTATION_RATE`定义了变异率,`GENERATIONS`定义了遗传算法的迭代次数。在`select`函数中,使用了轮盘赌选择算法来选择下一代个体;在`crossover`函数中,使用了部分映射交叉算法;在`mutate`函数中,使用了交换两个城市的位置的变异操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值