Run example instance
- Save results to csv - Generate csv attributes
This commit is contained in:
parent
597f289e81
commit
0ff13b8e2f
14
src/file.py
14
src/file.py
|
@ -2,5 +2,15 @@ import csv
|
|||
|
||||
|
||||
class File(object):
|
||||
def __init__(self, filename):
|
||||
pass
|
||||
def __init__(self, filename, header):
|
||||
self.file = open(filename, 'w')
|
||||
self.writer = csv.DictWriter(self.file, fieldnames=header)
|
||||
|
||||
def write_header(self):
|
||||
self.writer.writeheader()
|
||||
|
||||
def write_row(self, row):
|
||||
self.writer.writerow(row)
|
||||
|
||||
def close(self):
|
||||
self.file.close()
|
||||
|
|
|
@ -12,15 +12,14 @@ class Lifecycle(object):
|
|||
|
||||
def start(self):
|
||||
for epoch in range(0, self.params["iter"]):
|
||||
elite = round(self.params["elite"] * self.params["population_size"])
|
||||
crossover = round((self.params["crossover"]
|
||||
* self.params["population_size"]) / 2)
|
||||
elite = self.params["elite"]
|
||||
crossover = self.params["crossover"]
|
||||
self.population.advance_generation(elite, crossover)
|
||||
self.best_fit.append(self.population.best_fitness())
|
||||
self.average_fit.append(self.population.avg_fitness())
|
||||
|
||||
def best_member(self):
|
||||
return self.population.best_member()
|
||||
def best_fitness(self):
|
||||
return self.population.best_fitness()
|
||||
|
||||
def generate_graph(self, show=False, location=None):
|
||||
plt.plot(self.best_fit)
|
||||
|
@ -30,3 +29,8 @@ class Lifecycle(object):
|
|||
plt.show()
|
||||
if location is not None:
|
||||
plt.savefig(location)
|
||||
|
||||
def get_csv(self):
|
||||
id = {'id': self.id}
|
||||
best_fitness = {'best_fit': self.best_fitness()}
|
||||
return {**id, **best_fitness, **self.params}
|
||||
|
|
19
src/main.py
19
src/main.py
|
@ -1,16 +1,27 @@
|
|||
import os
|
||||
from lifecycle import Lifecycle
|
||||
from file import File
|
||||
|
||||
param_example = {'population_size': 10,
|
||||
'elite': round(0.1 * 10),
|
||||
'crossover': round(0.6 * 10),
|
||||
'iter': 1000}
|
||||
|
||||
|
||||
def cls():
|
||||
os.system('cls' if os.name == 'nt' else 'clear')
|
||||
|
||||
|
||||
ga = Lifecycle(1, {'population_size': 10,
|
||||
'elite': 0.1,
|
||||
'crossover': 0.6,
|
||||
'iter': 1000})
|
||||
output_file = File("output.csv", ['id', 'best_fit'] + list(param_example))
|
||||
|
||||
ga = Lifecycle(1, param_example)
|
||||
|
||||
ga.start()
|
||||
|
||||
output_file.write_header()
|
||||
|
||||
output_file.write_row(ga.get_csv())
|
||||
|
||||
output_file.close()
|
||||
|
||||
ga.generate_graph(show=True)
|
||||
|
|
|
@ -92,7 +92,7 @@ class Population(object):
|
|||
|
||||
self.members = new_generation
|
||||
|
||||
self.mutate(20)
|
||||
self.mutate(10)
|
||||
|
||||
def remove_member(self, member):
|
||||
self.members.remove(member)
|
||||
|
|
Loading…
Reference in New Issue
Block a user