遗传算法代码

遗传算法代码全局搜索最优算法 1 遗传算法这里以 github 上的遗传算法开源库为例子 首先我们安装 GA 官方说依赖库好像只支持 Python3 但是我好像 python2 也安装成功了 pip3installp 在这里我们讨论一个简单的全局优化过程 讨论 x 2 2 y 4 2 x 2 2 y 4 2 x 2 2 y 4 2 在 x 1 5 y 6 9 x subset 1 5 y subset 6 9 x 1 5 y 6 9 的最大值 源码如下 importnump

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

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() 
  1. 所有参数有一个范围或取值,如gene_space=[1,5,6],则表示所有参数只能取1,5,6中的一个值。
  2. 每个参数有不同取值,如gene_space=[[1,6],[4,5,8]],则表示第一个参数取值为1或者6,第二个参数取值为4,5或者8。

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214104.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午4:58
下一篇 2026年3月18日 下午4:58


相关推荐

  • 什么是Scrum?

    什么是Scrum?Scrum 是一个用于开发和维持复杂产品的框架 是一个增量的 迭代的开发过程 在这个框架中 整个开发过程由若干个短的迭代周期组成 一个短的迭代周期称为一个 Sprint 每个 Sprint 的建议长度是 2 到 4 周 互联网产品研发可以使用 1 周的 Sprint 在 Scrum 中 使用产品 Backlog 来管理产品的需求 产品 backlog 是一个按照商业价值排序的需求列表 列表条目的体现形式通常为用户故事 Scr

    2026年3月26日
    2
  • Struts2漏洞分析「建议收藏」

    Struts2漏洞分析「建议收藏」当在浏览器输入如下地址时:      http://www.xxxx.com/aaa.action?(‘\u0023_memberAccess[\’allowStaticMethodAccess\’]’)(meh)=true&(aaa)((‘\u0023context[\’xwork.MethodAccessor.denyMethodExecution\’]\u003d\u0023foo’)

    2022年7月19日
    21
  • (三)hadoop系列之__CRT(SecureCRTPortable)的使用

    (三)hadoop系列之__CRT(SecureCRTPortable)的使用  SecureCRTPortable属于终端仿真程序,支持SSH(查看此处http://blog.csdn.net/macrossdzh/article/details/5691924)协议。利用CRT可以很方便操作虚拟机终端。进入正题……1.首先,下载SecureCRTPortable软件。2.直接执行SecureCRTPortable.exe文件即可。3.执…

    2022年5月23日
    36
  • JS获取当前年份月[通俗易懂]

    JS获取当前年份月[通俗易懂]//获取完整的日期 vardate=newDate; varyear=date.getFullYear();  varmonth=date.getMonth()+1; month=(month varmydate=(year.toString()+month.toString());注意,year.toString()+month.toString()不能写成year+mont

    2025年12月8日
    4
  • win7文件和打印共享服务器,手动添加Windows凭据,彻底解决Win7系统打印共享-win7打印机共享设置…

    win7文件和打印共享服务器,手动添加Windows凭据,彻底解决Win7系统打印共享-win7打印机共享设置…问题的提出 一个办公室三 五个人共用一台电脑是常有的事 除了用硬件解决之外 很多人都会选择设置共享打印的方法去实现 但带来的问题是经常掉线 更严重的问题是关机后重新启动 部分电脑需要重新连接或安装共享打印机才能完成打印 有没有彻底解决的措施呢 答案是肯定的 下面做一个简单的分享 希望对你有所帮助 1 将打印机连接到其中一台电脑 A 上 安装打印机驱动程序 能够正常打印即可 2 在电脑 A 上设置打

    2026年3月19日
    1
  • 0基础安装 OpenClaw 图文教程(Windows 系统)

    0基础安装 OpenClaw 图文教程(Windows 系统)

    2026年3月13日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号