通过了解遗传算法的概念,应用和代码实现,来充分理解和学习遗传算法。本文文末包含两个不同的通俗易懂的例子,分别使用java和python实现。

  1. 什么是遗传算法?

    可参考这篇文章:link

  2. 应用:List of genetic algorithm applications
    (1)工程设计
    (2)旅行商问题


(3)机器人

(4)著名的组合优化问题「背包问题」
比如,你准备要去野游 1 个月,但是你只能背一个限重 30 公斤的背包。现在你有不同的必需物品,它们每一个都有自己的「生存点数」(具体在下表中已给出)。因此,你的目标是在有限的背包重量下,最大化你的「生存点数」。The image is from blog

3. (例子1)使用Java实现遗传算法的一个应用。

给定一组5个基因,每个基因可以保持二进制值0和1。

适应度值计算为基因组中存在的1的数量。 如果有五个1,那么它具有最大适应性。 如果没有1,那么它具有最小适应度。

该遗传算法试图最大化适应度以提供由最适合的个体组成的群体,即具有五个1的个体。

注意:在这个例子中,每次迭代,找到适应度最好的两个个体,他们交叉和变异之后,分别生成两个子个体,然后从这两个子个体中选择适应度最强的一个,来替换掉群体中适应度最差的个体。

当生成一个个体,它的所有的基因都为1时,程序结束。


import java.util.Random;/**** @author Vijini*///Main class
public class SimpleDemoGA {Population population = new Population();Individual fittest;Individual secondFittest;int generationCount = 0;public static void main(String[] args) {Random rn = new Random();SimpleDemoGA demo = new SimpleDemoGA();//Initialize populationdemo.population.initializePopulation(10);//Calculate fitness of each individualdemo.population.calculateFitness();System.out.println("Generation: " + demo.generationCount + " Fittest: " + demo.population.fittest);//While population gets an individual with maximum fitnesswhile (demo.population.fittest < 5) {++demo.generationCount;//Do selectiondemo.selection();//Do crossoverdemo.crossover();//Do mutation under a random probabilityif (rn.nextInt()%7 < 5) {demo.mutation();}//Add fittest offspring to populationdemo.addFittestOffspring();//Calculate new fitness valuedemo.population.calculateFitness();System.out.println("Generation: " + demo.generationCount + " Fittest: " + demo.population.fittest);}System.out.println("\nSolution found in generation " + demo.generationCount);System.out.println("Fitness: "+demo.population.getFittest().fitness);System.out.print("Genes: ");for (int i = 0; i < 5; i++) {System.out.print(demo.population.getFittest().genes[i]);}System.out.println("");}//Selectionvoid selection() {//Select the most fittest individualfittest = population.getFittest();//Select the second most fittest individualsecondFittest = population.getSecondFittest();}//Crossovervoid crossover() {Random rn = new Random();//Select a random crossover pointint crossOverPoint = rn.nextInt(population.individuals[0].geneLength);//Swap values among parentsfor (int i = 0; i < crossOverPoint; i++) {int temp = fittest.genes[i];fittest.genes[i] = secondFittest.genes[i];secondFittest.genes[i] = temp;}}//Mutationvoid mutation() {Random rn = new Random();//Select a random mutation pointint mutationPoint = rn.nextInt(population.individuals[0].geneLength);//Flip values at the mutation pointif (fittest.genes[mutationPoint] == 0) {fittest.genes[mutationPoint] = 1;} else {fittest.genes[mutationPoint] = 0;}mutationPoint = rn.nextInt(population.individuals[0].geneLength);if (secondFittest.genes[mutationPoint] == 0) {secondFittest.genes[mutationPoint] = 1;} else {secondFittest.genes[mutationPoint] = 0;}}//Get fittest offspringIndividual getFittestOffspring() {if (fittest.fitness > secondFittest.fitness) {return fittest;}return secondFittest;}//Replace least fittest individual from most fittest offspringvoid addFittestOffspring() {//Update fitness values of offspringfittest.calcFitness();secondFittest.calcFitness();//Get index of least fit individualint leastFittestIndex = population.getLeastFittestIndex();//Replace least fittest individual from most fittest offspringpopulation.individuals[leastFittestIndex] = getFittestOffspring();}}//Individual class
class Individual implements Cloneable{int fitness = 0;int[] genes = new int[5];int geneLength = 5;public Individual() {Random rn = new Random();//Set genes randomly for each individualfor (int i = 0; i < genes.length; i++) {genes[i] = Math.abs(rn.nextInt() % 2);}fitness = 0;}//Calculate fitnesspublic void calcFitness() {fitness = 0;for (int i = 0; i < 5; i++) {if (genes[i] == 1) {++fitness;}}}@Overrideprotected Object clone() throws CloneNotSupportedException {Individual individual = (Individual)super.clone();individual.genes = new int[5];for(int i = 0; i < individual.genes.length; i++){individual.genes[i] = this.genes[i];}return individual;}
}//Population class
class Population {int popSize = 10;Individual[] individuals = new Individual[10];int fittest = 0;//Initialize populationpublic void initializePopulation(int size) {for (int i = 0; i < individuals.length; i++) {individuals[i] = new Individual();}}//Get the fittest individualpublic Individual getFittest() {int maxFit = Integer.MIN_VALUE;int maxFitIndex = 0;for (int i = 0; i < individuals.length; i++) {if (maxFit <= individuals[i].fitness) {maxFit = individuals[i].fitness;maxFitIndex = i;}}fittest = individuals[maxFitIndex].fitness;try {return (Individual) individuals[maxFitIndex].clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return null;}//Get the second most fittest individualpublic Individual getSecondFittest() {int maxFit1 = 0;int maxFit2 = 0;for (int i = 0; i < individuals.length; i++) {if (individuals[i].fitness > individuals[maxFit1].fitness) {maxFit2 = maxFit1;maxFit1 = i;} else if (individuals[i].fitness > individuals[maxFit2].fitness) {maxFit2 = i;}}try {return (Individual) individuals[maxFit2].clone();} catch (CloneNotSupportedException e) {e.printStackTrace();}return null;}//Get index of least fittest individualpublic int getLeastFittestIndex() {int minFitVal = Integer.MAX_VALUE;int minFitIndex = 0;for (int i = 0; i < individuals.length; i++) {if (minFitVal >= individuals[i].fitness) {minFitVal = individuals[i].fitness;minFitIndex = i;}}return minFitIndex;}//Calculate fitness of each individualpublic void calculateFitness() {for (int i = 0; i < individuals.length; i++) {individuals[i].calcFitness();}getFittest();}}
  1. (例子2)使用python实现遗传算法的一个应用

本示例代码可以直接运行。给出一个目标句子,比如“Hello world, I am handsome!”,我们通过遗传算法,让随机初始化的句子群体进化出跟目标句子一样的个体。代码中包含详细的注释,此处不做过多解释!

# Python3 program to create target string, starting from
# random string using Genetic Algorithmimport random# Number of individuals in each generation
POPULATION_SIZE = 100# Valid genes
GENES = '''abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ 1234567890, .-;:_!"#%&/()=?@${[]}'''# Target string to be generated
TARGET = "Hello world, I am handsome!"class Individual(object):'''Class representing individual in population'''def __init__(self, chromosome):self.chromosome = chromosomeself.fitness = self.cal_fitness()@classmethoddef cal_fitness(self):'''Calculate fittness score, it is the number ofcharacters in string which differ from targetstring.'''global TARGETfitness = 0for gs, gt in zip(self.chromosome, TARGET):if gs != gt: fitness += 1return fitness@classmethoddef mutated_genes(self):'''create random genes for mutation'''global GENESgene = random.choice(GENES)return gene@classmethoddef create_gnome(self):'''create chromosome or string of genes'''global TARGETgnome_len = len(TARGET)return [self.mutated_genes() for _ in range(gnome_len)]def mate(self, par2):'''Perform mating and produce new offspring'''# chromosome for offspringchild_chromosome = []for gp1, gp2 in zip(self.chromosome, par2.chromosome):# random probabilityprob = random.random()# if prob is less than 0.45, insert gene# from parent 1if prob < 0.45:child_chromosome.append(gp1)# if prob is between 0.45 and 0.90, insert# gene from parent 2elif prob < 0.90:child_chromosome.append(gp2)# otherwise insert random gene(mutate),# for maintaining diversityelse:child_chromosome.append(self.mutated_genes())# create new Individual(offspring) using# generated chromosome for offspringreturn Individual(child_chromosome)# Driver codedef main():global POPULATION_SIZE# current generationgeneration = 1found = Falsepopulation = []# create initial populationfor _ in range(POPULATION_SIZE):gnome = Individual.create_gnome()population.append(Individual(gnome))while not found:# sort the population in increasing order of fitness scorepopulation = sorted(population, key=lambda x: x.fitness)# if the individual having lowest fitness score ie.# 0 then we know that we have reached to the target# and break the loopif population[0].fitness <= 0:found = Truebreak# Otherwise generate new offsprings for new generationnew_generation = []# Perform Elitism, that mean 10% of fittest population# goes to the next generations = int((10 * POPULATION_SIZE) / 100)new_generation.extend(population[:s])# From 50% of fittest population, Individuals# will mate to produce offsprings = int((90 * POPULATION_SIZE) / 100)for _ in range(s):parent1 = random.choice(population[:50])parent2 = random.choice(population[:50])child = parent1.mate(parent2)new_generation.append(child)population = new_generationprint("Generation: {}\tString: {}\tFitness: {}". \format(generation,"".join(population[0].chromosome),population[0].fitness))generation += 1print("Generation: {}\tString: {}\tFitness: {}". \format(generation,"".join(population[0].chromosome),population[0].fitness))if __name__ == '__main__':main()
  1. Reference

https://www.cnblogs.com/jingsupo/archive/2018/04/23/genetic-algorithm-python.html
https://www.analyticsvidhya.com/blog/2017/07/introduction-to-genetic-algorithm/
https://towardsdatascience.com/introduction-to-genetic-algorithms-including-example-code-e396e98d8bf3

Genetic Algorithm遗传算法,两个代码实现例子相关推荐

  1. 遗传算法matlab_智能算法之Genetic Algorithm遗传算法

    智能算法之Genetic Algorithm遗传算法 前言:本文主要围绕 Matlab 的实现展开,Java版本以及Python版本参考文章最后的源码地址,MatLab和python实现大致相同,Ja ...

  2. Genetic Algorithm遗传算法整理

    文章目录 一.简介 二.算法流程 三.参数 四.代码 五.参考资料 一.简介 遗传算法(Genetic Algorithm, GA)是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型 ...

  3. 【AI】Genetic Algorithm 遗传算法

    GA遗传算法 遗传算法概述 基因互换 基因突变 基因突变机率 遗传算法宏观步骤 适应度 fitness 遗传算法简单案例 复杂遗传算法python求解 遗传算法是一种基于自然选择的搜索算法,可用于解决 ...

  4. [ML] Genetic Algorithm 理论概述

    Genetic Algorithm 遗传算法: 遗传算法受到达尔文自然选择理论的启发,以遗传/变异/择优的策略进行机器学习进程. 核心算法逻辑: # Copyright:CMPUT 296, Univ ...

  5. 遗传算法 python包_遗传算法 (Genetic Algorithm)

    遗传算法( Genetic Algorithm )又叫基因进化算法,或进化算法.属于启发式搜索算法一种,这个算法比较有趣,并且弄明白后很简单,写个 100-200 行代码就可以实现.在某些场合下简单有 ...

  6. 算法高级(4)-遗传算法(Genetic Algorithm)简介

    01 什么是遗传算法? 1.1 遗传算法的科学定义 遗传算法(Genetic Algorithm, GA)是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型,是一种通过模拟自然进化过 ...

  7. 遗传算法(Genetic Algorithm)

    遗传算法(Genetic Algorithm)又叫基因进化算法,或进化算法.属于启发式搜索算法一种,这个算法比较有趣,并且弄明白后很简单,写个100-200行代码就可以实现.在某些场合下简单有效.本文 ...

  8. GA遗传算法(Genetic Algorithm)

    遗传算法(Genetic Algorithm)又叫基因进化算法,或进化算法.属于启发式搜索算法一种,这个算法比较有趣,并且弄明白后很简单,写个100-200行代码就可以实现.在某些场合下简单有效.本文 ...

  9. 超详细的遗传算法(Genetic Algorithm)解析【转】

    00 目录 遗传算法定义 生物学术语 问题导入 大体实现 具体细节 代码实现 01 什么是遗传算法? 1.1 遗传算法的科学定义 遗传算法(Genetic Algorithm, GA)是模拟达尔文生物 ...

最新文章

  1. 深入理解PHP内存管理之谁动了我的内存
  2. form表单会跨域_前端跨域So Easy
  3. MySQL主从复制Windows实现
  4. Apache网站服务
  5. 企业实战01_Linux下安装ActiveMQ并设置开机启动
  6. 非常详细Redis数据库入门教程
  7. android设置wifiip地址,android Wifi 设置静态ip地址的方法
  8. 二维haar小波matlab_MATLAB实验之二维小波变换[附效果图]
  9. jQuery(3)——如何绑定事件
  10. 傅里叶变换和拉普拉斯变换
  11. MATLAB去除人声
  12. win10记得pin码 重置密码登录
  13. Orcad Capture CIS出BOM表
  14. 亚马逊云科技 Build On -轻松搭建咖啡点单系统
  15. 光伏电站清扫机器人_光伏电站清扫机器人_雷曼科林
  16. tp路由器桥接成功无法上网怎么办
  17. 菜鸟学习 - Unity中的热更新 - Lua和C#通信
  18. js 生成26个英文字母
  19. 自定义控件--优酷menu
  20. 中国计算机学会高级会员资格,高级会员

热门文章

  1. 关闭linux服务器电源,linux关闭ACPI电源管理模块
  2. war包解压不了_牛骨高汤的熬制方法,拿走不谢!有了这配方,还愁开不了小吃店?...
  3. java web 打印控件_web打印,web打印控件,dotnet web打印控件,java web打印控件,webprint...
  4. mysql 单实例部署_MySQL 5.5单实例 编译安装
  5. SpringBoot2.0配置redis相关
  6. Fragment的详细使用
  7. kafka存储机制与读写流程
  8. 8款帅酷的HTML5/CSS3 3D动画、图片、菜单应用
  9. ansible调用callbacks插件 保存执行结果
  10. 【LeetCode】3Sum Closest 解题报告