MLE/03_euler_gen_alg/main.py

178 lines
6.1 KiB
Python

"""
Schreibe einen genetischen Algorithmus, der die Parameter
(a,b,c,d) der Funktion f (x ) = ax 3 + bx 2 + cx + d so optimiert,
dass damit die Funktion g(x ) = e x im Bereich [-1..1] möglichst
gut angenähert wird. Nutze dazu den quadratischen Fehler (oder
alternativ die Fläche zwischen der e-Funktion und dem Polynom).
Zeichne die Lösung und vergleiche die Koeffizienten mit denen der
Taylor-Reihe um 0.
"""
import numpy as np
import random
import time
import utils
POPULATION_SIZE = 10
SELECTION_SIZE = (POPULATION_SIZE * 7) // 10 # 70% of population, rounded down for selection
XOVER_PAIR_SIZE = (POPULATION_SIZE - SELECTION_SIZE)
XOVER_POINT = 3 # 4th position
MUTATION_BITS = POPULATION_SIZE // 2
fitness = 2
fitness_arr = [0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1]
gray_pop = [] # 32 Bit-Binary as String
bin_pop = [] # 32 Bit-Binary as String
bin_pop_params = [] # Arrays with 4 Binary values of 8s
new_pop = [] # 32 Bit Gray-Code as String
def generate_random_population(num=POPULATION_SIZE):
""" Puts random 32 Bit binary strings into 4 * 8 Bit long params. """
# Generate new population
for _ in range(num):
gray = format(random.getrandbits(32), '032b')
gray_pop.append(gray)
bin_str = utils.gray_to_bin(gray)
bin_pop.append(bin_str)
params = [bin_str[i:i+7] for i in range(0, 31, 8)]
bin_pop_params.append(params)
return bin_pop_params
def quadratic_error(original_fn, approx_fn, n):
error = 0.0
for i in range(-(n // 2), (n // 2) + 1):
error += (original_fn(i) - approx_fn(i))**2
return error
def eval_fitness(bin_pop_values):
""" Returns an array with fitness value of every individual in a population. """
fitness_arr = []
for params in bin_pop_values:
# Convert binary string to parameters for bin_values
a, b, c, d = [utils.bin_to_param(param) for param in params] # assign params to batch of population
# Create polynomial function with current parameters
approx = lambda x: a*x**3 + b*x**2 + c*x + d
e_func = lambda x: np.e**x
quad_error = quadratic_error(e_func, approx, 3) # the bigger the error, the worse the fitness
inverse_fitness = 1 / quad_error # using inverse to find small errors easier
inverse_fitness = round(inverse_fitness, 2)
print("Fitness: " + str(inverse_fitness)) # debugging
fitness_arr.append(inverse_fitness) # save fitness
return fitness_arr
def select(fitness_arr):
gray_pop_copy = gray_pop.copy() # copy of population
fitness_arr_copy = fitness_arr.copy() # copy of fitness array
selected_pop = []
while len(selected_pop) < SELECTION_SIZE:
sum_of_fitness = sum(fitness_arr_copy)
if sum_of_fitness == 0:
break
# Roulette logic
roulette_num = random.random()
cumulative_p = 0
for i, fitness in enumerate(fitness_arr_copy):
cumulative_p += fitness / sum_of_fitness
if roulette_num < cumulative_p:
# Add the selected individual
selected_pop.append(gray_pop_copy[i])
# Remove selected individual and their fitness
gray_pop_copy.pop(i)
fitness_arr_copy.pop(i)
break
return selected_pop
def xover(population):
"""Performs crossover on pairs of individuals from population."""
offspring = []
# Randomly shuffle the population to avoid bias
population_copy = population.copy()
random.shuffle(population_copy)
# Process pairs
i = 0
while i < XOVER_PAIR_SIZE:
parent_a = population_copy[i]
parent_b = population_copy[i + 1]
# Create two new offspring by swapping parts at random xover point
offspring_a = parent_a[:XOVER_POINT] + parent_b[XOVER_POINT:]
offspring_b = parent_b[:XOVER_POINT] + parent_a[XOVER_POINT:]
offspring.extend([offspring_a, offspring_b])
i += 2 # Move to next pair
if len(offspring) > XOVER_PAIR_SIZE:
offspring = offspring[:XOVER_PAIR_SIZE]
return offspring
def mutate(population, mutation_rate):
"""Mutate random bits in the population with given mutation rate"""
for _ in range(mutation_rate):
# Select random individual and convert to list for efficient modification
random_num = random.randrange(POPULATION_SIZE)
bits = list(population[random_num])
# Flip random bit
bit_pos = random.randrange(32)
bits[bit_pos] = '1' if bits[bit_pos] == '0' else '0'
# Convert back to string and update population
population[random_num] = ''.join(bits) # will work because lists are passed by reference
bin_pop_values = generate_random_population(POPULATION_SIZE)
print("Working...")
iteration = 0 # debugging
while not np.any((np.array(fitness_arr)) > 200): # Continue while any fitness value is > 1
print("\nIteration: " + str(iteration)) # debugging
# Evaluate fitness
fitness_arr = eval_fitness(bin_pop_values)
# Selection
new_pop = select(fitness_arr) # assigns
# Crossover
offspring = xover(gray_pop)
new_pop.extend(offspring) # Add offspring to population
# Mutation
mutate(new_pop, MUTATION_BITS)
# Update populations for next generation
gray_pop = new_pop.copy()
bin_pop_values = []
for gray_bin_string in gray_pop:
bin_str = utils.gray_to_bin(gray_bin_string)
params = [bin_str[i:i+7] for i in range(0, 31, 8)]
bin_pop_values.append(params)
# time.sleep(0.5) # debugging
iteration += 1 # debugging
max_fitness_index = np.argmax(np.array(fitness_arr))
a, b, c, d = [utils.bin_to_param(param) for param in bin_pop_values[max_fitness_index]]
print("Chosen value: " + str(fitness_arr[max_fitness_index])) # debugging
print("at index: " + str(max_fitness_index)) # debugging
print("a: " + str(a) + "; b: " + str(b) + "; c: " + str(c) + "; d: " + str(d) )
utils.plot_graph(a, b, c, d)