我创建了一个遗传算法,以使用python 3.x中的gaft库(https://github.com/PytLab/gaft)来最小化函数。因此,无论适应度得分如何,我都必须经历先前定义的世代数[engine.run(ng = 100):100次迭代]。
我想要一个if函数,该函数定义所需的适应性值并在该点停止迭代,或者应该继续执行直到达到所需的适应性
'''
Find the global maximum for function: f(x) = x + 10sin(5x) + 7cos(4x)
'''
from math import sin, cos
from gaft import GAEngine
from gaft.components import BinaryIndividual
from gaft.components import Population
from gaft.operators import TournamentSelection
from gaft.operators import UniformCrossover
from gaft.operators import FlipBitMutation
# Analysis plugin base class.
from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis
# Built-in best fitness analysis.
from gaft.analysis.fitness_store import FitnessStore
# Define population.
indv_template = BinaryIndividual(ranges=[(0, 10)], eps=0.001)
population = Population(indv_template=indv_template, size=30).init()
# Create genetic operators.
selection = TournamentSelection()
crossover = UniformCrossover(pc=0.8, pe=0.5)
mutation = FlipBitMutation(pm=0.1)
# Create genetic algorithm engine.
engine = GAEngine(population=population, selection=selection,
crossover=crossover, mutation=mutation,
analysis=[FitnessStore])
# Define fitness function.
@engine.fitness_register
def fitness(indv):
x, = indv.solution
return x + 10*sin(5*x) + 7*cos(4*x)
# Define on-the-fly analysis.
@engine.analysis_register
class ConsoleOutputAnalysis(OnTheFlyAnalysis):
interval = 1
master_only = True
def register_step(self, g, population, engine):
best_indv = population.best_indv(engine.fitness)
msg = 'Generation: {}, best fitness: {:.3f}'.format(g, engine.ori_fmax)
self.logger.info(msg)
def finalize(self, population, engine):
best_indv = population.best_indv(engine.fitness)
x = best_indv.solution
y = engine.ori_fmax
msg = 'Optimal solution: ({}, {})'.format(x, y)
self.logger.info(msg)
if '__main__' == __name__:
# Run the GA engine.
engine.run(ng=100)