def __init__(self, *args, **kwargs): mins = kwargs.pop("constr_min") maxes = kwargs.pop("constr_max") G1DList.__init__(self, *args, **kwargs) allele = GAlleles( [GAlleleRange(b, e, True) for (b, e) in zip(mins, maxes)]) self.setParams(allele=allele) self.initializator.set(G1DListInitializatorAllele) self.mutator.set(G1DListMutatorAllele)
def __init__(self, *args, **kwargs): mins = kwargs.pop("constr_min") maxes = kwargs.pop("constr_max") G1DList.__init__(self, *args, **kwargs) allele = GAlleles([GAlleleRange(b, e, True) for (b, e) in zip(mins, maxes)]) self.setParams(allele=allele) self.initializator.set(G1DListInitializatorAllele) self.mutator.set(G1DListMutatorAllele)
def __init__(self): ''' Constructor ''' G1DList.__init__(self, PacmanConsts.NUMBER_OF_CHROMOSOMES) self.setParams(rangemin=RANGE_MIN,rangemax=RANGE_MAX) self.initializator.set(G1DListInitializatorReal) self.mutator.set(G1DListMutatorRealGaussian) self.crossover.set(G1DListCrossoverUniform)
def __init__(self, initialList=[]): ''' Constructor ''' G1DList.__init__(self, CHROMOSOME_LENGTH) self.setParams(minMean=RANGE_MEAN_MIN, maxMean=RANGE_MEAN_MAX, minSigma=RANGE_SIGMA_MIN, maxSigma=RANGE_SIGMA_MAX, minWallPenalty=RANGE_WALL_PENALTY_MIN, maxWallPenalty=RANGE_WALL_PENALTY_MAX) # self.initializator.set(PacmanGaussianInitializator) self.initializator.set(PacmanFixStartInitializator) self.mutator.set(PacmanGaussianMutator) self.crossover.set(Crossovers.G1DListCrossoverUniform) if initialList: self.genomeList = initialList
def call(settings, input_dict): """ This function ... :param settings: :param input_dict: :return: """ # Inform the user log.info("Calling Pyevolve ...") # Import pyevolve modules from pyevolve.G1DList import G1DList from pyevolve.G2DList import G2DList from pyevolve.G1DBinaryString import G1DBinaryString from pyevolve.G2DBinaryString import G2DBinaryString from pyevolve.GSimpleGA import GSimpleGA, RawScoreCriteria from pyevolve.Initializators import G1DListInitializatorInteger, G1DListInitializatorReal from pyevolve.Mutators import G1DListMutatorIntegerRange, G1DListMutatorIntegerGaussian, G1DListMutatorIntegerBinary, G1DListMutatorRealRange, G1DListMutatorRealGaussian from pyevolve.Consts import minimaxType # Get the settings output = settings["output"] genome_type = settings[ "genome_type"] if "genome_type" in settings else "list" genome_dimension = settings[ "genome_dimension"] if "genome_dimension" in settings else 1 nparameters = settings["nparameters"] if "nparameters" in settings else None nparameters2 = settings[ "nparameters2"] if "nparameters2" in settings else None nindividuals = settings[ "nindividuals"] if "nindividuals" in settings else None parameter_range = settings[ "parameter_range"] if "parameter_range" in settings else None best_raw_score = settings[ "best_raw_score"] if "best_raw_score" in settings else None round_decimal = settings[ "round_decimal"] if "round_decimal" in settings else None ngenerations = settings[ "ngenerations"] if "ngenerations" in settings else None mutation_rate = settings[ "mutation_rate"] if "mutation_rate" in settings else None crossover_rate = settings[ "crossover_rate"] if "crossover_rate" in settings else None stats_freq = settings["stats_freq"] if "stats_freq" in settings else None mutation_method = settings[ "mutation_method"] if "mutation_method" in settings else None min_or_max = settings["min_or_max"] if "min_or_max" in settings else None # No messages stats_freq = 0 # Get the input evaluator = input_dict["evaluator"] # this is required! genome = input_dict["genome"].clone() if "genome" in input_dict else None initializator = input_dict[ "initializator"] if "initializator" in input_dict else None mutator = input_dict["mutator"] if "mutator" in input_dict else None crossover = input_dict["crossover"] if "crossover" in input_dict else None callback = input_dict["callback"] if "callback" in input_dict else None # Get kwargs for the functions evaluator_kwargs = input_dict[ "evaluator_kwargs"] if "evaluator_kwargs" in input_dict else None initializator_kwargs = input_dict[ "initializator_kwargs"] if "initializator_kwargs" in input_dict else None mutator_kwargs = input_dict[ "mutator_kwargs"] if "mutator_kwargs" in input_dict else None crossover_kwargs = input_dict[ "crossover_kwargs"] if "crossover_kwargs" in input_dict else None callback_kwargs = input_dict[ "callback_kwargs"] if "callback_kwargs" in input_dict else None # Create partial functions with kwargs set if evaluator_kwargs is not None: evaluator = partial(evaluator, **evaluator_kwargs) if initializator is not None and initializator_kwargs is not None: initializator = partial(initializator, **initializator_kwargs) if mutator is not None and mutator_kwargs is not None: mutator = partial(mutator, **mutator_kwargs) if crossover is not None and crossover_kwargs is not None: crossover = partial(crossover, **crossover_kwargs) if callback is not None and callback_kwargs is not None: callback = partial(callback, **callback_kwargs) # Create genome instance if genome is None: # List genome if genome_type == "list": # Create 1D genome if genome_dimension == 1: genome = G1DList(nparameters) elif genome_dimension == 2: genome = G2DList(nparameters, nparameters2) else: raise ValueError("Dimensions > 2 are not supported") # Binary string genome elif genome_type == "binary_string": # 1D or 2D if genome_dimension == 1: genome = G1DBinaryString(nparameters) elif genome_dimension == 2: genome = G2DBinaryString(nparameters, nparameters2) else: raise ValueError("Dimensions > 2 are not supported") # Invalid option else: raise ValueError("Genome type must be 'list' or 'binary_string") # Set genome properties if parameter_range is not None: genome.setParams(rangemin=parameter_range.min, rangemax=parameter_range.max) if best_raw_score is not None: genome.setParams(bestrawscore=best_raw_score) if round_decimal is not None: genome.setParams(rounddecimal=round_decimal) # Set initializator if initializator is not None: genome.initializator.set(initializator) else: if isinstance(parameter_range, IntegerRange): genome.initializator.set(G1DListInitializatorInteger) elif isinstance(parameter_range, RealRange): genome.initializator.set(G1DListInitializatorReal) else: raise ValueError("Invalid parameter range") # Set mutation method if mutator is not None: genome.mutator.set(mutator) else: if isinstance(parameter_range, IntegerRange): if mutation_method == "range": genome.mutator.set(G1DListMutatorIntegerRange) elif mutation_method == "gaussian": genome.mutator.set(G1DListMutatorIntegerGaussian) elif mutation_method == "binary": genome.mutator.set(G1DListMutatorIntegerBinary) else: raise ValueError("Mutation method '" + mutation_method + "' not recognized") elif isinstance(parameter_range, RealRange): if mutation_method == "range": genome.mutator.set(G1DListMutatorRealRange) elif mutation_method == "gaussian": genome.mutator.set(G1DListMutatorRealGaussian) else: raise ValueError("Mutation method '" + mutation_method + "' not valid for genome of real values") else: raise ValueError("Invalid parameter range") # Set crossover if crossover is not None: genome.crossover.set(crossover) # The evaluator function (objective function) genome.evaluator.set(evaluator) # Genetic Algorithm Instance ga = GSimpleGA(genome) ga.terminationCriteria.set(RawScoreCriteria) ga.setMinimax(minimaxType[min_or_max]) ga.setGenerations(ngenerations) if crossover_rate is not None: ga.setCrossoverRate(crossover_rate) ga.setPopulationSize(nindividuals) ga.setMutationRate(mutation_rate) # Set the callback function if callback is not None: ga.stepCallback.set(callback) # ----------------------------------------------------------------- # Do the evolution with Bar(label='', width=32, hide=None, empty_char=BAR_EMPTY_CHAR, filled_char=BAR_FILLED_CHAR, expected_size=ga.nGenerations, every=1, add_datetime=True) as bar: # Create partial function for the callback refresh_progress_bar_partial = partial(refresh_progress_bar, **{"bar": bar}) # Set callback function to print generation ga.stepCallback.set(refresh_progress_bar_partial) # Evolve ga.evolve(freq_stats=stats_freq) # ----------------------------------------------------------------- # Get the best individual best = ga.bestIndividual() # Return the best individual return best
def setUp(self): self.mom = G1DList(3) self.mom.genomeList = [1, 2, 3] self.dad = G1DList(3) self.dad.genomeList = [4, 5, 6]
def setUp(self): self.genome = G1DList(3) self.genome.genomeList = [1, 2, 3]
def __init__(self, *args, **kwargs): G1DList.__init__(self, *args, **kwargs) self.initializator.set(custom_initializer) self.mutator.set(custom_mutator) self.crossover.set(custom_crossover)
net.connections[net['bias']][1].params[0] = eVar[3] res = net.activateOnDataset(DS) fitness = 1 for i in range(len(DS['target'])): absError = abs(calcError(res[i], DS['target'][i])) if absError <= 1: fitness += 1 - absError # Removes as many percent as the network is incorrect from the fitness else: fitness -= 1.0 / len( DS) # If the network is too inaccurate it is instead punished return fitness genome = G1DList(4) # We'll change all 4 weights in the network genome.setParams(rangemin=-10, rangemax=10) genome.initializator.set( G1DListInitializatorReal) # Initializes the genes with a Real value genome.mutator.set( G1DListMutatorRealGaussian) # Uses a Real value Gaussian mutator genome.evaluator.set(testNetwork) #genome.crossover.clear() # Remove the crossover function, not possible if our list only has 1 element, but it seems like crossover improves the results a lot if enabled ga = GSimpleGA(genome) ga.setElitism( True ) # Uses Elitism, so a few of the successful inidividuals get carried over ga.selector.set( GRouletteWheel ) # Roulette wheel selector, see http://www.edc.ncl.ac.uk/assets/hilite_graphics/rhjan07g02.png ga.nGenerations = 100 # Number of generations
:return: """ chi_squared = 0.0 for i in range(len(test_data_x)): x = test_data_x[i] y = test_data_y[i] chromosome_y = fit_function(x, chromosome[0], chromosome[1]) chi_squared += (y - chromosome_y) ** 2. chi_squared /= 2.0 return chi_squared # ----------------------------------------------------------------- # Genome instance genome = G1DList(2) genome.setParams(rangemin=0., rangemax=50., bestrawscore=0.00, rounddecimal=2) genome.initializator.set(Initializators.G1DListInitializatorReal) genome.mutator.set(Mutators.G1DListMutatorRealGaussian) # Set the evaluator function genome.evaluator.set(chi_squared_function) # Genetic algorithm instance #seed = 4357 ga = GSimpleGA(genome, seed=config.seed) ga.terminationCriteria.set(RawScoreCriteria) ga.setMinimax(Consts.minimaxType["minimize"]) ga.setGenerations(5) ga.setCrossoverRate(0.5) ga.setPopulationSize(100)
def test_1d_list_real_initializator(self): genome = G1DList(3) Initializators.G1DListInitializatorReal(genome) for gen in genome.genomeList: self.assertTrue(type(gen) == float)