遗传算法代码

2023-05-16

全局搜索最优算法(1)——遗传算法

这里以github上的遗传算法开源库为例子:
首先我们安装GA(官方说依赖库好像只支持Python 3,但是我好像python2也安装成功了。。。)

pip3 install pygad

在这里我们讨论一个简单的全局优化过程,讨论 ( x − 2 ) 2 + ( y − 4 ) 2 (x-2)^2+(y-4)^2 (x2)2+(y4)2 x ⊂ ( 1 , 5 ) , y ⊂ ( 6 , 9 ) x\subset(1,5),y\subset(6,9) x(1,5),y(6,9)的最大值。
源码如下:

import numpy as np
import pygad

#the most important part in GA
def fitness_func(solution, solution_idx):
    # solution[i] represeent the value of the (i+1)th parameter in solution
    fitness =pow((solution[0]-2),2)+pow((solution[1]-4),2)
    return fitness

num_generations = 500 # Number of generations.
num_parents_mating = 5 # Number of solutions to be selected as parents in the mating pool.

# To prepare the initial population, there are 2 ways:
# 1) Prepare it yourself and pass it to the initial_population parameter. This way is useful when the user wants to start the genetic algorithm with a custom initial population.
# 2) Assign valid integer values to the sol_per_pop and num_genes parameters. If the initial_population parameter exists, then the sol_per_pop and num_genes parameters are useless.
sol_per_pop = 10 # Number of solutions in the population.


parent_selection_type = "sss" # Type of parent selection.

crossover_type = "single_point" # Type of the crossover operator.

# Parameters of the mutation operation.
mutation_type = "random" # Type of the mutation operator.

last_fitness = 0
def callback_generation(ga_instance):
    global last_fitness
    print("Generation = {generation}".format(generation=ga_instance.generations_completed))
    print("Fitness    = {fitness}".format(fitness=ga_instance.best_solution()[1]))
    print("Change     = {change}".format(change=ga_instance.best_solution()[1] - last_fitness))
    last_fitness = ga_instance.best_solution()[1]

# Creating an instance of the GA class inside the ga module. Some parameters are initialized within the constructor.
ga_instance = pygad.GA(
                       #Number of generations(iterations).
                       num_generations=50,
                       num_parents_mating=num_parents_mating,
                       fitness_func=fitness_func,
                       sol_per_pop=sol_per_pop,
                       #the Number of parameters(the number of genes)
                       num_genes=2,
                      # It is used to specify the possible values for each gene 
                      # in case the user wants to restrict the gene values. 
                      # It is useful if the gene space is restricted to 
                      # a certain range or to discrete values. 
                      # It accepts a list, tuple, or range. 
                      # When all genes have the same global space, 
                     # specify their values as a list/tuple/range. 
                     # For example, gene_space = [0.3, 5.2, -4, 8] 
                      # restricts the gene values to the 4 specified values. 
                     # If each gene has its own space, then the gene_space
                     # parameter can be nested like [[0.4, -5], [0.5, -3.2, 8.2, -9], ...] 
                     #  where the first sublist determines the values for 
                     # the first gene,the second sublist for the second gene, and so on.
                       gene_space=[np.arange(1, 5.01,0.01).tolist(),np.arange(6, 9.01,0.01).tolist()],
                       parent_selection_type=parent_selection_type,
                       # Number of parents to keep in the next population.
                       # -1 means keep all parents
                      # and 0 means keep nothing.
                       keep_parents=1,
                       crossover_type=crossover_type,
                       mutation_type=mutation_type,
                       # Percentage of genes to mutate. This parameter has no action
                       # if the parameter mutation_num_genes exists.
                       mutation_percent_genes=50,
                       callback_generation=callback_generation)

# Running the GA to optimize the parameters of the function.
ga_instance.run()

# After the generations complete, some plots are showed that summarize the how the outputs/fitenss values evolve over generations.
ga_instance.plot_result()

# Returning the details of the best solution.
solution, solution_fitness, solution_idx = ga_instance.best_solution()
print("Parameters of the best solution : {solution}".format(solution=solution))
print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))
#print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))

if ga_instance.best_solution_generation != -1:
    print("Best fitness value reached after {best_solution_generation} generations.".format(best_solution_generation=ga_instance.best_solution_generation))

# Saving the GA instance.
filename = 'genetic' # The filename to which the instance is saved. The name is without extension.
ga_instance.save(filename=filename)
# Loading the saved GA instance.
loaded_ga_instance = pygad.load(filename=filename)
loaded_ga_instance.plot_result()

结果如下所示:
Parameters of the best solution : [5. 9.]
Fitness value of the best solution = 33.99999999999938
Best fitness value reached after 26 generations.

迭代的图片如下:
GA迭代次数图尤其注意的是,gene_space这个参数,这一段话我给翻译一下,原文链接在这,它用于指定每个基因(参数)的可能值,用户可以自定义基因(参数)的取值或者取值范围。可以取离散值或者连续值。它接受列表(list)、元组(Tuple)或范围(Range)。
但是python的range其实也是离散值,我就很迷惑了。但是numpy可以实现这个功能,最终还是要转为list。
有两种情况

  1. 所有参数有一个范围或取值,如gene_space=[1,5,6],则表示所有参数只能取1,5,6中的一个值。
  2. 每个参数有不同取值,如gene_space=[[1,6],[4,5,8]],则表示第一个参数取值为1或者6,第二个参数取值为4,5或者8。

需要注意的是适应度函数应该返回的最优解对应的值,通过淘汰适应度低的物种,物竞天择,适者生存,最终返回全局最优解,这就是GA的整体流程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

遗传算法代码 的相关文章

  • Debian 11 KDE Plasma桌面环境,编译Fcitx5(只编译,不安装)

    Debian 11 KDE Plasma桌面环境 xff0c 编译Fcitx5 xff08 只编译 xff0c 不安装 xff09 安装依赖的工具和库 安装前需要检查电脑上是不是具备这些工具 xff0c 或者库 xff08 这是我根据实际情
  • 快速解决 vsftpd nologin 虚拟用户 拒绝访问 无法登录

    搭建好了vsftpd服务之后 xff0c 新建了一个nologin虚拟用户 xff0c 然而在另一台win7上用WinSCP连接ftp时提示错误 useradd d home ftp s sbin nologin ftpUser1 pass
  • 云计算的部署

    一 云计算的服务和交付模式 基础设施即服务 xff08 Iaas xff09 平台即服务 xff08 Paas xff09 软件即服务 xff08 Saas xff09 衍生出 xff1a 存储即服务 数据库即服务 安全即服务 通信即服务
  • MapReduce的数据流程、执行流程

    MapReduce的大体流程是这样的 xff0c 如图所示 xff1a 由图片可以看到mapreduce执行下来主要包含这样几个步骤 1 首先对输入数据源进行切片 2 master调度worker执行map任务 3 worker读取输入源片
  • 免费下载中国知网、万方学术论文的几种方法(福利合集)

    在国内 xff0c 中国知网收录了最多的期刊论文和硕博士论文 无论学霸学渣 xff0c 都得上去下载论文 如果你的学校在知网购买了相应的下载版权 xff0c 那恭喜你 xff0c 你通过校园网就能免费下载了 但一旦你回了家 xff0c 或学
  • 使用apt离线安装deb包

    文章目录 apt 下载的deb路径阻止apt自动删除缓存文件的方法只下载不安装的方法离线安装deb包离线安装gcc1 下载依赖2 打包下载的deb文件 xff0c 上传到没有外网连接的服务器3 安装deb包 apt 下载的deb路径 默认存
  • haar分类

    今天说一说haar分类算法 首先介绍haar like特征 haar like的特征有边缘特征 线性特征 中心特征和对角线特征 我们使用特征模板来表示特征的计算 xff0c 如图所示 xff1a 这些特征分别对应着不同的矩阵以便于进行计算
  • POI window excel 打开提示部分内容有问题, 是否尝试尽量恢复

    问题如下 window excel 打开报错如下 但是WPS打开正常 问题在于 window excel 冻结窗口只能设置一行 WPS可以设置多行 设置冻结窗口如下 冻结第一行 sheet createFreezePane 0 1 0 1
  • 解决从数据库中取出json数据有转义符

    不处理从数据库取出数据如下 String s1 61 34 34 MsgId 34 1 34 TotalCount 34 10 34 FilterCount 34 8 34 SentCount 34 7 34 ErrorCount 34 0
  • 查询数据报错 com.mysql.cj.exceptions.DataConversionException

    com mysql cj exceptions DataConversionException Caused by java sql SQLDataException Cannot determine value type from str
  • 微信调用接口报错:"errcode":45009,"errmsg":"reach max api daily quota limit hints:

    api请求次数达到最大上限 每个帐号每月共10次清零操作机会 xff0c 清零生效一次即用掉一次机会 xff08 10次包括了平台上的清零和调用接口API的清零 xff09 https developers weixin qq com do
  • @FeignClient注解 中属性 contextId使用

    64 FeignClient注解 中属性 contextId 比如我们有个user服务 xff0c 但user服务中有很多个接口 xff0c 我们不想将所有的调用接口都定义在一个类中 xff0c 比如 xff1a Client span c
  • toString和toJSONString的区别

    Map span class token generics function span class token punctuation lt span String span class token punctuation span Int
  • Neutron运营商网络和租户网络详解

    由租户创建并且管理的网络 xff0c Neutron称之为租户网络 但是Openstack不是万能的 xff0c Neutron也不是万能的 还有很多网络不在Neutron管理范围内 xff08 Neutron称之为外部网络 xff09 有
  • mysql in查询太慢, 使用join优化

    mysql中查询 in 参数太多 导致查询很慢 使用join优化 在实例中in查询话费2s 优化后0 4s span class token keyword SELECT span span class token operator spa
  • Springboot 多数据源事务,切换数据源+事务

    项目有多个数据源 根据配置文件配置的连接数来自动生成多数据源配置 并且使用 aop切换数据源 使用的是 AbstractRoutingDataSource 重写 determineCurrentLookupKey 方法 在切换数据源之前 6
  • Redisson自定义序列化方式

    redissonClient span class token punctuation span span class token function getBucket span span class token punctuation s
  • 方法区使用举例

    span class token keyword public span span class token keyword class span span class token class name MethodAreaDemo span
  • mysql动态字段行转列

    动态行转列 table schema id name s 001 是否吃饭了 s 002 你的汽车品牌 table schema value id user id schema id schema value span class toke

随机推荐

  • freertos学习02-队列 stream buffer message buffer

    1 freertos数据传递简介 在freertos中 xff0c 各个模块都是独立的任务 xff0c 那么任务之间怎么进行大量的数据通信呢 xff1f 在V10版本给出了三种方法 队列queue xff0c 发送固定长度的数据串strea
  • stlink故障修复

    前言 一直用的是国产版stlink xff0c 但是最近手头手头上的两个stlink在下载的时候出故障了 xff0c 无法识别 上淘宝一搜发现涨价了 xff0c 记得以前是20左右 xff0c 现在都要40快一个 于是想着能不能进行修复 百
  • ssd.pytorch源码分析(三)— 非极大值抑制NMS

    NMS源码 SSD论文链接 NMS介绍 吴恩达对于NMS xff08 非极大值抑制 xff09 的介绍 xff1a 说白了 xff0c NMS的作用就是去掉目标检测任务重复的检测框 例如 xff0c 一个目标有多个选择框 xff0c 现在要
  • Hexo的常用命令

    Hexo 常见命令 hexo s hexo s 启动服务器 xff0c 用于预览主题 hexo s 是 hexo server 的缩写 xff0c 命令效果一致 xff1b 预览的同时可以修改文章内容或者主题的代码 xff0c 保存后刷新即
  • hexo史上最全搭建教程

    外链图片转存失败 源站可能有防盗链机制 建议将图片保存下来直接上传 img CF2m4SwD 1628816637063 http peu31tfv4 bkt clouddn com 1 jpg 花了几天搭建了个网站 xff0c 先上链接
  • Neutron中的物理网络详解

    Neutron的模型定义 xff0c 关于物理网络 xff08 provider physical network xff09 有三个地方都有所涉及 xff0c 如下表所示 应该说 xff0c 这三处描述仍然不能很好地表达这个物理网络的准确
  • SAR空间自回归模型

    空间自回归模型 Spatial autoregressive models 适用于包含地理区域 观测数据的数据集 观测空间单位 xff0c 可以是国家 州 县 邮政编码或城市街区 或者 xff0c 社交网络的节点 SAR是什么 xff1f
  • conda安装sklearn库失败

    conda install sklearn PackagesNotFoundError The following packages are not available from current channels sklearn conda
  • 找不到GLIBCXX_3.4.29问题

    参考资料 xff1a 1 2022 02 01 Windows下配置深度学习环境 xff08 Ubuntu 43 Anaconda 43 CUDA 43 Pytorch 43 gcc xff09 知乎 2 version 96 GLIBCX
  • [TW 2023] 将三图神经网络与多个隐式反馈相结合,用于社交推荐

    Incorporating A Triple Graph Neural Network with Multiple Implicit Feedback for Social Recommendation ACM Transactions o
  • [INFOCOM 2019] NeuralWalk:使用神经网络的在线社交网络中的信任评估

    NeuralWalk Trust Assessment in Online Social Networks with Neural Networks IEEE Conference Publication IEEE Xplore 摘要 xf
  • [CDC 2018] 理解压缩对抗隐私

    Understanding Compressive Adversarial Privacy IEEE Conference Publication IEEE Xplore 摘要 本文提出了一种新的隐私保护方法 xff0c 称为 压缩对抗隐私
  • 弱实体集

    弱实体 weak entity 1 定义 xff1a 有些实体集的所有属性都不足以形成主码 xff0c 这样的实体集称为弱实体集 与此相对 xff0c 其属性可以形成主码的实体集称为强实体集 通俗的说 xff1a 有些实体集的所有属性都不足
  • 理解“生成高斯随机测量矩阵”段代码;奇异值分解(SVD)的理解

    生成高斯随机测量矩阵 sampleRate 61 0 7 采样率 Phi 61 np random randn 256 256 u s vh 61 np linalg svd Phi Phi 61 u 256 sampleRate 将测量矩
  • 云服务器cvm & 云服务器ecs区别

    1 全称 cvm的英文全拼是 Cloud Virtual Machine xff08 云虚拟机 xff09 ecs的英文全拼是 Elastic Compute Service xff08 弹性计算服务 xff09 2 对比 云服务器cvm是
  • 远程连接腾讯云上的数据库

    一 准备工作 1 云服务器配置为windows server 2012 r2 2 远程连接云主机 下载rdp xff0c 输入win账号密码运行即可 2 在云主机上安装mysql xff08 1 xff09 下载mysql安装包 xff0c
  • 基于ubuntu18.04 VNC开机自启动

    本博客内容实现了RK3399 NanoPi NEO4的VNC的开机自启动 xff0c 以及原版桌面的显示 系统 xff1a FriendlyDesktop 最新版本 xff0d 基于Ubuntu 18 04 64位系统构建 易于开发 xff
  • Latex部分斜体变直体

    Latex斜体变为直体 rm即可 未使用之前的效果 xff08 x n 43 1 61 mathop arg min limits x alpha x D n xff09 为了将所有的小写x变为直体 xff0c 将所有的x替换为 rm x
  • Latex打花体

    Latex提供了三种花体 xff0c 注意使用时候提前导入包 xff0c 否则会报错 usepackage amsthm amsmath amssymb usepackage mathrsfs 使用的时候直接掉包即可 下面演示部分效果 xf
  • 遗传算法代码

    全局搜索最优算法 xff08 1 xff09 遗传算法 这里以github上的遗传算法开源库为例子 xff1a 首先我们安装GA xff08 官方说依赖库好像只支持Python 3 xff0c 但是我好像python2也安装成功了 xff0