GAFT(Genetic Algorithm Framework in Python)是一个基于python的遗传算法框架,它提供了一系列的遗传运算子(operator)和一些插件接口(plugin interfaces),方便用户自定义。同时还提供了运行时分析(on-the-fly analysis)。GAFT还集成了MPI并行化接口,可以加速算法的运算。
Installation
Python环境:Python 3.x
1
pip install gaft
如果希望支持并行化,需要安装MPI。
1
pip install mpi4py
Quick Start
1.引入GAFT模块
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# components and operators from gaft import GAEngine from gaft.components import BinaryIndividual from gaft.components import Population from gaft.operators import RouletteWheelSelection from gaft.operators import UniformCrossover from gaft.operators import FlipBitMutation
# Analysis Plugin from gaft.plugin_interfaces.analysis import OnTheFlyAnalysis
from gaft.analysis.fitness_store import FitnessStore
definit(self, indvs=None): ''' Initialize current population with individuals. :param indvs: Initial individuals in population, randomly initialized individuals are created if not provided. :type indvs: list of Individual object ''' IndvType = self.indv_template.__class__
if indvs isNone: for _ inrange(self.size): indv = IndvType(ranges=self.indv_template.ranges, eps=self.indv_template.eps, size=self.indv_template.size) self.individuals.append(indv) else: # Check individuals. iflen(indvs) != self.size: raise ValueError('Invalid individuals number') for indv in indvs: ifnotisinstance(indv, IndividualBase): raise ValueError('individual class must be subclass of IndividualBase') self.individuals = indvs
from random import random from bisect import bisect_right from itertools import accumulate
from ...plugin_interfaces.operators.selection import Selection
classRouletteWheelSelection(Selection): ''' Selection operator with fitness proportionate selection(FPS) or so-called roulette-wheel selection implementation. ''' def__init__(self): pass
defselect(self, population, fitness): ''' Select a pair of parent using FPS algorithm. :param population: Population where the selection operation occurs. :type population: :obj:`gaft.components.Population` :return: Selected parents (a father and a mother) :rtype: list of :obj:`gaft.components.IndividualBase` ''' # Normalize fitness values for all individuals. fit = population.all_fits(fitness) min_fit = min(fit) fit = [(i - min_fit) for i in fit]
# Create roulette wheel. ## HERE! sum_fit = sum(fit) if sum_fit != 0.0: wheel = list(accumulate([i/sum_fit for i in fit])) else: wheel = [0.0for i in fit] wheel[len(wheel) - 1] = 1.0
# Select a father and a mother. father_idx = bisect_right(wheel, random()) father = population[father_idx] mother_idx = (father_idx + 1) % len(wheel) mother = population[mother_idx]