improved code structure; fitness evaluation done; selection done
parent
bc1ffb957a
commit
a6b906d9b3
|
|
@ -1,83 +0,0 @@
|
|||
"""
|
||||
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 struct
|
||||
import time
|
||||
# import matplotlib.pyplot as plt
|
||||
|
||||
def generate_random_population():
|
||||
pop_grey = [format(random.getrandbits(32), '32b') for i in range(10)]
|
||||
pop_bin = grey_to_bin(pop_grey)
|
||||
a, b, c, d = pop_bin[0:7], pop_bin[8:15], pop_bin[16:23], pop_bin[24:31]
|
||||
|
||||
return [a, b, c, d]
|
||||
|
||||
def grey_to_bin(gray):
|
||||
"""Convert Gray code to binary, operating on the integer value directly"""
|
||||
num = int(gray, 2) # Convert string to integer
|
||||
mask = num
|
||||
while mask != 0:
|
||||
mask >>= 1
|
||||
num ^= mask
|
||||
return format(num, f'0{len(gray)}b') # Convert back to binary string with same length
|
||||
|
||||
def bin_to_grey(binary):
|
||||
"""Convert binary to Gray code using XOR with right shift"""
|
||||
num = int(binary, 2) # Convert string to integer
|
||||
gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1)
|
||||
return format(gray, f'0{len(binary)}b') # Convert back to binary string with same length
|
||||
|
||||
def bin_to_param(binary, q_min = 0.0, q_max = 10.0):
|
||||
"""Convert binary string to float parameter in range [q_min, q_max]"""
|
||||
val = int(binary, 2) / 25.5 * 10 # conversion to 0.0 - 10.0 float
|
||||
# Scale to range [q_min, q_max]
|
||||
q = q_min + ((q_max - q_min) / (2**len(binary))) * val
|
||||
|
||||
return q
|
||||
|
||||
|
||||
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 e_fn_approx(a, b, c, d, x = 1):
|
||||
return a*x**3 + b*x**2 + c*x + d
|
||||
|
||||
def fuck_that_shit_up():
|
||||
bin_values = generate_random_population()
|
||||
# Convert binary string to parameters for bin_values
|
||||
a, b, c, d = [bin_to_param(bin) for bin in bin_values]
|
||||
|
||||
e_func = lambda x: np.e**x
|
||||
fixed_approx = lambda x: e_fn_approx(a, b, c, d, x)
|
||||
fitness = quadratic_error(e_func, fixed_approx, 6)
|
||||
|
||||
while fitness > 0.01:
|
||||
# calc fitness
|
||||
fitness = quadratic_error(e_func, fixed_approx, 6)
|
||||
print(fitness)
|
||||
time.sleep(1)
|
||||
|
||||
# selection
|
||||
# crossover
|
||||
# mutation
|
||||
|
||||
# neue population
|
||||
return 0
|
||||
|
||||
fuck_that_shit_up()
|
||||
# b = format(random.getrandbits(32), '32b')
|
||||
# print(quadratic_error(e_func, fixed_approx, 6)) # hopefully works
|
||||
|
|
@ -0,0 +1,111 @@
|
|||
"""
|
||||
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 struct
|
||||
import time
|
||||
import utils
|
||||
# import matplotlib.pyplot as plt
|
||||
|
||||
POPULATION_SIZE = 10
|
||||
SELECTION_SIZE = (POPULATION_SIZE * 7) // 10 # 70% of population, rounded down for selection
|
||||
CROSSOVER_PAIR_SIZE = (POPULATION_SIZE - SELECTION_SIZE) // 2 # pairs needed for crossover
|
||||
XOVER_POINT = 3
|
||||
|
||||
fitness = 0.01
|
||||
pop_grey = []
|
||||
pop_bin = []
|
||||
pop_bin_params = []
|
||||
pop_new = []
|
||||
|
||||
e_func = lambda x: np.e**x
|
||||
|
||||
def generate_random_population():
|
||||
for i in range(POPULATION_SIZE):
|
||||
pop_grey[i] = format(random.getrandbits(32), '32b')
|
||||
pop_bin[i] = utils.grey_to_bin(pop_grey[i])
|
||||
pop_bin_params[i] = [pop_bin[i][0:7], pop_bin[i][8:15], pop_bin[i][16:23], pop_bin[i][24:31]]
|
||||
|
||||
return pop_bin_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(pop_bin_values):
|
||||
""" Returns an array with fitness value of every individual in a population."""
|
||||
fitness_arr = []
|
||||
for params in pop_bin_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
|
||||
fitness = quadratic_error(e_func, approx, 6)
|
||||
print(fitness) # debugging
|
||||
|
||||
fitness_arr.append(fitness) # save fitness
|
||||
# save params # already saved in pop_grey
|
||||
|
||||
return fitness_arr
|
||||
|
||||
def select(fitness_arr):
|
||||
sum_of_fitness = sum(fitness_arr)
|
||||
while len(pop_new) < SELECTION_SIZE:
|
||||
roulette_num = random.random()
|
||||
is_chosen = False
|
||||
while not is_chosen:
|
||||
cumulative_p = 0 # Track cumulative probability
|
||||
for i, fitness in enumerate(fitness_arr):
|
||||
cumulative_p += fitness / sum_of_fitness
|
||||
if roulette_num < cumulative_p:
|
||||
# Add the 32 Bit individual in grey code to pop_new
|
||||
pop_new.append(pop_grey[i])
|
||||
|
||||
# Calc new sum of fitness
|
||||
fitness_arr.pop(i)
|
||||
sum_of_fitness = sum(fitness_arr)
|
||||
|
||||
is_chosen = True # break while loop
|
||||
break # break for loop
|
||||
|
||||
def xover():
|
||||
# calc how many pairs are possible with pop_new
|
||||
individual_a = pop_new[0]
|
||||
individual_b = pop_new[1]
|
||||
|
||||
|
||||
# get first three pairs in pop_new
|
||||
# do the crossover
|
||||
|
||||
def main():
|
||||
pop_bin_values = generate_random_population(10)
|
||||
while fitness > 0.01:
|
||||
|
||||
# Evaluate fitness
|
||||
fitness_arr = eval_fitness(pop_bin_values)
|
||||
|
||||
# Selection
|
||||
select(fitness_arr) # Alters pop_new
|
||||
|
||||
# Crossover
|
||||
|
||||
# mutation
|
||||
|
||||
# pop_grey = pop_new
|
||||
return 0
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
def grey_to_bin(gray):
|
||||
"""Convert Gray code to binary, operating on the integer value directly"""
|
||||
num = int(gray, 2) # Convert string to integer
|
||||
mask = num
|
||||
while mask != 0:
|
||||
mask >>= 1
|
||||
num ^= mask
|
||||
return format(num, f'0{len(gray)}b') # Convert back to binary string with same length
|
||||
|
||||
def bin_to_grey(binary):
|
||||
"""Convert binary to Gray code using XOR with right shift"""
|
||||
num = int(binary, 2) # Convert string to integer
|
||||
gray = num ^ (num >> 1) # Gray code formula: G = B ^ (B >> 1)
|
||||
return format(gray, f'0{len(binary)}b') # Convert back to binary string with same length
|
||||
|
||||
def bin_to_param(binary, q_min = 0.0, q_max = 10.0):
|
||||
"""Convert binary string to float parameter in range [q_min, q_max]"""
|
||||
val = int(binary, 2) / 25.5 * 10 # conversion to 0.0 - 10.0 float
|
||||
# Scale to range [q_min, q_max]
|
||||
q = q_min + ((q_max - q_min) / (2**len(binary))) * val
|
||||
|
||||
return q
|
||||
Loading…
Reference in New Issue