Zaktualizuj 'genetic_route.py'
This commit is contained in:
parent
03efb3cdcf
commit
b6faed1ed2
@ -4,25 +4,25 @@ from math import floor
|
||||
import copy
|
||||
|
||||
num_of_surviving = 6
|
||||
num_of_couples = 12
|
||||
num_of_couples = 8
|
||||
mutation_probability = 0.07
|
||||
max_population = 20
|
||||
iterations = 50
|
||||
|
||||
|
||||
# creates new random solution to add to population
|
||||
def create_new_route(points):
|
||||
route = np.random.permutation(points)
|
||||
route = [x + 1 for x in route]
|
||||
return route
|
||||
|
||||
|
||||
# creates initian population
|
||||
def create_population(points):
|
||||
population = []
|
||||
for i in range(max_population):
|
||||
population.append(create_new_route(points))
|
||||
return population
|
||||
|
||||
|
||||
# gives score to a solution based on lenght
|
||||
def score_route(graph_map, route):
|
||||
score = graph_map[0][route[0]]
|
||||
for i in range(len(route) - 2):
|
||||
@ -31,7 +31,7 @@ def score_route(graph_map, route):
|
||||
score = score + graph_map[route[i + 1]][route[i + 2]]
|
||||
return score
|
||||
|
||||
|
||||
# scores every solution in population
|
||||
def score_all(graph_map, population):
|
||||
scores = []
|
||||
for i in range(len(population)):
|
||||
@ -39,7 +39,7 @@ def score_all(graph_map, population):
|
||||
scores.append(tmp)
|
||||
return scores
|
||||
|
||||
|
||||
# designed to create new population by mixing steps between most succesfull solutions
|
||||
def crossover(a, b):
|
||||
new_a = copy.deepcopy(a)
|
||||
new_b = copy.deepcopy(b)
|
||||
@ -53,10 +53,9 @@ def crossover(a, b):
|
||||
new_b[new_b.index(tmp_a)] = tmp_b
|
||||
new_a[rel] = tmp_b
|
||||
new_b[rel] = tmp_a
|
||||
|
||||
return new_a, new_b
|
||||
|
||||
|
||||
# adds randomness to newly created solutions
|
||||
def mutate(route):
|
||||
new_route = copy.deepcopy(route)
|
||||
for i in range(len(route) - 1):
|
||||
@ -66,7 +65,7 @@ def mutate(route):
|
||||
new_route[i + 1] = tmp
|
||||
return new_route
|
||||
|
||||
|
||||
# main function that iterate population until the best solutions emerge
|
||||
def genetic_trace_route(graph_map, packages):
|
||||
population = create_population(packages)
|
||||
for i in range(iterations):
|
||||
@ -91,13 +90,9 @@ def genetic_trace_route(graph_map, packages):
|
||||
population = copy.deepcopy(new_population)
|
||||
scores = score_all(graph_map, population)
|
||||
scores.sort(key=lambda x: x[1])
|
||||
print(population)
|
||||
print("Best route of all population in iteration " + i + 1)
|
||||
print(scores[0][1])
|
||||
|
||||
scores = score_all(graph_map, population)
|
||||
scores.sort(key=lambda x: x[1])
|
||||
print("best route lenght")
|
||||
print(scores[0][1])
|
||||
print("secand best route lenght")
|
||||
print(scores[1][1])
|
||||
return population[scores[0][0]]
|
||||
|
Loading…
Reference in New Issue
Block a user