def execute_ga(instance: ProblemInstance, settings: GaRunSettings = None, algorithm_params: GaAlgorithmParams = None) -> Result: start = time.perf_counter() if settings is None: settings = GaRunSettings() if algorithm_params is None: algorithm_params = GaAlgorithmParams() if settings.start_generation is None: settings.start_generation = {'variables': None, 'scores': None} if instance.consider_all: def f(X): return fitness_score_device_type(X, instance) instance.filtered_devices = get_unique_devices( filter_devices(instance)) scores = [] for x in permutations(len(instance.filtered_devices)): X = [] for index, include in enumerate(x): X.append(include) scores.append((X, f(X))) X = [True] * len(instance.filtered_devices) scores.append((X, f(X))) end = time.perf_counter() return create_result_enumeration(scores, end - start, instance, settings, algorithm_params) else: def f(X): return fitness_score_individual(X, instance) instance.filtered_devices = filter_devices(instance) algorithm_param = asdict(algorithm_params) model = ga(function=f, dimension=len(instance.filtered_devices), variable_type='bool', algorithm_parameters=algorithm_param, function_timeout=100000) model.run(**asdict(settings)) end = time.perf_counter() return create_result(model, end - start, instance, settings, algorithm_params)
iterations = 100 varbound = np.array([[-100, 100]] * 15) available_values = [np.arange(-100, 101)] * 15 my_local_optimizer = lambda arr, score: Hill_Climbing_descent( function=f, available_predictors_values=available_values, max_function_evals=50, start_solution=arr) model = ga(function=f, dimension=varbound.shape[0], variable_type='int', variable_boundaries=varbound, algorithm_parameters={ 'max_num_iteration': iterations, 'population_size': 400 }) for time in ('before_select', 'after_select', 'never'): model.run(no_plot=True, population_initializer=Population_initializer( select_best_of=3, local_optimization_step=time, local_optimizer=my_local_optimizer)) plt.plot(model.report, label=f"local optimization time = '{time}'") plt.xlabel('Generation')
# -*- coding: utf-8 -*- """ Created on Sat Feb 20 10:52:41 2021 @author: qtckp """ import sys sys.path.append('..') import numpy as np from geneticalgorithm2 import geneticalgorithm2 as ga def f(X): return np.sum(X) varbound = np.array([[0, 10]] * 20) model = ga(function=f, dimension=20, variable_type='real', variable_boundaries=varbound) print(str(model))
def f(X): return np.sum(converter(X)) dim = 80 varbound = np.array([[0, 1]] * dim) model = ga(function=f, dimension=dim, variable_type='real', variable_boundaries=varbound, algorithm_parameters={ 'max_num_iteration': 1000, 'population_size': 50, 'mutation_probability': 0.1, 'elit_ratio': 0.01, 'crossover_probability': 0.5, 'parents_portion': 0.3, 'crossover_type': 'uniform', 'mutation_type': 'uniform_by_center', 'selection_type': 'roulette', 'max_iteration_without_improv': None }) model.run(no_plot=False, stop_when_reached=0) model.plot_generation_scores( title='Population scores after ending of searching', save_as='with_dups.png') model.run(no_plot=False,
Crossover.shuffle(), 'shuffle', Crossover.segment(), 'segment', # only for real!!!! Crossover.mixed(), Crossover.arithmetic()) for mutation in mutations: for crossover in crossovers: print(f"mutation = {mutation}, crossover = {crossover}") algorithm_param = { 'max_num_iteration': 400, 'population_size': 100, 'mutation_probability': 0.1, 'elit_ratio': 0.01, 'crossover_probability': 0.5, 'parents_portion': 0.3, 'crossover_type': crossover, 'mutation_type': mutation, 'max_iteration_without_improv': None } model = ga(function=f, dimension=3, variable_type='real', variable_boundaries=varbound, algorithm_parameters=algorithm_param) model.run(no_plot=False)
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 16:20:05 2020 @author: qtckp """ import sys sys.path.append('..') import numpy as np from geneticalgorithm2 import geneticalgorithm2 as ga def f(X): return np.sum(X) varbound = np.array([[0.5, 1.5], [1, 100], [0, 1]]) vartype = np.array(['real', 'int', 'int']) model = ga(function=f, dimension=3, variable_type_mixed=vartype, variable_boundaries=varbound) model.run()
# -*- coding: utf-8 -*- """ Created on Thu Nov 19 16:18:37 2020 @author: qtckp """ import sys sys.path.append('..') import numpy as np from geneticalgorithm2 import geneticalgorithm2 as ga def f(X): return np.sum(X) varbound = np.array([[0, 10]] * 3) model = ga(function=f, dimension=3, variable_type='int', variable_boundaries=varbound) model.run()
child_inds = np.array(list(a_only) + list(b_only), dtype=np.int8) np.random.shuffle(child_inds) # mix childs = np.zeros((2, parent_a.size)) if intersect: childs[:, np.array(list(intersect))] = 1 childs[0, child_inds[:int(child_inds.size / 2)]] = 1 childs[1, child_inds[int(child_inds.size / 2):]] = 1 return childs[0, :], childs[1, :] model = ga( function=f, dimension=objects_count, variable_type='bool', algorithm_parameters={ 'max_num_iteration': 500, 'mutation_probability': 0, # no mutation, just crossover 'elit_ratio': 0.05, 'crossover_probability': 0.5, 'parents_portion': 0.3, 'crossover_type': my_crossover, 'max_iteration_without_improv': 20 }) model.run(no_plot=False, start_generation={ 'variables': start_generation, 'scores': None })
restaurant.SoupChef(input['soupChef']) restaurant.MainChef(input['mainChef']) restaurant.DesserChef(input['desserChef']) restaurant.Barista(input['barista']) restaurant.Waiter2(input['waiter2'][0], input['waiter2'][1]) restaurant.Delivery(input['delivery'][0], input['delivery'][1]) restaurant.Cashier(input['cashier'][0], input['cashier'][1]) print("\n") for system in Systems: print(f'Queue in system {system.name}: {restaurant.K_I(system)}') system_info([1, 1, 3, 2]) varbound = np.array([[1, 10], [1, 10], [1, 10], [1, 10]]) model = ga(function=generic_cost_function, dimension=4, variable_type='int', variable_boundaries=varbound, algorithm_parameters={ 'max_num_iteration': 200, 'population_size': 10, 'mutation_probability': 0.1, 'elit_ratio': 0.01, 'crossover_probability': 0.5, 'parents_portion': 0.3, 'max_iteration_without_improv': None }) model.run() system_info(model.output_dict['variable']) #test_algorithm(100)
vartype = np.array(['int'] * nVars) #GA parameters algorithm_param = {'max_num_iteration': 500,\ 'population_size':100,\ 'mutation_probability':0.30,\ 'elit_ratio': 0.10,\ 'crossover_probability': 0.50,\ 'parents_portion': 0.30,\ 'crossover_type':'uniform',\ 'max_iteration_without_improv':100} #Solve model = ga(function=f, dimension=nVars, variable_type_mixed=vartype, variable_boundaries=varbounds, algorithm_parameters=algorithm_param) model.run() #print x = model.best_variable objFun = model.best_function paths['activated'] = 0 for p in paths.index: paths.activated[p] = x[p] print('\n\nAll Paths:') print(paths) print('\nSelected Paths:')
(Selection.ranking(), 'ranking'), (Selection.linear_ranking(selection_pressure=1.5), 'linear_ranking; selection_pressure = 1.5'), (Selection.linear_ranking(selection_pressure=1.9), 'linear_ranking; selection_pressure = 1.9'), (Selection.tournament(tau=2), 'tournament; size = 2'), (Selection.tournament(tau=4), 'tournament; size = 4')] start_gen = np.random.uniform(0, 10, (100, dim)) for sel, lab in selections: model = ga(function=f, dimension=dim, variable_type='real', variable_boundaries=varbound, algorithm_parameters={ 'max_num_iteration': 400, 'selection_type': sel }) model.run(no_plot=True, start_generation={ 'variables': start_gen, 'scores': None }) plt.plot(model.report, label=lab) plt.xlabel('Generation') plt.ylabel('Minimized function (sum of array)') plt.title('Several selection types for one task')
from OptimizationTestFunctions import Eggholder dim = 2*15 f = Eggholder(dim) xmin, xmax, ymin, ymax = f.bounds varbound = np.array([[xmin, xmax], [ymin, ymax]]*15) model = ga(function=f, dimension = dim, variable_type='real', variable_boundaries=varbound, algorithm_parameters = { 'max_num_iteration': 300, 'population_size': 100 }) # run and save last generation to file filename = "eggholder_lastgen.npz" model.run(save_last_generation_as = filename) # load start generation from file model.run(start_generation=filename)
return imageTest.getDifference(individual, "MSE") #return imageTest.getDifference(individual, "SSIM") from geneticalgorithm2 import geneticalgorithm2 as ga # GA method from geneticalgorithm2 import Callbacks # for callbacks model = ga(function=getDiff, dimension=NUM_OF_PARAMS, variable_type='real', variable_boundaries=np.array([[BOUNDS_LOW, BOUNDS_HIGH]] * NUM_OF_PARAMS), function_timeout=100, algorithm_parameters={ 'max_num_iteration': 15, 'population_size': POPULATION_SIZE, 'mutation_probability': P_MUTATION, 'elit_ratio': HALL_OF_FAME_SIZE / POPULATION_SIZE, 'crossover_probability': P_CROSSOVER, 'parents_portion': 0.3, 'crossover_type': 'two_point', 'mutation_type': 'uniform_by_center', 'selection_type': 'tournament', 'max_iteration_without_improv': None }) # save the best current drawing (used as a callback): def saveImage(gen, polygonData): # create folder if does not exist: folder = "images/results/run-{}-{}".format(POLYGON_SIZE, NUM_OF_POLYGONS)
dim = 15 np.random.seed(3) rands = np.random.uniform(-10, 10, 100) def func(X): return np.sum(rands[X.astype(int)]) + X.sum() iterations = 900 varbound = np.array([[0,99]]*dim) model = ga(function=func, dimension=dim, variable_type='int', variable_boundaries=varbound, algorithm_parameters={ 'max_num_iteration': iterations }) start_pop = np.random.randint(0, 10, size = (100, dim)) start_gen = { 'variables': start_pop, 'scores': None } np.random.seed(3) model.run(no_plot = True, start_generation=start_gen) plt.plot(model.report, label = 'without dups removing')