python写遗传算法
时间: 2023-09-22 19:05:04 浏览: 78
python-algoritmo-genetico:用Python编写的遗传算法实现。 旨在查找智能交通信号灯的最佳时间,并最大化通过随机和不平衡交通流的两条街道的交通流量
以下是一个Python遗传算法的示例,用于解决最大化函数f(x) = x*sin(10*pi*x)+2.0(其中0<=x<=1)。该算法具有以下参数:
- popSize:种群数量
- eliteSize:精英数量
- mutationRate:突变率
- generations:遗传算法的迭代次数
代码如下:
```
import random
import math
def fitness(x):
return x * math.sin(10 * math.pi * x) + 2.0
def generateIndividual():
return random.random()
def generatePopulation(popSize):
return [generateIndividual() for i in range(popSize)]
def rankPopulation(population):
fitnessResults = {}
for i in range(len(population)):
fitnessResults[i] = fitness(population[i])
return sorted(fitnessResults.items(), key = lambda x : x[1], reverse = True)
def selectParents(populationRanked, eliteSize):
parents = []
for i in range(eliteSize):
parents.append(populationRanked[i][0])
for i in range(len(populationRanked) - eliteSize):
if random.random() < 0.5:
parents.append(populationRanked[i][0])
return parents
def breed(parent1, parent2):
child = []
geneA = int(random.random() * len(parent1))
geneB = int(random.random() * len(parent1))
startGene = min(geneA, geneB)
endGene = max(geneA, geneB)
for i in range(startGene, endGene):
child.append(parent1[i])
for i in range(len(parent2)):
if parent2[i] not in child:
child.append(parent2[i])
return child
def breedPopulation(parents, eliteSize):
children = []
length = len(parents) - eliteSize
pool = random.sample(parents, len(parents))
for i in range(eliteSize):
children.append(parents[i])
for i in range(length):
child = breed(pool[i], pool[len(parents) - i - 1])
children.append(child)
return children
def mutate(individual, mutationRate):
if random.random() < mutationRate:
index = int(random.random() * len(individual))
individual[index] = random.random()
return individual
def mutatePopulation(population, mutationRate):
mutatedPopulation = []
for individual in population:
mutatedIndividual = mutate(individual, mutationRate)
mutatedPopulation.append(mutatedIndividual)
return mutatedPopulation
def nextGeneration(currentGen, eliteSize, mutationRate):
populationRanked = rankPopulation(currentGen)
parents = selectParents(populationRanked, eliteSize)
children = breedPopulation(parents, eliteSize)
nextGeneration = mutatePopulation(children, mutationRate)
return nextGeneration
def geneticAlgorithm(popSize, eliteSize, mutationRate, generations):
population = generatePopulation(popSize)
for i in range(generations):
population = nextGeneration(population, eliteSize, mutationRate)
populationRanked = rankPopulation(population)
return populationRanked[0][0]
print(geneticAlgorithm(popSize = 100, eliteSize = 20, mutationRate = 0.01, generations = 100))
```
这个示例代码使用了Python的随机数生成器和数学库,以便随机生成个体和进行适应度计算。在主函数中,我们使用100个种群,精英数量为20,突变率为0.01,进行100代的遗传算法迭代。输出的结果是一个最优解,即f(x)的最大值对应的x值。
阅读全文