new selections need to set a time limit

This commit is contained in:
2019-10-24 10:03:18 +02:00
parent b1f0bab9a7
commit 132cec2445
4 changed files with 54 additions and 25 deletions

View File

@@ -1,28 +1,54 @@
import numpy as np
import random
from brain import Neural_Network
from params import MUTATION_RATE
from params import MUTATION_RATE, SELECTION_ALG, KWAY_TOURNAMENT_PLAYERS
def kway_selection(brains, exclude=None):
tourn_pool = []
best_play = None
if exclude :
brains = [x for x in brains if x != exclude]
for x in range(KWAY_TOURNAMENT_PLAYERS):
new_play = random.choice(brains)
while new_play in tourn_pool :
new_play = random.choice(brains)
if not best_play or best_play.fitness < new_play.fitness :
best_play = new_play
return best_play
def genetic_selection(brains):
# tot_fitness = sum ([int(b.fitness) for b in brains])
# does not seem very optimized... TBR
# constitute a list where every brain is represented
# proportionnally to its relative fitness
wheel = []
for b in brains :
wheel += [b] * b.fitness
tot_fitness = len(wheel)
parents_pool = []
half_pop = int(len(brains)/2)
# selection of pool/2 pair of parents to reproduce
parents_pool = []
for _ in range(half_pop):
parents_pool.append([
wheel[round(random.random()*tot_fitness)],
wheel[round(random.random()*tot_fitness)]
if SELECTION_ALG == "kway":
for x in range(half_pop) :
p1 = kway_selection(brains)
p2 = kway_selection(brains, exclude=p1)
parents_pool.append([
p1,
p2
])
elif SELECTION_ALG == "roulette" :
# does not seem very optimized... TBR
# constitute a list where every brain is represented
# proportionnally to its relative fitness
wheel = []
for b in brains :
wheel += [b] * b.fitness
tot_fitness = len(wheel)
# selection of pool/2 pair of parents to reproduce
for _ in range(half_pop):
idx1 = round(random.random()*tot_fitness - 1)
idx2 = round(random.random()*tot_fitness - 1)
parents_pool.append([
wheel[idx1],
wheel[idx2]
])
return parents_pool