- Кроссовер: одноточечный (OT), двухточечный (DT)
- Скорость мутаций: 0,001 (M1), 0,05 (M2), 0,01 (M3)
- Отбор родителей: Инбридинг (ID), Аутбридинг (AD), Панмиксия (PM), Селекционное разведение (SE).
- Отбор потомков для новой популяции: Нормальный отбор ( ZV), Выбор смещения (VV), Элитный отбор (EV)
- Критерии остановки: Фиксированные итерации (KI), Расстояние между особями (VCH), Расстояние между средними значениями приспособленности (VF)< /li>
- Сравнить производительность при различных комбинациях этих параметров(с использованием таблиц).
- Постройте графики, показывающие зависимость минимального значения функции от численности популяции, частоты тестовых мутаций, типов скрещивания, отбора родителей и формирования популяции.
Код: Выделить всё
{
"name": "error",
"message": "unpack requires a buffer of 4 bytes",
"stack": "---------------------------------------------------------------------------
error Traceback (most recent call last)
Cell In[36], line 2
1 # Run the genetic algorithm
----> 2 best_solution, best_fitness = genetic_algorithm(
3 iterations=100,
4 pop_count=50,
5 num_children=50,
6 crossover_point_count=1,
7 mutation_chance=0.1,
8 inversion_chance=0.05,
9 function_constraints=[(-100, 100), (-100, 100)],
10 fit_f=easom,
11 parent_selection=inbreeding,
12 children_selection=normal_selection,
13 )
14 print(f\"Best solution: {best_solution}, with fitness: {best_fitness}\")
Cell In[35], line 55, in genetic_algorithm(iterations, pop_count, num_children, crossover_point_count, mutation_chance, inversion_chance, function_constraints, fit_f, parent_selection, children_selection)
50 children[i] = apply_mutation_and_inversion(
51 children[i], mutation_chance, inversion_chance
52 )
54 # convert children to float to calculate fitness
---> 55 children = [[binary_to_float(gene) for gene in child] for child in children]
57 # check constraints for children
58 for i in range(len(children)):
Cell In[35], line 55, in [*](.0)
50 children[i] = apply_mutation_and_inversion(
51 children[i], mutation_chance, inversion_chance
52 )
54 # convert children to float to calculate fitness
---> 55 children = [[binary_to_float(gene) for gene in child] for child in children]
57 # check constraints for children
58 for i in range(len(children)):
Cell In[35], line 55, in (.0)
50 children[i] = apply_mutation_and_inversion(
51 children[i], mutation_chance, inversion_chance
52 )
54 # convert children to float to calculate fitness
---> 55 children = [[binary_to_float(gene) for gene in child] for child in children]
57 # check constraints for children
58 for i in range(len(children)):
Cell In[20], line 26, in binary_to_float(binary_list)
24 # pack these bytes together into binary data, then unpack as a float
25 binary_data = struct.pack(\"B\" * len(byte_values), *byte_values)
---> 26 float_num = struct.unpack(\"f\", binary_data)[0]
28 return float_num
error: unpack requires a buffer of 4 bytes"
}
Код: Выделить всё
def binary_to_float(binary_list):
# convert binary string into bytes
byte_values = [int("".join(str(bit) for bit in binary_list[i:i + 8]), 2) for i in range(0, len(binary_list), 8)]
# pack these bytes together into binary data, then unpack as a float
binary_data = struct.pack("B" * len(byte_values), *byte_values)
float_num = struct.unpack("f", binary_data)[0] # ERROR: This line raises the unpacking error
return float_num
- Функции приспособленности для трех целевых функций.
- Двоичное преобразование чисел с плавающей запятой в двоичные строки и наоборот.
- Операции кроссовера, мутации и инверсии.
- Родительский элемент методы выбора, возвращающие двух родителей на основе критериев выбора.
- Методы выбора дочерних элементов, включая элитный выбор, но я получаю ошибки
(например, TypeError: неподдерживаемый тип операнда) .
- Что вызывает ошибку «для распаковки требуется буфер размером 4 байта» в функцииbinary_to_float?
- Как правильно составить генетический алгоритм для обработки этих параметров и продолжить тестирование?
Подробнее здесь: https://stackoverflow.com/questions/790 ... ion-format