How to use the deap.tools.selTournament function in deap

To help you get started, we’ve selected a few deap examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github renatoosousa / GeneticAlgorithmForFeatureSelection / gaFeatureSelection.py View on Github external
"""
    # create individual
    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Individual", list, fitness=creator.FitnessMax)

    # create toolbox
    toolbox = base.Toolbox()
    toolbox.register("attr_bool", random.randint, 0, 1)
    toolbox.register("individual", tools.initRepeat,
                     creator.Individual, toolbox.attr_bool, len(X.columns))
    toolbox.register("population", tools.initRepeat, list,
                     toolbox.individual)
    toolbox.register("evaluate", getFitness, X=X, y=y)
    toolbox.register("mate", tools.cxOnePoint)
    toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
    toolbox.register("select", tools.selTournament, tournsize=3)

    # initialize parameters
    pop = toolbox.population(n=n_population)
    hof = tools.HallOfFame(n_population * n_generation)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean)
    stats.register("min", np.min)
    stats.register("max", np.max)

    # genetic algorithm
    pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2,
                                   ngen=n_generation, stats=stats, halloffame=hof,
                                   verbose=True)

    # return hall of fame
    return hof
github scoliann / GeneticAlgorithmFeatureSelection / gaFeatureSelectionExample.py View on Github external
# Create Individual
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)

# Create Toolbox
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, len(dfData.columns) - 1)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

# Continue filling toolbox...
toolbox.register("evaluate", getFitness, X_train=X_train, X_test=X_test, y_train=y_train, y_test=y_test)
toolbox.register("mate", tools.cxOnePoint)
toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
toolbox.register("select", tools.selTournament, tournsize=3)

#========

def getHof():

	# Initialize variables to use eaSimple
	numPop = 100
	numGen = 10
	pop = toolbox.population(n=numPop)
	hof = tools.HallOfFame(numPop * numGen)
	stats = tools.Statistics(lambda ind: ind.fitness.values)
	stats.register("avg", numpy.mean)
	stats.register("std", numpy.std)
	stats.register("min", numpy.min)
	stats.register("max", numpy.max)
github thinkingmachines / christmAIs / christmais / trainer.py View on Github external
# Start optimization via genetic algorithm
        population = init_population.copy()
        self.logger.info('Optimization has started')
        with trange(steps, desc='GEN', ncols=100, unit='gen') as t:
            for gen in t:

                # Filesystem IO
                if outdir is not None:
                    dir_ = outdir + '/gen{}/'.format(str(gen + 1).zfill(2))

                next_pop = []  # Next population

                for idx in range(len(population)):
                    # Select parents using tournament selection
                    parents = tools.selTournament(
                        population, k=2, tournsize=4, fit_attr='fitness'
                    )
                    best_parent = max(
                        parents, key=operator.attrgetter('fitness')
                    )

                    # Generate new child using uniform crossover
                    c_artist = best_parent.artist
                    c_gene = tools.cxUniform(
                        parents[0].gene.copy(), parents[1].gene.copy(), indpb
                    )[0]
                    if np.random.uniform() < mutpb:
                        c_gene = tools.mutShuffleIndexes(c_gene, indpb)[0]
                    c_image = c_artist.draw_from_gene(c_gene)
                    c_fitness = self._fitness_fcn([c_image], target=target)[0]
                    child = Individual(c_image, c_gene, c_fitness, c_artist)
github Capnode / Algoloop / Algorithm.Python / PythonPackageTestAlgorithm.py View on Github external
# onemax example evolves to print list of ones: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    numpy.random.seed(1)
    def evalOneMax(individual):
        return sum(individual),

    creator.create("FitnessMax", base.Fitness, weights=(1.0,))
    creator.create("Individual", list, typecode='b', fitness=creator.FitnessMax)

    toolbox = base.Toolbox()
    toolbox.register("attr_bool", numpy.random.randint, 0, 1)
    toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, 10)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)
    toolbox.register("evaluate", evalOneMax)
    toolbox.register("mate", tools.cxTwoPoint)
    toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
    toolbox.register("select", tools.selTournament, tournsize=3)

    pop   = toolbox.population(n=50)
    hof   = tools.HallOfFame(1)
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", numpy.mean)
    stats.register("std", numpy.std)
    stats.register("min", numpy.min)
    stats.register("max", numpy.max)

    pop, log = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=30, 
                                   stats=stats, halloffame=hof, verbose=False) # change to verbose=True to see evolution table
    print ("deap test >>>", hof[0])
github jstrassburg / evolving-search-relevancy / program.py View on Github external
    @staticmethod
    def main():
        creator.create("FitnessMax", base.Fitness, weights=(1.0,))
        creator.create("Individual", list, fitness=creator.FitnessMax)

        toolbox = base.Toolbox()
        toolbox.register("attr_bool", random.randint, 0, 1)
        toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, CandidateSolution.size)
        toolbox.register("population", tools.initRepeat, list, toolbox.individual)

        toolbox.register("evaluate", CandidateSolution.evaluate)
        toolbox.register("mate", tools.cxTwoPoint)
        toolbox.register("mutate", tools.mutFlipBit, indpb=0.05)
        toolbox.register("select", tools.selTournament, tournsize=3)

        population = toolbox.population(n=200)

        hof = tools.HallOfFame(maxsize=1)
        final_population = algorithms.eaSimple(population, toolbox, cxpb=0.5, mutpb=0.1, ngen=10, halloffame=hof)

        print final_population
        print "Best solution: {0}, fitness: {1}".format(hof[0], hof[0].fitness)

        best_solution = CandidateSolution(hof[0])
        print "Best solution: name_boost = {0}, description_boost = {1}".format(
            best_solution.name_boost.value, best_solution.description_boost.value)
github soravux / scoop / bench / evosn / multi_evosn.py View on Github external
# Gene initializer
toolbox.register("network", genNetwork, dimension=INPUTS,
        min_size=sizes[INPUTS][0] if INPUTS in sizes else 25,
        max_size=sizes[INPUTS][1] if INPUTS in sizes else 35)

# Structure initializers
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.network)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

toolbox.register("evaluate", evalEvoSN, dimension=INPUTS)
toolbox.register("mate", tools.cxTwoPoints)
toolbox.register("mutate", mutWire, dimension=INPUTS, indpb=0.05)
toolbox.register("addwire", mutAddWire, dimension=INPUTS)
toolbox.register("delwire", mutDelWire)
toolbox.register("select", tools.selTournament, tournsize=3)

p = Pool(args.cores)
toolbox.register("map", p.map)
#logging.warning("avant main")
def main():
    # test if file is ok before starting the test
    if args.filename:
        open(args.filename).close()
    random.seed(64)
    
    beginTime = time.time()
    evaluationTime = 0

    population = toolbox.population(n=args.population)
    hof = tools.ParetoFront()
github pelillian / varro / algo / archive / evolve.py View on Github external
# Defines a mutation function that takes in
    # a single tuple (an individual) and for each
    # entry in the tuple, we have a different probability
    # of mutation given by indpb, and parameters for
    # how much to mutate each entry by, using a gaussian
    # distribution
    toolbox.register("mutate", 
                     tools.mutGaussian, 
                     mu=0, 
                     sigma=1, 
                     indpb=0.1)
                     
    # Defines the selection method for the mating
    # pool / offspring 
    toolbox.register("select", 
                     tools.selTournament, 
                     tournsize=3)
                     
    # Defines the evaluation function
    # we will use for calculating the fitness of
    # an individual
    toolbox.register("evaluate", 
                     evaluate_nn_function_approx)

    return toolbox
github fzahari / ParFit / ParFit / Ga.py View on Github external
for i in xrange(len(child)):
                    if child[i] > max:
                        child[i] = max
                    elif child[i] < min:
                        child[i] = min
            return offspring
        return wrapper
    return decorator

   MIN=-3.0
   MAX=3.0

   toolbox.decorate("mate", checkBounds(MIN, MAX))
   toolbox.decorate("mutate", checkBounds(MIN, MAX))

   toolbox.register("select",tools.selTournament,tournsize=3)

   stats = tools.Statistics(key=lambda ind: ind.fitness.values[0])
   stats.register("avg", numpy.mean)
   stats.register("std", numpy.std)
   stats.register("min", numpy.min)
   stats.register("max", numpy.max)

   hof = tools.HallOfFame(np, similar=numpy.allclose)

   pop=toolbox.population(n=50)
   eaSimple(pop,toolbox,cxpb=0.35,mutpb=0.05,ngen=ngen,stats=stats,halloffame=hof,verbose=True)
   print "The best rmse is", hof[0].fitness.values[0],"corresponding to the parameters",numpy.array(hof[0])

   #return hof[0:int(np/20)]
   return hof
github cjekel / piecewise_linear_fit_py / pwlf / ga.py View on Github external
new = random.choice(set_to_choose)
        temp_set.add(new)
        return temp_set,

    toolbox = base.Toolbox()

    # set up the population
    toolbox.register("individual", random_samp, nvar)
    toolbox.register("population", tools.initRepeat, list, toolbox.individual)

    # set up the GA functions
    toolbox.register("evaluate", evaluation)
    toolbox.register("mate", cxSet)
    toolbox.register("mutate", mutSet)
    # toolbox.register("select", tools.selNSGA2)
    toolbox.register("select", tools.selTournament, tournsize=tournsize)

    # initialize the population
    pop = toolbox.population(n=mu)
    hof = tools.ParetoFront()
    stats = tools.Statistics(lambda ind: ind.fitness.values)
    stats.register("avg", np.mean, axis=0)
    stats.register("std", np.std, axis=0)
    stats.register("min", np.min, axis=0)
    stats.register("max", np.max, axis=0)
    # run the GA
    algorithms.eaMuPlusLambda(pop, toolbox, mu, lam, cxpb, mutpb, ngen, stats,
                              halloffame=hof, verbose=verbose)
    return pop, hof, stats
github EvoML / EvoML / Sub Spacing / sub - spacing / auto_feature.py View on Github external
#ToDo: make all the parameters in the init function
        input_feat = list(X.columns.values);
        creator.create("FitnessMax", base.Fitness, weights=(-1.0,))
        creator.create("Individual", list, fitness=creator.FitnessMax)
        self.X = X
        self.y = y
        #self.unseen_y = unseen_y
        #self.unseen_X = unseen_X
        toolbox = base.Toolbox()
        toolbox.register("attr_bool", self.get_indiv_sample_bag, data=X, output=y, base_estimator=self.base_estimator)
        toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=self.N_individual)
        toolbox.register("population", tools.initRepeat, list, toolbox.individual)
        toolbox.register("evaluate", evalOneMax2,X_f=X, y_f=y)
        toolbox.register("mate", self.crossover_func)
        toolbox.register("mutate", mutate_feat, indpb=self.indpb,input_fe = input_feat, X_tr = X)
        toolbox.register("select", tools.selTournament, tournsize=3)
        
        pop = toolbox.population(n=self.N_population)
        hof = tools.HallOfFame(1, similar=compare_hof);
        stats = tools.Statistics(lambda ind: ind.fitness.values)
        stats.register("avg", np.mean)
        stats.register("min", np.min)
        stats.register("max", np.max)
        self.pop, self.logbook = algorithms.eaSimple(pop, toolbox, cxpb=self.cxpb, mutpb=self.mutpb, ngen=self.ngen, stats=stats, halloffame=hof,  verbose=False)
        self.hof = hof
        #return pop, logbook, hof
        return self