遗传算法代码,不调用其他库
时间: 2023-02-20 09:58:18 浏览: 68
好的,以下是遗传算法的简单 Python 代码,不调用任何其他库:
```
import random
def create_individual(length, geneSet, get_fitness):
genes = []
while len(genes) < length:
sampleSize = min(length - len(genes), len(geneSet))
genes.extend(random.sample(geneSet, sampleSize))
fitness = get_fitness(genes)
return Chromosome(genes, fitness)
def mutate(parent, geneSet, get_fitness):
index = random.randrange(0, len(parent.Genes))
childGenes = parent.Genes[:]
newGene, alternate = random.sample(geneSet, 2)
childGenes[index] = alternate if newGene == childGenes[index] else newGene
fitness = get_fitness(childGenes)
return Chromosome(childGenes, fitness)
def crossover(parentGenes, index, offspring_length, geneSet, get_fitness):
genes1 = parentGenes[0][:index] + parentGenes[1][index:]
genes2 = parentGenes[1][:index] + parentGenes[0][index:]
fitness1 = get_fitness(genes1)
fitness2 = get_fitness(genes2)
return Chromosome(genes1, fitness1), Chromosome(genes2, fitness2)
class Chromosome:
def __init__(self, genes, fitness):
self.Genes = genes
self.Fitness = fitness
def get_best(get_fitness, targetLen, optimalFitness, geneSet, display):
random.seed()
bestParent = create_individual(targetLen, geneSet, get_fitness)
display(bestParent)
if bestParent.Fitness >= optimalFitness:
return bestParent
while True:
child = mutate(bestParent, geneSet, get_fitness)
if bestParent.Fitness >= child.Fitness:
continue
display(child)
if child.Fitness >= optimalFitness:
return child
bestParent = child
```
这份代码实现了遗传算法的基本步骤,包括生成初始种群,变异,交叉,选择最优解等。希望这份代码能够帮助您理解遗传算法的工作原理。
阅读全文