Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# Multiprocessing is not supported yet.
# pool = multiprocessing.Pool(multiprocessing.cpu_count())
# toolbox.register("map", pool.map)
# Run ga optimization
self.output(f" parameter optimization space :{total_size}")
self.output(f" the total number of population each generation :{pop_size}")
self.output(f" the number of fine screening :{mu}")
self.output(f" iterations :{ngen}")
self.output(f" crossover probability :{cxpb:.0%}")
self.output(f" mutation probability :{mutpb:.0%}")
start = time()
algorithms.eaMuPlusLambda(
pop,
toolbox,
mu,
lambda_,
cxpb,
mutpb,
ngen,
stats,
halloffame=hof
)
end = time()
cost = int((end - start))
self.output(f" genetic algorithm optimization is complete , time consuming {cost} second ")
def main():
#random.seed(21)
pop = toolbox.population(n=300)
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)
algorithms.eaSimple(pop, toolbox, 0.5, 0.2, 40, stats, halloffame=hof)
return pop, stats, hof
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
M = "POP_SIZE PROFIGA ERROR;"
print(M)
# --filter best inds;
locale.population[:] = evolutionHooks.selBest(locale.population, locale.POP_SIZE)
checkPopulation(locale.population, "Population dead after selection of score filter.")
assert (None not in locale.population)
# print(EvolutionStatistics)
#FinalBestScores.append(Stats['max'])
# --select best individues to procreate
LAMBDA = max(World.genconf._lambda, locale.POP_SIZE - len(locale.population))
TournamentSize = max(2 * LAMBDA, len(locale.population))
offspring = evolutionHooks.Tournament(locale.population, LAMBDA, TournamentSize)
offspring = [deepcopy(x) for x in offspring] # is deepcopy necessary?
# --modify and integrate offspring;
offspring = algorithms.varAnd(
offspring, World.tools, World.genconf.cxpb, World.genconf.mutpb
)
locale.extratools.ageZero(offspring)
locale.population += offspring
# --NOW DOESN'T MATTER IF SOME INDIVIDUE LACKS FITNESS VALUES;
assert (None not in locale.population)
# --immigrate individual from HallOfFame;
if random.random() < 0.2:
locale.population = locale.extratools.ImmigrateHoF(locale.population)
# --immigrate random number of random individues;
if random.random() < 0.5:
locale.population = locale.extratools.ImmigrateRandom((2, 7), locale.population)
assert (len(locale.population))
assert (None not in locale.population)
toolbox.register("evaluate", deap_efel_eval1.evaluate)
# Register the mate operator
toolbox.register(
"mate",
deap.tools.cxSimulatedBinaryBounded,
eta=ETA,
low=LOWER,
up=UPPER)
# Register the mutation operator
toolbox.register("mutate", deap.tools.mutPolynomialBounded, eta=ETA,
low=LOWER, up=UPPER, indpb=0.1)
# Register the variate operator
toolbox.register("variate", deap.algorithms.varAnd)
# Register the selector (picks parents from population)
toolbox.register(
"select",
tools.selNSGA2)
# Generate the population object
pop = toolbox.population(n=MU)
# Register the statistics we want to record during the optimisation
# In this case only the minimal value
first_stats = tools.Statistics(key=lambda ind: ind.fitness.values[0])
second_stats = tools.Statistics(key=lambda ind: ind.fitness.values[1])
stats = tools.MultiStatistics(obj1=first_stats, obj2=second_stats)
stats.register("min", numpy.min, axis=0)
def main():
random.seed(64)
pop = toolbox.population(n=300)
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=40,
stats=stats, halloffame=hof, verbose=True)
return pop, log, hof
random.seed(64)
NGEN = 50
MU = 50
LAMBDA = 100
CXPB = 0.7
MUTPB = 0.2
pop = toolbox.population(n=MU)
hof = tools.ParetoFront()
stats = tools.Statistics(lambda ind: ind.fitness.values)
stats.register("avg", numpy.mean, axis=0)
stats.register("std", numpy.std, axis=0)
stats.register("min", numpy.min, axis=0)
stats.register("max", numpy.max, axis=0)
algorithms.eaMuPlusLambda(pop, toolbox, MU, LAMBDA, CXPB, MUTPB, NGEN, stats,
halloffame=hof)
return pop, stats, hof
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)
# The centroid is set to a vector of 5.0 see http://www.lri.fr/~hansen/cmaes_inmatlab.html
# for more details about the rastrigin and other tests for CMA-ES
strategy = cma.Strategy(centroid=[5.0]*N, sigma=5.0, lambda_=20*N)
toolbox.register("generate", strategy.generate, creator.Individual)
toolbox.register("update", strategy.update)
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)
#logger = tools.EvolutionLogger(stats.functions.keys())
# The CMA-ES algorithm converge with good probability with those settings
algorithms.eaGenerateUpdate(toolbox, ngen=250, stats=stats, halloffame=hof)
# print "Best individual is %s, %s" % (hof[0], hof[0].fitness.values)
return hof[0].fitness.values[0]
for idx, deme in enumerate(demes):
for ind in deme:
ind.fitness.values = toolbox.evaluate(ind)
stats.update(deme, idx)
hof.update(deme)
logger.logGeneration(gen="0", deme=idx, evals=len(deme), stats=stats, index=idx)
stats.update(demes[0]+demes[1]+demes[2], 3)
logger.logGeneration(gen=0, deme=idx, evals="-", stats=stats, index=3)
gen = 1
while gen <= NGEN and stats.max[3][-1][0] < 100.0:
for idx, deme in enumerate(demes):
deme[:] = toolbox.select(deme, len(deme))
deme[:] = algorithms.varAnd(deme, toolbox, cxpb=CXPB, mutpb=MUTPB)
invalid_ind = [ind for ind in deme if not ind.fitness.valid]
for ind in invalid_ind:
ind.fitness.values = toolbox.evaluate(ind)
stats.update(deme, idx)
hof.update(deme)
logger.logGeneration(gen="%d" %gen, deme=idx, evals=len(invalid_ind), stats=stats, index=idx)
if gen % MIG_RATE == 0:
toolbox.migrate(demes)
stats.update(demes[0]+demes[1]+demes[2], 3)
logger.logGeneration(gen="%d" % gen, deme="-", evals="-", stats=stats, index=3)
gen += 1
return demes, stats, hof