【遗传算法GA】--TSP旅行商问题(Python)

一.基础介绍

遗传算法的来源、定义、特点见之前的文章【遗传算法GA】–计算函数最值(Python)


下面我们先来看本次需要实现的内容:我们随机生成一些城市的坐标,然后找一条最短路径通过所有城市。

最重要的还是对染色体DNA的编码以及适应度函数的确定。对于本题来说可以先将所以城市进行编号,然后对这些编号进行排序,排好的顺序就是旅行的路线。对于适应度函数来说就是将路程加起来,总路程最小,适应度越高。

参数:

参数名称含义
citys城市个数
pc交叉概率
pm变异概率
popsize种群规模
iternum迭代次数
pop种群
city_position城市坐标

二.分布实现

∙ \bullet 参数

citys = 20 #染色体DNA长度
pc = 0.1 #交叉概率
pm = 0.02 #变异概率
popsize = 500 #种群规模
iternum = 100 #迭代次数

GA类:

∙ \bullet 将种群中排好的序列横纵坐标分别提取出来transltaeDNA函数:参数DNA为种群pop,参数city_position为所有城市坐标

def translateDNA(self,DNA,city_position):
    #生成等长的空列表
    lineX = np.empty_like(DNA,dtype=np.float64)
    lineY = np.empty_like(DNA,dtype=np.float64)
    #将下标和值同时提取出来
    for i,d in enumerate(DNA):
        city_coord = city_position[d]
        lineX[i,:] = city_coord[:,0]
        lineY[i,:] = city_coord[:,1]
    return lineX,lineY

∙ \bullet 求适应度函数getFiness:参数lineX、lineY分别为城市坐标,返回fitness为每个个体的适应度,totalDis为每个个体的总路程。

def getFitness(self,lineX,lineY):
    totalDis = np.empty((lineX.shape[0],),dtype=np.float64)
    for i,(xval,yval) in enumerate(zip(lineX,lineY)):
        totalDis[i]=np.sum(np.sqrt(np.square(np.diff(xval)) + np.square(np.diff(yval))))
    fitness = np.exp(self.citys*2/totalDis)
    return fitness,totalDis

∙ \bullet 选择函数selection:参数fitness为适应度,选择适应度更高的个体。

def selection(self,fitness):
    idx = np.random.choice(np.arange(self.popsize),size=self.popsize,replace=True,p=fitness/fitness.sum())
    return self.pop[idx]

∙ \bullet 交叉函数selection:参数parent为父本中一个个体,pop为种群。

交叉规则:在交叉概率内随机选择种群中一个体,随机选择一些位置,将这些位置的数提取出来放到数组前面,然后将母本中除这些数之外的数按顺序放入数组后面,组成新个体。

def crossover(self,parent,pop):
    if np.random.rand() < self.pc:
        i = np.random.randint(0, self.popsize, size=1)  #随机选取一个个体进行交换                      
        cross_points = np.random.randint(0, 2, self.citys).astype(np.bool)   #随机选择个体中的一些位置
        keep_city = parent[~cross_points]     #将parent中False的位置返给keep_city                                  
        swap_city = pop[i, np.isin(pop[i].ravel(), keep_city, invert=True)]  #将keep_city中没有出现的数赋给swap_city
        parent[:] = np.concatenate((keep_city, swap_city)) #拼接形成新个体
    return parent

∙ \bullet 变异函数mutation:在变异范围内随机选取一个位置与下标位置的数进行互换。

def mutation(self,child):
    for point in range(self.citys):
        if np.random.rand()<self.pm:
            swap_point = np.random.randint(0,self.citys)
            swapa,swapb = child[point],child[swap_point]
            child[point],child[swap_point] = swapb,swapa
    return child

∙ \bullet 进化函数evolve:调用交叉函数和变异函数。

def evolve(self,fitness):
    pop = self.selection(fitness)
    pop_copy = pop.copy()
    for parent in pop: 
        child = self.crossover(parent,pop_copy)
        child = self.mutation(child)
        parent[:] = child
    self.pop = pop

TSP类

∙ \bullet 构造函数:随机生成城市坐标

def __init__(self,citys):
    #生成每个城市的横纵坐标
    self.city_position = np.random.rand(citys,2)
    plt.ion()

∙ \bullet 绘图函数plotting:参数lx、ly为城市横纵坐标,total_d最优路线。

def plotting(self,lx,ly,total_d):
    plt.cla()
    plt.scatter(self.city_position[:, 0].T, self.city_position[:, 1].T, s=100, c='k')  #画散点图
    plt.plot(lx.T, ly.T, 'r-') #连线
    plt.text(-0.05, -0.05, "Total distance=%.2f" % total_d, fontdict={'size': 20, 'color': 'red'})
    plt.xlim((-0.1, 1.1))
    plt.ylim((-0.1, 1.1))
    plt.pause(0.01)

∙ \bullet 主函数

if __name__=='__main__':
    ga = GA(citys=citys,pc=pc,pm=pm,popsize=popsize)
    env = TSP(citys=citys)
    
    for gen in range(iternum):
        lx,ly = ga.translateDNA(ga.pop,env.city_position)
        fitness,total_distance = ga.getFitness(lx,ly)
        ga.evolve(fitness)
        best_idx = np.argmax(fitness) #最优解的下标
        print("Gen:", gen," | best fit: %.2f"%fitness[best_idx],)
        
        env.plotting(lx[best_idx],ly[best_idx],total_distance[best_idx])
    
    plt.ioff()
    plt.show()

三.完整代码

import numpy as np
import matplotlib.pyplot as plt


#参数
citys = 20 #染色体DNA长度
pc = 0.1 #交叉概率
pm = 0.02 #变异概率
popsize = 500 #种群规模
iternum = 100 #迭代次数

class GA(object):
    def __init__(self,citys,pc,pm,popsize,):
        self.citys = citys
        self.pc = pc
        self.pm = pm
        self.popsize = popsize
        
        #vstck纵向拼接数组,permutaion将数字0-(city-1)进行随机排序
        #生成种群,dna序列为0到city的随机序列
        self.pop = np.vstack([np.random.permutation(citys) for _ in range(popsize)])
    
    #将种群中排好的序列横纵坐标分别提取出来
    def translateDNA(self,DNA,city_position):
        #生成等长的空列表
        lineX = np.empty_like(DNA,dtype=np.float64)
        lineY = np.empty_like(DNA,dtype=np.float64)
        #将下标和值同时提取出来
        for i,d in enumerate(DNA):
            city_coord = city_position[d]
            lineX[i,:] = city_coord[:,0]
            lineY[i,:] = city_coord[:,1]
        return lineX,lineY

    
    def getFitness(self,lineX,lineY):
        totalDis = np.empty((lineX.shape[0],),dtype=np.float64)
        for i,(xval,yval) in enumerate(zip(lineX,lineY)):
            totalDis[i]=np.sum(np.sqrt(np.square(np.diff(xval)) + np.square(np.diff(yval))))
        fitness = np.exp(self.citys*2/totalDis)
        return fitness,totalDis
        
    def selection(self,fitness):
        idx = np.random.choice(np.arange(self.popsize),size=self.popsize,replace=True,p=fitness/fitness.sum())
        return self.pop[idx]
        
    def crossover(self,parent,pop):
        if np.random.rand() < self.pc:
            i = np.random.randint(0, self.popsize, size=1)  #随机选取一个个体进行交换                      
            cross_points = np.random.randint(0, 2, self.citys).astype(np.bool)   #随机选择个体中的一些位置
            keep_city = parent[~cross_points]     #将parent中False的位置返给keep_city                                  
            swap_city = pop[i, np.isin(pop[i].ravel(), keep_city, invert=True)]  #将keep_city中没有出现的数赋给swap_city
            parent[:] = np.concatenate((keep_city, swap_city)) #拼接形成新个体
        return parent
        
    def mutation(self,child):
        for point in range(self.citys):
            if np.random.rand()<self.pm:
                swap_point = np.random.randint(0,self.citys)
                swapa,swapb = child[point],child[swap_point]
                child[point],child[swap_point] = swapb,swapa
        return child
            
    def evolve(self,fitness):
        pop = self.selection(fitness)
        pop_copy = pop.copy()
        for parent in pop: 
            child = self.crossover(parent,pop_copy)
            child = self.mutation(child)
            parent[:] = child
        self.pop = pop
            
        
    
class TSP(object):
    def __init__(self,citys):
        #生成每个城市的横纵坐标
        self.city_position = np.random.rand(citys,2)
        plt.ion()
        
    def plotting(self,lx,ly,total_d):
        plt.cla()
        plt.scatter(self.city_position[:, 0].T, self.city_position[:, 1].T, s=100, c='k')  #画散点图
        plt.plot(lx.T, ly.T, 'r-') #连线
        plt.text(-0.05, -0.05, "Total distance=%.2f" % total_d, fontdict={'size': 20, 'color': 'red'})
        plt.xlim((-0.1, 1.1))
        plt.ylim((-0.1, 1.1))
        plt.pause(0.01)
        
if __name__=='__main__':
    ga = GA(citys=citys,pc=pc,pm=pm,popsize=popsize)
    env = TSP(citys=citys)
    
    for gen in range(iternum):
        lx,ly = ga.translateDNA(ga.pop,env.city_position)
        fitness,total_distance = ga.getFitness(lx,ly)
        ga.evolve(fitness)
        best_idx = np.argmax(fitness) #最优解的下标
        print("Gen:", gen," | best fit: %.2f"%fitness[best_idx],)
        
        env.plotting(lx[best_idx],ly[best_idx],total_distance[best_idx])
    
    plt.ioff()
    plt.show()
    
    

    

四.结果截图

初始情况(进行100次迭代):在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 13
    点赞
  • 51
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
TSP问题是一个经典的组合优化问题,遗传算法是其中一种求解TSP问题的启发式算法。下面是遗传算法求解TSP问题的步骤: 1. 初始化种群:随机生成一定数量的路径作为初始种群。 2. 适应度函数:计算每个个体的适应度,即路径的总长度。 3. 选择操作:根据适应度函数选择优秀的个体,用于产生下一代种群。 4. 交叉操作:从父代中选择两个个体,通过交叉操作产生两个子代。 5. 变异操作:对子代进行变异操作,增加种群的多样性。 6. 更新种群:用新的个体替换旧的个体,产生下一代种群。 7. 终止条件:达到预设的迭代次数或者找到最优解时终止算法。 下面是一个Python实现的遗传算法求解TSP问题的例子: ```python import random # 城市坐标 city_pos = [(60, 200), (180, 200), (80, 180), (140, 180), (20, 160), (100, 160), (200, 160), (140, 140), (40, 120), (100, 120), (180, 100), (60, 80), (120, 80), (180, 60), (20, 40), (100, 40), (200, 40), (20, 20), (60, 20), (160, 20)] # 计算两个城市之间的距离 def distance(city1, city2): return ((city1[0] - city2[0]) ** 2 + (city1[1] - city2[1]) ** 2) ** 0.5 # 计算路径长度 def path_length(path): length = 0 for i in range(len(path) - 1): length += distance(city_pos[path[i]], city_pos[path[i+1]]) length += distance(city_pos[path[-1]], city_pos[path[0]]) return length # 初始化种群 def init_population(pop_size, city_num): population = [] for i in range(pop_size): path = list(range(city_num)) random.shuffle(path) population.append(path) return population # 选择操作 def selection(population, fitness): fitness_sum = sum(fitness) probability = [f/fitness_sum for f in fitness] cum_probability = [sum(probability[:i+1]) for i in range(len(probability))] new_population = [] for i in range(len(population)): r = random.random() for j in range(len(cum_probability)): if r < cum_probability[j]: new_population.append(population[j]) break return new_population # 交叉操作 def crossover(parent1, parent2): child1, child2 = parent1.copy(), parent2.copy() start, end = sorted([random.randint(0, len(parent1)-1) for _ in range(2)]) for i in range(start, end+1): child1[i], child2[i] = child2[i], child1[i] return child1, child2 # 变异操作 def mutation(path): i, j = sorted([random.randint(0, len(path)-1) for _ in range(2)]) path[i:j+1] = reversed(path[i:j+1]) return path # 遗传算法求解TSP问题 def tsp_ga(city_pos, pop_size=100, max_iter=1000): city_num = len(city_pos) population = init_population(pop_size, city_num) best_path, best_length = None, float('inf') for i in range(max_iter): fitness = [1/path_length(path) for path in population] best_index = fitness.index(max(fitness)) if path_length(population[best_index]) < best_length: best_path = population[best_index] best_length = path_length(best_path) new_population = [population[best_index]] while len(new_population) < pop_size: parent1, parent2 = random.choices(population, weights=fitness, k=2) child1, child2 = crossover(parent1, parent2) child1 = mutation(child1) if random.random() < 0.1 else child1 child2 = mutation(child2) if random.random() < 0.1 else child2 new_population.extend([child1, child2]) population = selection(new_population, fitness) return best_path, best_length # 测试 best_path, best_length = tsp_ga(city_pos) print('最短路径:', best_path) print('路径长度:', best_length) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

比奇堡咻飞兜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值