Почему мой генетический алгоритм не сходится к глобальному минимуму функции Easom?Python

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 Почему мой генетический алгоритм не сходится к глобальному минимуму функции Easom?

Сообщение Anonymous »

Я реализую генетический алгоритм для оптимизации функций тестирования, таких как Easom, Ackley и Three-Hump Camel. Однако он изо всех сил пытается достичь глобального минимума и вместо этого возвращает значения, которые находятся далеко (например, для функции Easom [1.19, 0.81] с пригодностью -2.51e-05 вместо f(π, π) = - 1). Точно так же результаты для функции Экли также не идеальны (например, [-0,10, -0,007] с пригодностью 0,56 вместо f(0, 0) = 0).
Вот часть моего генетического алгоритма, в которой, как я подозреваю, проблемы с выбором родителей, отбором потомков для новой популяции или настройкой параметров могут привести к плохой сходимости.
Выбор родителей

Код: Выделить всё

def select_parents(population, fitness, method):
if method == "PM":  # Panmixia
return random.sample(population, k=2)
elif (
method == "SE"
):  # Selective based on fitness: Parents with fitness below average fitness
avg_fitness = np.mean(fitness)
parents = [ind for ind, fit in zip(population, fitness) if fit < avg_fitness]
if len(parents) < 2:
if len(parents) == 0:
return random.sample(
population, k=2
)  # Fallback to random sampling from the entire population
else:
# return parents[0], parents[0]
return parents[0], random.choice(population)
return random.sample(parents, k=2)
elif method == "ID":  # Inbreeding
parent1 = random.choice(population)
parent2 = min(population, key=lambda x: hamming_distance(parent1, x))
return parent1, parent2
elif method == "OD":  # Outbreeding
parent1 = random.choice(population)
parent2 = max(population, key=lambda x: hamming_distance(parent1, x))
return parent1, parent2
Выбор детей

Код: Выделить всё

# Simple selection (SS), Selection with displacement (SD), Elite selection (ES)
def form_new_population(population, offspring, method, fitness_func):
if method == "SS":  # Simple selection
return offspring
elif method == "SD":  # Selection with displacement (unique individuals)
# Convert lists to tuples to make them hashable for set operations
unique_offspring = list(map(tuple, offspring))
unique_offspring = list(set(unique_offspring))
unique_offspring = list(map(list, unique_offspring))

if len(unique_offspring) < len(population):
additional_offspring = random.sample(
offspring, len(population) - len(unique_offspring)
)
unique_offspring.extend(additional_offspring)

return random.sample(unique_offspring, len(population))
elif method == "ES":  # Elite selection
combined = population + offspring
combined_fitness = evaluate_population(combined, fitness_func)
elite_indices = np.argsort(combined_fitness)[: len(population)]
return [combined[i] for i in elite_indices]
Основной цикл алгоритма

Код: Выделить всё

 for _ in range(pop_size // 2):
# Parent selection
parent1, parent2 = select_parents(
binary_population, fitness, parent_selection_method
)

# (crossover, mutation, inversion)
child1, child2 = process_children(
parent1,
parent2,
crossover_type,
mutation_rate,
inversion_rate,
CROSSOVER_CHANCE,
)

# convert back to float
decoded_child1 = decode_individual(child1, limits, n_bits)
decoded_child2 = decode_individual(child2, limits, n_bits)

children.append(decoded_child1)
children.append(decoded_child2)

# Children selection for new population
population = form_new_population(
population, children, population_formation, func
)

# Evaluate fitness for the new population
fitness = evaluate_population(population, func)

current_best = min(fitness)

# the best solution for the current iteration
best_solution_history.append(population[fitness.index(current_best)])

fitness_history.append(current_best)
iteration += 1

overall_best = min(fitness_history)
best_overall_solution = best_solution_history[fitness_history.index(overall_best)]
Я разместил полный код с графиком, показывающим значения пригодности для разных поколений, на своем Github.
Какие факторы мне следует учитывать при настройке моего алгоритма? улучшить сходимость? Существуют ли известные передовые методы настройки параметров таких функций, как Easom?

Подробнее здесь: https://stackoverflow.com/questions/790 ... -easom-fun
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Нейронная сеть и генетический алгоритм Connect4
    Anonymous » » в форуме Python
    0 Ответы
    25 Просмотры
    Последнее сообщение Anonymous
  • Генетический алгоритм - траектория автомобиля
    Anonymous » » в форуме Python
    0 Ответы
    22 Просмотры
    Последнее сообщение Anonymous
  • Генетический алгоритм - траектория автомобиля
    Anonymous » » в форуме Python
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Проблема N Queen Генетический алгоритм против детерминированного алгоритма
    Anonymous » » в форуме JAVA
    0 Ответы
    28 Просмотры
    Последнее сообщение Anonymous
  • Генетический алгоритм распределения Kubernetes
    Anonymous » » в форуме Python
    0 Ответы
    24 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»