Python遗传算法搜索最优最短路径

发布于:2024-03-07 ⋅ 阅读:(71) ⋅ 点赞:(0)

程序示例精选
Python遗传算法搜索最优最短路径
如需安装运行环境或远程调试,见文章底部个人QQ名片,由专业技术人员远程协助!

前言

这篇博客针对《Python遗传算法搜索最优最短路径》编写代码,代码整洁,规则,易读。 学习与应用推荐首选。


运行结果


文章目录

一、所需工具软件
二、使用步骤
       1. 主要代码
       2. 运行结果
三、在线协助

一、所需工具软件

       1. VS2019, Qt
       2. C++

二、使用步骤

代码如下(示例):

#!/usr/bin/env python 
# -*- coding:utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np

N_CITIES = 20  # DNA长度
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.pop = np.vstack([np.random.permutation(DNA_size) for _ in range(pop_size)])

    def translateDNA(self, DNA, city_position):     # get cities' coord in order
        """
        这个方法的目的是将城市坐标按照 DNA 中的顺序排列,并将 x 坐标和 y 坐标分别存储在 line_x 和 line_y 中。
        :param DNA:  这里的DNA是pop_size个 不是一个
        :param city_position:
        :return:
        """
        line_y = np.empty_like(DNA, dtype=np.float64)    # 存放y轴的点
        for i, d in enumerate(DNA):     #根据DNA中的每个城市顺序获取坐标
            city_coord = city_position[d]   #根据d重新排列city_position的顺序得到city_coord
            line_x[i, :] = city_coord[:, 0]  # 将city_coord数组的第一列的值赋给line_x数组的第 i 行
            line_y[i, :] = city_coord[:, 1]

        return line_x, line_y

    def get_fitness(self, line_x, line_y):
        """
        获取适应度
        :param line_x:
        :param line_y:
        :return:
        """
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):
        """

        :param fitness:
        :return:  返回一个心中群
        """
        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):
        """
        交叉
        :param parent:
        :param pop:
        :return:

            # swap_city 通过布尔数组从 pop[i_] 中选取了不在 keep_city 中的城市编码。
            swap_city = pop[i_, np.isin(pop[i_].ravel(), keep_city, invert=True)]
            # 将 keep_city 和 swap_city 进行拼接,得到了新的子代个体的 DNA 序列,
            parent[:] = np.concatenate((keep_city, swap_city))
        return parent

    def mutate(self, child):
        """
        变异
        这里的变异是将DNA序列的两个点给交换一下
        :param child:
        :return:
        """
self.DNA_size)
                swapA, swapB = child[point], child[swap_point]
                child[point], child[swap_point] = swapB, swapA
        return child

    def evolve(self, fitness):
        """
        开始进化算法
        :param fitness:
        :return:
        """
        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.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(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)
        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()



运行结果


在这里插入图片描述

三、在线协助:

如需安装运行环境或远程调试,见文章底部个人 QQ 名片,由专业技术人员远程协助!

1)远程安装运行环境,代码调试
2)Visual Studio, Qt, C++, Python编程语言入门指导
3)界面美化
4)软件制作
5)云服务器申请
6)网站制作

当前文章连接:https://blog.csdn.net/alicema1111/article/details/132666851
个人博客主页https://blog.csdn.net/alicema1111?type=blog
博主所有文章点这里:https://blog.csdn.net/alicema1111?type=blog

博主推荐:
Python人脸识别考勤打卡系统:
https://blog.csdn.net/alicema1111/article/details/133434445
Python果树水果识别https://blog.csdn.net/alicema1111/article/details/130862842
Python+Yolov8+Deepsort入口人流量统计:https://blog.csdn.net/alicema1111/article/details/130454430
Python+Qt人脸识别门禁管理系统:https://blog.csdn.net/alicema1111/article/details/130353433
Python+Qt指纹录入识别考勤系统:https://blog.csdn.net/alicema1111/article/details/129338432
Python Yolov5火焰烟雾识别源码分享:https://blog.csdn.net/alicema1111/article/details/128420453
Python+Yolov8路面桥梁墙体裂缝识别:https://blog.csdn.net/alicema1111/article/details/133434445


网站公告

今日签到

点亮在社区的每一天
去签到