【启发式算法】Python实现遗传算法求解TSP问题

遗传算法

算法相关参数

  • 种群个体数量:p_num
  • 进化代数:gen
  • 变异率:pm
  • 被选中的概率:mask_list[i]/sum_len(即当前距离差值/距离差值之和)

算法效果分析

  1. 种群数量越多,迭代次数越多,搜索次数越多,程序运行越慢,相对来 得到的解更可信
  2. 种群中个体的路径长度越短,被选中作为父代的概率越大,即优胜劣汰
  3. 算法随机性体现在:父代的随机选取,孩子继承父母的基因序列长度随机(即单点交叉策略),一定概率进行变异,变异中随机选取基因进行交换

算法步骤

  1. 数据初始化:计算距离矩阵(dist[i][j]表示i城市与j城市之间的距离);随机得到初始解(起点为0城市);编写距离计算函数;初始化第一代的种群
  2. 求得当前代时种群中的最优解,并初始化子代矩阵
  3. 遗传算法的核心:算法迭代gen次,每次产生p_num个子代。
    3.1 随机选择一对父母(路径越短,选中的概率越大),并选取父母各自一段基因序列进行遗传(基因即路径,长度随机生成);
    3.2 第一个孩子继承母亲的部分基因序列
    3.3 随机生成概率,判断是否变异
    3.4 将孩子基因放入孩子序列,孩子的数量+1
    3.5 同理第二个孩子继承父亲的基因(见3.2~3.4)
    3.6 计算过所有p_num个子代后,找出当前代的最优解并与全局最优解比较
  4. 直到迭代gen次,算法结束
# -*- coding: utf-8 -*-
import numpy as np
import random
import math
import matplotlib.pyplot as plt
import time

"""
Desicribe:遗传算法解TSP问题

"""

# 解决中文显示问题
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

# 原始数据
coordinates = np.array([[565.0, 575.0], [25.0, 185.0], [345.0, 750.0], [945.0, 685.0], [845.0, 655.0],
                        [880.0, 660.0], [25.0, 230.0], [525.0, 1000.0], [580.0, 1175.0], [650.0, 1130.0],
                        [1605.0, 620.0], [1220.0, 580.0], [1465.0, 200.0], [1530.0, 5.0], [845.0, 680.0],
                        [725.0, 370.0], [145.0, 665.0], [415.0, 635.0], [510.0, 875.0], [560.0, 365.0],
                        [300.0, 465.0], [520.0, 585.0], [480.0, 415.0], [835.0, 625.0], [975.0, 580.0],
                        [1215.0, 245.0], [1320.0, 315.0], [1250.0, 400.0], [660.0, 180.0], [410.0, 250.0],
                        [420.0, 555.0], [575.0, 665.0], [1150.0, 1160.0], [700.0, 580.0
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
遗传算法是一种启发式优化算法,常用于求解TSP(Traveling Salesman Problem)问题。下面是使用遗传算法求解TSP问题Python代码示例: ```python import random # 定义TSP问题的距离矩阵 distance_matrix = [ [0, 10, 15, 20], [10, 0, 35, 25], [15, 35, 0, 30], [20, 25, 30, 0] ] # 定义遗传算法的参数 population_size = 50 # 种群大小 elite_size = 10 # 精英个体数量 mutation_rate = 0.01 # 变异率 generations = 100 # 迭代次数 # 创建一个个体(路径) def create_individual(): individual = list(range(len(distance_matrix))) random.shuffle(individual) return individual # 创建初始种群 def create_population(): population = [] for _ in range(population_size): population.append(create_individual()) return population # 计算路径的总距离 def calculate_fitness(individual): total_distance = 0 for i in range(len(individual)): from_city = individual[i] to_city = individual[(i + 1) % len(individual)] total_distance += distance_matrix[from_city][to_city] return total_distance # 选择精英个体 def select_elite(population): population_with_fitness = [(individual, calculate_fitness(individual)) for individual in population] population_with_fitness.sort(key=lambda x: x[1]) return [individual for individual, _ in population_with_fitness[:elite_size]] # 交叉互换操作 def crossover(parent1, parent2): child = [None] * len(parent1) start_index = random.randint(0, len(parent1) - 1) end_index = random.randint(start_index + 1, len(parent1)) child[start_index:end_index] = parent1[start_index:end_index] for i in range(len(parent2)): if parent2[i] not in child: for j in range(len(child)): if child[j] is None: child[j] = parent2[i] break return child # 变异操作 def mutate(individual): for i in range(len(individual)): if random.random() < mutation_rate: j = random.randint(0, len(individual) - 1) individual[i], individual[j] = individual[j], individual[i] return individual # 进化过程 def evolve(population): elite = select_elite(population) new_population = elite[:] while len(new_population) < population_size: parent1 = random.choice(elite) parent2 = random.choice(elite) child = crossover(parent1, parent2) child = mutate(child) new_population.append(child) return new_population # 主函数 def tsp_ga(): population = create_population() for _ in range(generations): population = evolve(population) best_individual = min(population, key=calculate_fitness) best_distance = calculate_fitness(best_individual) return best_individual, best_distance # 执行遗传算法求解TSP问题 best_individual, best_distance = tsp_ga() print("Best individual:", best_individual) print("Best distance:", best_distance) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值