遗传算法(三)—— 旅行商问题TSP

遗传算法 (GA) 算法最主要的就是我们要想明白什么是他的 DNA 和怎么样对个体进行评估 (他们的 Fitness).

Fitness和DNA

这次的编码 DNA 方式又不一样, 我们可以尝试对每一个城市有一个 ID, 那经历的城市顺序就是按 ID 排序咯. 比如说商人要经过3个城市, 我们就有

  • 0-1-2
  • 0-2-1
  • 1-0-2
  • 1-2-0
  • 2-0-1
  • 2-1-0

这6种排列方式. 每一种排列方式我们就能把它当做一种 DNA 序列, 用 numpy 产生这种 DNA 序列的方式很简单.

>>> np.random.permutation(3)
# array([1, 2, 0])

计算 fitness 的时候, 我们只要将 DNA 中这几个城市连成线, 计算一下总路径的长度, 根据长度, 我们定下规则, 越短的总路径越好, 下面的 fitness0 就用来计算 fitness 啦. 因为越短的路径我们更要价大幅度选择, 所以这里我用到了 fitness1 这种方式.

fitness0 = 1/total_distance
fitness1 = np.exp(1/total_distance)

交叉和变异

我们要注意的是在 crossover 和 mutate 的时候有一点点不一样, 因为对于路径点, 我们不能随意变化. 比如 如果按平时的 crossover, 可能会是这样的结果:

p1=[0,1,2,3] (爸爸)

p2=[3,2,1,0] (妈妈)

cp=[m,b,m,b] (交叉点, m: 妈妈, b: 爸爸)

c1=[3,1,1,3] (孩子)

那么这样的 c1 要经过两次城市 3, 两次城市1, 而没有经过 2, 0. 显然不行. 所以我们 crossover 以及 mutation 都要换一种方式进行. 其中一种可行的方式是这样. 同样是上面的例子.

p1=[0,1,2,3] (爸爸)

cp=[_,b,_,b] (选好来自爸爸的点)

c1=[1,3,_,_] (先将爸爸的点填到孩子的前面)

此时除开来自爸爸的 1, 3. 还有0, 2 两个城市, 但是0,2 的顺序就按照妈妈 DNA 的先后顺序排列. 也就是 p2=[3,2,1,0] 的 0, 2 两城市在 p2 中是先有 2, 再有 0. 所以我们就按照这个顺序补去孩子的 DNA.

c1=[1,3,2,0]

按照这样的方式, 我们就能成功避免在 crossover 产生的问题: 访问多次通过城市的问题了. 用 Python 的写法很简单.

if np.random.rand() < self.cross_rate:
    i_ = np.random.randint(0, self.pop_size, size=1)                        # select another individual from pop
    cross_points = np.random.randint(0, 2, self.DNA_size).astype(np.bool)   # choose crossover points
    keep_city = parent[cross_points]                                       # find the city number
    swap_city = pop[i_, np.isin(pop[i_].ravel(), keep_city, invert=True)]   # 找到与爸爸不同的城市
    parent[:] = np.concatenate((keep_city, swap_city))

在 mutate 的时候, 也是找到两个不同的 DNA 点, 然后交换这两个点就好了.

for point in range(self.DNA_size):
    if np.random.rand() < self.mutate_rate:
        swap_point = np.random.randint(0, self.DNA_size)
        swapA, swapB = child[point], child[swap_point]
        child[point], child[swap_point] = swapB, swapA

完整代码:

"""
Visualize Genetic Algorithm to find the shortest path for travel sales problem.
Visit my tutorial website for more: https://morvanzhou.github.io/tutorials/
"""
import matplotlib.pyplot as plt
import numpy as np

N_CITIES = 20  # DNA size
CROSS_RATE = 0.1
MUTATE_RATE = 0.02
POP_SIZE = 500
N_GENERATIONS = 500

class GA(object):
    def __init__(self, DNA_size, cross_rate, mutation_rate, pop_size, ):
        self.DNA_size = DNA_size
        self.cross_rate = cross_rate
        self.mutate_rate = mutation_rate
        self.pop_size = pop_size

        self.pop = np.vstack([np.random.permutation(DNA_size) for _ in range(pop_size)])

    def translateDNA(self, DNA, city_position):     # get cities‘ coord in order
        line_x = np.empty_like(DNA, dtype=np.float64)
        line_y = np.empty_like(DNA, dtype=np.float64)
        for i, d in enumerate(DNA):
            city_coord = city_position[d]
            line_x[i, :] = city_coord[:, 0]
            line_y[i, :] = city_coord[:, 1]
        return line_x, line_y

    def get_fitness(self, line_x, line_y):
        total_distance = np.empty((line_x.shape[0],), dtype=np.float64)
        for i, (xs, ys) in enumerate(zip(line_x, line_y)):
            total_distance[i] = np.sum(np.sqrt(np.square(np.diff(xs)) + np.square(np.diff(ys))))
        fitness = np.exp(self.DNA_size * 2 / total_distance)
        return fitness, total_distance

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

    def crossover(self, parent, pop):
        if np.random.rand() < self.cross_rate:
            i_ = np.random.randint(0, self.pop_size, size=1)                        # select another individual from pop
            cross_points = np.random.randint(0, 2, self.DNA_size).astype(np.bool)   # choose crossover points
            keep_city = parent[~cross_points]                                       # find the city number
            swap_city = pop[i_, np.isin(pop[i_].ravel(), keep_city, invert=True)]
            parent[:] = np.concatenate((keep_city, swap_city))
        return parent

    def mutate(self, child):
        for point in range(self.DNA_size):
            if np.random.rand() < self.mutate_rate:
                swap_point = np.random.randint(0, self.DNA_size)
                swapA, swapB = child[point], child[swap_point]
                child[point], child[swap_point] = swapB, swapA
        return child

    def evolve(self, fitness):
        pop = self.select(fitness)
        pop_copy = pop.copy()
        for parent in pop:  # for every parent
            child = self.crossover(parent, pop_copy)
            child = self.mutate(child)
            parent[:] = child
        self.pop = pop

class TravelSalesPerson(object):
    def __init__(self, n_cities):
        self.city_position = np.random.rand(n_cities, 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)

ga = GA(DNA_size=N_CITIES, cross_rate=CROSS_RATE, mutation_rate=MUTATE_RATE, pop_size=POP_SIZE)

env = TravelSalesPerson(N_CITIES)
for generation in range(N_GENERATIONS):
    lx, ly = ga.translateDNA(ga.pop, env.city_position)
    fitness, total_distance = ga.get_fitness(lx, ly)
    ga.evolve(fitness)
    best_idx = np.argmax(fitness)
    print(‘Gen:‘, generation, ‘| best fit: %.2f‘ % fitness[best_idx],)

    env.plotting(lx[best_idx], ly[best_idx], total_distance[best_idx])

plt.ioff()
plt.show()

参考链接:莫烦PYTHON-旅行商问题(Travel Sales Problem)

原文地址:https://www.cnblogs.com/lfri/p/12240751.html

时间: 2024-08-03 06:53:40

遗传算法(三)—— 旅行商问题TSP的相关文章

[数学建模(三)]遗传算法与旅行商问题

clc,clear sj=load('data3.txt') %加载敌方100 个目标的数据 x=sj(:,1); y=sj(:,2); d1=[70,40]; sj0=[d1;sj;d1]; %增加一个点[70,40]作为首尾 sj=sj0; d=zeros(102); %距离矩阵d % 通过向量化的方法计算距离矩阵 amount = size(sj,1); dist_matrix = zeros(amount, amount); coor_x_tmp1 = sj(:,1) * ones(1,

poj3311 Hie with the Pie 旅行商问题(TSP)

题目链接 http://poj.org/problem?id=3311 Hie with the Pie Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 5094   Accepted: 2716 Description The Pizazz Pizzeria prides itself in delivering pizzas to its customers as fast as possible. Unfortuna

遗传算法解决旅行商问题GA_TSP

心血来潮把GA_TSP问题用C++封装起来搞了一遍,期间真是收益不小. 主要是用STL中的vector和list,结构体赋值中遇到了一些难点,原谅我自己是一棵白菜. 选择方法:用种群前面最优的20%代替后面的20%进行淘汰(当然这个比例可以自己拟定,修改代码中得pm_即可). 变异方法:交换一个路径上随机产生的两个城市. 交叉方法:三交换启发交叉(THGA). genticTsp.h 代码如下: 1 #ifndef GENTIC_TSP_H_ 2 #define GENTIC_TSP_H_ 3

07_旅行商问题(TSP问题,货郎担问题,经典NPC难题)

问题来源:刘汝佳<算法竞赛入门经典--训练指南> P61 问题9: 问题描述:有n(n<=15)个城市,两两之间均有道路直接相连,给出每两个城市i和j之间的道路长度L[i][j],求一条经过每个城市一次且仅一次,最后回到起点的路线,使得经过的道路总长度最短(城市编号为0~n-1). 分析: 1.因为最后走的路线为一个环,可以设城市0为起点城市. 2.将每个城市看作二进制的一个位(1代表有,0代表没有),则数k可以表示一些城市的集合(例如k=13,二进制表示为1101,表示城市0,2,3的

旅行商问题(TSP)之动态规划解法

http://soj.sysu.edu.cn/show_problem.php?pid=1000&cid=1769 sicily Traveling Salesman Problem 有编号1到N的N个城市,问从1号城市出发,遍历完所有的城市并最后停留在N号城市的最短路径长度. Input 第一行整数 T :T组数据 (T<=20) 每个case 读入一个N( 2 <= N <= 20),接着输入N行,第i行有两个整数 xi,yi表示 第i个城市坐标轴上的坐标,两个城市的距离定义

旅行商问题(tsp)之分支定界法

http://soj.sysu.edu.cn/show_problem.php?pid=1001&cid=1816 做了一个晚上的题,真是弱爆了... 其实就是深搜最短路,不过加了一个upper bound用来剪枝,因为数据比较小可以过! 深搜还是要熟悉啊! 1 #include <bits/stdc++.h> 2 3 using namespace std; 4 5 double graph[25][25]; 6 int vis[25]; 7 double a[25]; 8 doub

遗传算法的C语言实现(二)-----以求解TSP问题为例

上一次我们使用遗传算法求解了一个较为复杂的多元非线性函数的极值问题,也基本了解了遗传算法的实现基本步骤.这一次,我再以经典的TSP问题为例,更加深入地说明遗传算法中选择.交叉.变异等核心步骤的实现.而且这一次解决的是离散型问题,上一次解决的是连续型问题,刚好形成对照. 首先介绍一下TSP问题.TSP(traveling salesman problem,旅行商问题)是典型的NP完全问题,即其最坏情况下的时间复杂度随着问题规模的增大按指数方式增长,到目前为止还没有找到一个多项式时间的有效算法.TS

遗传算法的C语言实现(二)

上一次我们使用遗传算法求解了一个较为复杂的多元非线性函数的极值问题,也基本了解了遗传算法的实现基本步骤.这一次,我再以经典的TSP问题为例,更加深入地说明遗传算法中选择.交叉.变异等核心步骤的实现.而且这一次解决的是离散型问题,上一次解决的是连续型问题,刚好形成对照. 首先介绍一下TSP问题.TSP(traveling salesman problem,旅行商问题)是典型的NP完全问题,即其最坏情况下的时间复杂度随着问题规模的增大按指数方式增长,到目前为止还没有找到一个多项式时间的有效算法.TS

优化算法入门系列文章目录(更新中):

1. 模拟退火算法 2. 遗传算法 一. 爬山算法 ( Hill Climbing ) 介绍模拟退火前,先介绍爬山算法.爬山算法是一种简单的贪心搜索算法,该算法每次从当前解的临近解空间中选择一个最优解作为当前解,直到达到一个局部最优解. 爬山算法实现很简单,其主要缺点是会陷入局部最优解,而不一定能搜索到全局最优解.如图1所示:假设C点为当前解,爬山算法搜索到A点这个局部最优解就会停止搜索,因为在A点无论向那个方向小幅度移动都不能得到更优的解. 图1     二. 模拟退火(SA,Simulate