def fit(self,data,target): target = [t if t==0 else 1 for t in target] self.x = list(set(target)) config.load(len(data[0])) chromosome.node_gene_type = genome.NodeGene def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 for i, inputs in enumerate(data): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - target[i])**2 chromo.fitness = 1 - math.sqrt(error/len(target)) population.Population.evaluate = eval_fitness pop = population.Population() pop.epoch(self.max_generations, report=True, save_best=False) winner = pop.stats[0][-1] self.network = winner
def main(): global novSearch # myworld = World("Simulator", 1080, 280, 40) # myworld.readWorldConfigFile("testConfig.txt") myworld = World("Simulator", 2000, 400, 40) myworld.readWorldConfigFile("finalWorld.txt") myworld.getValidStand() myworld.getAirspace() # mario = Mario(myworld, "Mario", 0, 5) mario = Mario(myworld, "Mario", 0, 8) # for final world # set up NEAT config.load("marNovelty_config") chromosome.node_gene_type = genome.NodeGene # use the noveltyFitness function to determine fitness scores population.Population.evaluate = noveltyFitness pop = population.Population() # set how many generations you want evolution to run generations = 10 pop.epoch(generations, report=True) # After evolution completes... # Plot the best/average fitness across the evolution visualize.plot_stats(pop.stats) # Create a visualization of speciation that occurred visualize.plot_species(pop.species_log) # save the archive and growth data from novelty search novSearch.saveArchive("mario") novSearch.saveGrowth("mario") # Save the best coverage chormosomes found print "\nFound behaviors with the following coverage scores:" for i in range(len(bestChromos)): print bestChromos[i][1] f = open("bestChromo%d" % (i), "w") pickle.dump(bestChromos[i][0], f) f.close() # Save the most recently added chromosomes in the archive print "\nNovelty scores for 10 most recently added behaviors:" i = 0 for saved in novSearch.archive[-10:]: print saved[1] f = open("novelty%d" % (i), "w") pickle.dump(saved[2], f) f.close() i += 1
def main(argv=None): # Use a command line argument to pass in the chromo file of an evolved net argv = sys.argv[1:] print argv if len(argv) != 1: print "Usage: You muset pass a chromosome file to be evaluated" return else: chromo_file = argv[0] log_file = argv[0] + ".log" # set up NEAT logFP = open(log_file, "w") chromoFP = open(chromo_file, "r") chromo = pickle.load(chromoFP) chromoFP.close() print chromo # Creates a visualization of the network's topology visualize.draw_net(chromo, "_"+chromo_file) config.load("marNovelty_config") chromosome.node_gene_type = genome.NodeGene # set up your simulator # myworld = World("Simulator", 1080, 280, 40) # myworld.readWorldConfigFile("easyConfig.txt") # myworld.readWorldConfigFile("intermediateConfig.txt") # myworld.readWorldConfigFile("testConfig.txt") myworld = World("Simulator", 1080, 280, 40) # for final world myworld.readWorldConfigFile("testConfig.txt") # for final world myworld.getValidStand() myworld.getAirspace() mario = Mario(myworld, "Mario", 0, 5) #for test world # mario = Mario(myworld, "Mario", 0, 8) # for final world myworld.addMario(mario) myworld.makeVisible() mario.setBrain(neatBrain(chromo, logFP)) for i in range(1500): if not mario.alive: break myworld.step() fitness = mario.getFitness() print "Objective fitness:", fitness, "coinScore:", mario.coinScore print "maxCoinScore: ", mario.world.maxCoinScore, "or:", mario.maxCoinScore print "Behavior:", mario.getBehavior() # wait for a mouse click before ending the program myworld.window.getMouse() logFP.write("Fitness %f\n" % fitness) logFP.close()
def main(): config.load('NEATconfig') chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = eval_fitness generations = 200 pop = population.Population() pop.epoch(generations, report=True, save_best=True, checkpoint_interval=None, checkpoint_generation=5) out.close() plot.plot_bee_pops() plot.plot_hive_vitality()
def main(argv=None): # Use a command line argument to pass in the chromo file of an evolved net argv = sys.argv[1:] print argv if len(argv) != 1: print "Usage: You must pass a chromo_file to be evaluated" return else: chromo_file = argv[0] log_file = argv[0] + ".log" # set up NEAT logFP = open(log_file, "w") chromoFP = open(chromo_file, "r") chromo = pickle.load(chromoFP) chromoFP.close() # print chromo # Creates a visualization of the network's topology visualize.draw_net(chromo, "_"+chromo_file) config.load("smallNEAT_config") chromosome.node_gene_type = genome.NodeGene # set up your simulator myworld = World("Simulator", 1080, 280, 40) myworld.readWorldConfigFile("hardSmallWorld.txt") myworld.getValidStand() myworld.getAirspace() mario = Mario(myworld, "Mario", 0, 5) myworld.addMario(mario) myworld.makeVisible() mario.setBrain(neatBrain(chromo, logFP)) for i in range(1500): if not mario.alive: break myworld.step() fitness = mario.getFitness() # print 'COINSCORE: ', mario.coinScore # print 'max: ', mario.maxCoinScore # print "Fitness:", fitness # wait for a mouse click before ending the program myworld.window.getMouse() #logFP.write("Fitness %f\n" % fitness) logFP.close()
def main(): # set up NEAT config.load("mar2_config") chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = coverageFitness #function name pop = population.Population() # set how many generations you want evolution to run generations = 30 pop.epoch(generations, report=True, save_best=True) # Plots the best/average fitness across the evolution visualize.plot_stats(pop.stats) # Creates a visualization of speciation that occurred visualize.plot_species(pop.species_log)
def main(): # set up NEAT config.load("NEAT_config") chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = coverageFitness #function name pop = population.Population() # set how many generations you want evolution to run generations = 30 pop.epoch(generations, report=True, save_best=True) # Plots the best/average fitness across the evolution visualize.plot_stats(pop.stats) # Creates a visualization of speciation that occurred visualize.plot_species(pop.species_log)
def main(): #create config config.load('2048_config') # neuron model type chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(1, save_best=1) winner = pop.stats[0][-1] print winner
def main(): hive = Rectangle(Point(240,240),Point(260,260)) hive.setFill('orange') hive.draw(win) config.load('NEATconfig') chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = eval_fitness generations = 50 pop = population.Population() pop.epoch(generations, report=True, save_best=True, checkpoint_interval=None, checkpoint_generation=5) global win win.getMouse() win.close() out.close() hive_life.close()
import math from neat import config, population, chromosome, genome, iznn, visualize #from psyco.classes import * config.load('xor2_config') # Temporary workaround chromosome.node_gene_type = genome.NodeGene # For spiking networks config.Config.output_nodes = 2 # XOR-2 INPUTS = ((0, 0), (0, 1), (1, 0), (1, 1)) OUTPUTS = (0, 1, 1, 0) # For how long are we going to wait for an answer from the network? MAX_TIME = 100 # in miliseconds of simulation time def eval_fitness(population): for chromosome in population: brain = iznn.create_phenotype(chromosome) error = 0.0 for i, input in enumerate(INPUTS): for j in range(MAX_TIME): output = brain.advance([x * 10 for x in input]) if output != [False, False]: break if output[0] and not output[1]: # Network answered 1 error += (1 - OUTPUTS[i])**2
from player_2048 import * from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn config.load('2048_config') max_generations = 5 # set node gene type chromosome.node_gene_type = genome.NodeGene def eval_fitness(population): #global melhor_score for chromo in population: net = nn.create_ffphenotype(chromo) score = play_with_AI(net) chromo.fitness = score population.Population.evaluate = eval_fitness pop = population.Population() pop.epoch(max_generations, report=True, save_best=False) winner = pop.stats[0][-1] print('Number of evaluations: %d' % winner.id)
import math import random import cPickle as pickle import time import platform import traceback import sys import copy from scraper import Scraper from neat import config, population, chromosome, genome from neat.nn import nn_pure as nn config.load("nba_predict_config") # set node gene type chromosome.node_gene_type = genome.NodeGene # scrape web for training set statistics stats_scraper = Scraper() games = stats_scraper.retrieve_games() teams = stats_scraper.retrieve_teams() MAX_FITNESS = 1000 def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo)
import math import cPickle as pickle # When using NEAT you must import the following from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn # When using NEAT you must create a configuration file to set the # parameters of the evolution config.load('xor_config') chromosome.node_gene_type = genome.NodeGene INPUTS = [[0, 0], [0, 1], [1, 0], [1, 1]] OUTPUTS = [0, 1, 1, 0] def eval_fitness(population): """ Create a fitness function that returns higher values for better solutions. For this task, we first calculate the sum-squared error of a network on the XOR task. Good networks will have low error, so the fitness is 1 - sqrt(avgError). """ for chromo in population: brain = nn.create_ffphenotype(chromo) error = 0.0 for i, inputs in enumerate(INPUTS): brain.flush() output = brain.sactivate(inputs) error += (output[0] - OUTPUTS[i])**2
# Apply action to the simulated cart-pole x, x_dot, theta, theta_dot = cart_pole(action[0], x, x_dot, theta, theta_dot) # Check for failure. If so, return steps # the number of steps indicates the fitness: higher = better fitness += 1 if (abs(x) >= 2.5 or abs(theta) >= twelve_degrees): #if abs(theta) > twelve_degrees: # Igel (p. 5) # the cart/pole has run/inclined out of the limits break chromo.fitness = fitness if __name__ == "__main__": config.load('spole_ctrnn_config') # Temporary workaround chromosome.node_gene_type = genome2.CTNodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(2000, report=1, save_best=0) print 'Number of evaluations: %d' %(pop.stats[0][-1]).id # visualize the best topology #visualize.draw_net(pop.stats[0][-1]) # best chromosome # Plots the evolution of the best/average fitness #visualize.plot_stats(pop.stats)
theta_dot) # Check for failure. If so, return steps # the number of steps indicates the fitness: higher = better fitness += 1 if (abs(x) >= 2.5 or abs(theta) >= twelve_degrees): #if abs(theta) > twelve_degrees: # Igel (p. 5) # the cart/pole has run/inclined out of the limits break chromo.fitness = fitness if __name__ == "__main__": config.load('spole_ctrnn_config') # Temporary workaround chromosome.node_gene_type = genome2.CTNodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(2000, report=1, save_best=0) print 'Number of evaluations: %d' % (pop.stats[0][-1]).id # visualize the best topology #visualize.draw_net(pop.stats[0][-1]) # best chromosome # Plots the evolution of the best/average fitness #visualize.plot_stats(pop.stats)
import math from neat import config, population, genome_feedforward, genome, visualize #from psyco.classes import * config.load('xor3_config') # XOR-3 INPUTS = ((0,0,0), (0,0,1), (0,1,0), (0,1,1), (1,0,0), (1,0,1), (1,1,0), (1,1,1)) OUTPUTS = (0,1,1,0,1,0,0,1) def eval_fitness(population): for chromosome in population: brain = genome_feedforward.create_phenotype(chromosome) error = 0.0 for i, input in enumerate(INPUTS): output = brain.sactivate(input) # serial activation error += (output[0] - OUTPUTS[i])**2 #error += math.fabs(output[0] - OUTPUTS[i]) #chromosome.fitness = (8.0 - error)**2 # (Stanley p. 43) chromosome.fitness = 1 - math.sqrt(error/len(OUTPUTS)) population.Population.evaluate = eval_fitness pop = population.Population() pop.epoch(500, stats=1, save_best=0) # Draft solution for network visualizing visualize.draw_net(pop.stats[0][-1]) # best chromosome # Plots the evolution of the best/average fitness visualize.plot_stats(pop.stats) # Visualizes speciation #visualize.plot_species(pop.species_log)
from neat import nn from random import randint import cPickle as pickle import single_pole chromosome.node_gene_type = genome2.NodeGene # load the winner file = open('winner_chromosome', 'r') c = pickle.load(file) file.close() print 'Loaded chromosome:' print c config.load('spole_config') net = nn.create_phenotype(c) #x = 0.0 #x_dot = 0.0 #theta = 0.0 #theta_dot = 0.0 # initial conditions (as used by Stanley) x = randint(0, 4799)/1000.0 - 2.4 x_dot = randint(0, 1999)/1000.0 - 1.0 theta = randint(0, 399)/1000.0 - 0.2 theta_dot = randint(0, 2999)/1000.0 - 1.5 print "\nInitial conditions:"
import math import random import cPickle as pickle import time import platform import traceback import sys import copy from scraper import Scraper from neat import config, population, chromosome, genome from neat.nn import nn_pure as nn config.load('nba_predict_config') # set node gene type chromosome.node_gene_type = genome.NodeGene # scrape web for training set statistics stats_scraper = Scraper() games = stats_scraper.retrieve_games() teams = stats_scraper.retrieve_teams() MAX_FITNESS = 1000 def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo)
__author__ = 'user' import math import random import cPickle as pickle from neat import config, population, chromosome, genome #visualize from neat.nn import nn_pure as nn import neatGame #from neat.nn import nn_cpp as nn # C++ extension config.load('game_config') # set node gene type chromosome.node_gene_type = genome.NodeGene # XOR-2 NUMAVG = 10 def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) play = neatGame.Game() temp = 0.0 for x in range(NUMAVG): temp += play.main_loop(False, net) temp = temp / NUMAVG chromo.fitness = temp / 10000.0 population.Population.evaluate = eval_fitness
sim.addBox(4.8, 0.2, 5.2, 0.6, "black") sim.addBox(4.8, 9.4, 5.2, 9.8, "white") # add some sensors: sim.robots[0].addDevice(PioneerFrontLightSensors()) sim.robots[0].addDevice(PioneerFrontSonars()) sim.robots[1].addDevice(PioneerFrontLightSensors()) sim.robots[1].addDevice(PioneerFrontSonars()) # create a symbolic robot redEng = Simbot(sim, ["localhost", 60000], 0) blueEng = Simbot(sim, ["localhost", 60001], 0) # set up neat config.load('redEat_config') chromosome.node_gene_type = genome.NodeGene def main(): population.Population.evaluate = eval_fitness pop = population.Population() generations = 23 pop.epoch(generations, report=True, save_best=True, \ checkpoint_interval=None, checkpoint_generation=11) stop = time.time() elapsed = stop - start print "Total time to evolve:", elapsed print "Time per generation:", elapsed / float(generations) visualize.plot_stats(pop.stats)
import cPickle as pickle from neat import config, population, chromosome, genome config.load('redEat_config') chromosome.node_gene_type = genome.NodeGene pop = population.Population() chromo = pop.create_individual() fp = open("red_init_chromo", 'w') pickle.dump(chromo, fp)
from graphics import * from math import * from prey import Prey from predator import Predator from random import * from math import * import cPickle as pickle import sys # When using NEAT you must import the following from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn # When using NEAT you must create a configuration file to set the # parameters of the evolution config.load('config') chromosome.node_gene_type = genome.NodeGene def eval_fitness(population): for chromo in population: chromo.fitness = eval_individual(chromo) print "Fitness:", chromo.fitness def eval_individual(chromo,logFP=None): brain = nn.create_phenotype(chromo) sumTime = 0 sumPeople = 0 sumDist = 0 for trial in range(3):
import cPickle as pickle from cart_pole import CartPole if len(sys.argv) > 1: # load genome try: file = open(sys.argv[1], 'r') except IOError: print "Filename: '"+sys.argv[1]+"' not found!" sys.exit(0) else: c = pickle.load(file) file.close() else: print "Loading default winner chromosome file" try: file = open('winner_chromosome', 'r') except IOError: print "Winner chromosome not found!" sys.exit(0) else: c = pickle.load(file) file.close() # load settings file config.load('cpExp_config') print "Loaded genome:" print c # starts the simulation simulator = CartPole([c], markov=False) simulator.run(testing=True)
from hearthbreaker.agents.basic_agents import * from hearthbreaker.constants import CHARACTER_CLASS from hearthbreaker.game_objects import Game, card_lookup, Deck from hearthbreaker.cards import * from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn import timeit config.load('evolve_agent_config') # set node gene type chromosome.node_gene_type = genome.NodeGene def load_deck(filename): cards = [] character_class = CHARACTER_CLASS.MAGE with open(filename, "r") as deck_file: contents = deck_file.read() items = contents.splitlines() for line in items[0:]: parts = line.split(" ", 1) count = int(parts[0]) for i in range(0, count): card = card_lookup(parts[1]) if card.character_class != CHARACTER_CLASS.ALL: character_class = card.character_class cards.append(card) if len(cards) > 30: pass
spikes += action # Check for failure. If so, return steps # the number of steps indicates the fitness: higher = better fitness += 1 if (abs(x) >= 2.4 or abs(theta) >= twelve_degrees): #if abs(theta) > twelve_degrees: # Igel (p. 5) uses theta criteria only # the cart/pole has run/inclined out of the limits break chromo.fitness = fitness print 'Spikes:', spikes, ', Firing rate:', spikes / MAX_TIME, '(spikes/ms)' if __name__ == "__main__": config.load('spole_config') # Temporary workaround chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(200, report=1, save_best=0) #pop.epoch(500, report=1, save_best=0) print 'Number of evaluations: %d' % (pop.stats[0][-1]).id # visualize the best topology visualize.draw_net(pop.stats[0][-1]) # best chromosome # Plots the evolution of the best/average fitness visualize.plot_stats(pop.stats)
import math import random import cPickle as pickle from neat import config, population, chromosome, genome, visualize from neat.nn import nn_pure as nn #from neat.nn import nn_cpp as nn # C++ extension config.load('xor2_config') # set node gene type chromosome.node_gene_type = genome.NodeGene # XOR-2 INPUTS = [[0, 0], [0, 1], [1, 0], [1, 1]] OUTPUTS = [0, 1, 1, 0] def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 #error_stanley = 0.0 for i, inputs in enumerate(INPUTS): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - OUTPUTS[i])**2 #error_stanley += math.fabs(output[0] - OUTPUTS[i]) #chromo.fitness = (4.0 - error_stanley)**2 # (Stanley p. 43) chromo.fitness = 1 - math.sqrt(error/len(OUTPUTS))
def Evaluate(set): global signalYield, signalSample, backgroundYield, backgroundSample # Reading variable list variables = open('%s/inputvars.txt' % set['directory']).readlines() variables = [variable.rstrip() for variable in variables] # Setting the number of input and output in the neat config file file = open('%s/neat.config' % set['directory']) template = string.Template(file.read()) file.close() file = open('%s/neat.config' % set['directory'], 'w') file.write( template.safe_substitute(input_nodes=len(variables), output_nodes=1)) file.close() # Read neat configuration file config.load('%s/neat.config' % set['directory']) print('Training: Reading signal files') # Signal topovars signals = TopovarReader(variables) # Adding signal files for sample in Common.TrainingSignals: signals.add('%s/%s/%s.root' % (Common.SampleLocation, Common.TrainingSample, Common.filename(set, sample))) # Creating a variable normalizer normalizer = VariableNormalizer(variables) # Saving the population in buffer signalSample = signals.sample(compress=True) # Adding the sample to the normalizer normalizer.add(signalSample) # Compute the total weight signalYield = normalizer.getTotalWeight() print('Training: Reading background files') # Background topovars backgrounds = TopovarReader(variables) # Adding background files for sample in Common.TrainingBackgrounds: backgrounds.add('%s/%s/%s.root' % (Common.SampleLocation, Common.TrainingSample, Common.filename(set, sample))) # Saving the population in buffer backgroundSample = backgrounds.sample(compress=True) # Adding the sample to the normalizer normalizer.add(backgroundSample) # Compute the total weight backgroundYield = normalizer.getTotalWeight() - signalYield # Reporting the normalization normalizer.report() # Normalization of the variables normalizer.normalizeSample(signalSample) normalizer.normalizeSample(backgroundSample) # NEAT training chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = FitnessFunctionWrapper pop = population.Population() pop.epoch(int(set['number_generations']), report=True, save_best=False, checkpoint_interval=None) winner = pop.stats[0][-1] print 'Training: Number of evaluations: %d' % winner.id print 'Training: Best NN fitness: %0.2f' % winner.fitness # Save the best network file = open('%s/winner.dat' % set['directory'], 'w') pickle.dump(winner, file) file.close() # Save the best network file = open('%s/winner-fitness.txt' % set['directory'], 'w') file.write('%f' % winner.fitness) file.close()
import cPickle as pickle from neat import config, population, chromosome, genome config.load('blueEat_config') chromosome.node_gene_type = genome.NodeGene pop = population.Population() chromo = pop.create_individual() fp = open("blue_init_chromo", 'w') pickle.dump(chromo, fp)
import cPickle as pickle from neat import config, population, chromosome, genome, visualize from cart_pole import CartPole def evaluate_population(population): simulation = CartPole(population, markov=False) # comment this line to print the status simulation.print_status = False simulation.run() if __name__ == "__main__": config.load("cpExp_config") # change the number of inputs accordingly to the type # of experiment: markov (6) or non-markov (3) # you can also set the configs in dpole_config as long # as you have two config files for each type of experiment config.Config.input_nodes = 3 # neuron model type chromosome.node_gene_type = genome.NodeGene # chromosome.node_gene_type = genome.CTNodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(500, report=1, save_best=0)
import math #import random #import cPickle as pickle from neat import config, population, chromosome, genome, visualize #from neat.nn import nn_pure as nn from neat.nn import nn_cpp as nn # C++ extension config.load('xor2_config.txt') # set node gene type chromosome.node_gene_type = genome.NodeGene # XOR-2 INPUTS = [[0, 0], [0, 1], [1, 0], [1, 1]] OUTPUTS = [0, 1, 1, 0] def eval_fitness(population): for chromo in population: net = nn.create_ffphenotype(chromo) error = 0.0 #error_stanley = 0.0 for i, inputs in enumerate(INPUTS): net.flush() # not strictly necessary in feedforward nets output = net.sactivate(inputs) # serial activation error += (output[0] - OUTPUTS[i])**2 #error_stanley += math.fabs(output[0] - OUTPUTS[i]) #chromo.fitness = (4.0 - error_stanley)**2 # (Stanley p. 43) chromo.fitness = 1 - math.sqrt(error/len(OUTPUTS))
def Evaluate(set): global signalYield, signalSample, backgroundYield, backgroundSample # Reading variable list variables = open('%s/inputvars.txt' % set['directory']).readlines() variables = [variable.rstrip() for variable in variables] # Setting the number of input and output in the neat config file file = open ('%s/neat.config' % set['directory']) template = string.Template(file.read()) file.close() file = open ('%s/neat.config' % set['directory'], 'w') file.write(template.safe_substitute(input_nodes = len(variables), output_nodes = 1)) file.close() # Read neat configuration file config.load('%s/neat.config' % set['directory']) print('Training: Reading signal files') # Signal topovars signals = TopovarReader(variables) # Adding signal files for sample in Common.TrainingSignals: signals.add('%s/%s/%s.root' % ( Common.SampleLocation, Common.TrainingSample, Common.filename(set, sample) ) ) # Creating a variable normalizer normalizer = VariableNormalizer(variables) # Saving the population in buffer signalSample = signals.sample(compress = True) # Adding the sample to the normalizer normalizer.add(signalSample) # Compute the total weight signalYield = normalizer.getTotalWeight() print ('Training: Reading background files') # Background topovars backgrounds = TopovarReader(variables) # Adding background files for sample in Common.TrainingBackgrounds: backgrounds.add('%s/%s/%s.root' % ( Common.SampleLocation, Common.TrainingSample, Common.filename(set, sample) ) ) # Saving the population in buffer backgroundSample = backgrounds.sample(compress = True) # Adding the sample to the normalizer normalizer.add(backgroundSample) # Compute the total weight backgroundYield = normalizer.getTotalWeight() - signalYield # Reporting the normalization normalizer.report() # Normalization of the variables normalizer.normalizeSample(signalSample) normalizer.normalizeSample(backgroundSample) # NEAT training chromosome.node_gene_type = genome.NodeGene population.Population.evaluate = FitnessFunctionWrapper pop = population.Population() pop.epoch(int(set['number_generations']), report=True, save_best=False, checkpoint_interval = None) winner = pop.stats[0][-1] print 'Training: Number of evaluations: %d' % winner.id print 'Training: Best NN fitness: %0.2f' % winner.fitness # Save the best network file = open('%s/winner.dat' % set['directory'], 'w') pickle.dump(winner, file) file.close() # Save the best network file = open('%s/winner-fitness.txt' % set['directory'], 'w') file.write('%f' % winner.fitness) file.close()
import math import random import cPickle as pickle from neat import config, population, chromosome, genome, visualize from cart_pole import CartPole def evaluate_population(population): simulation = CartPole(population, markov = False) # comment this line to print the status simulation.print_status = False simulation.run() if __name__ == "__main__": config.load('cpExp_config') # change the number of inputs accordingly to the type # of experiment: markov (6) or non-markov (3) # you can also set the configs in dpole_config as long # as you have two config files for each type of experiment config.Config.input_nodes = 3 # neuron model type chromosome.node_gene_type = genome.NodeGene #chromosome.node_gene_type = genome.CTNodeGene population.Population.evaluate = evaluate_population pop = population.Population() pop.epoch(500, report=1, save_best=0)