Last active
October 6, 2017 23:14
-
-
Save pcallec/65fda3d2fd7e976bdc49562e3e3bb1c5 to your computer and use it in GitHub Desktop.
NSGA-II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #base from file from https://github.com/aarongarrett/inspyred/blob/master/examples/standard/nsga_example.py | |
| from random import Random | |
| from time import time | |
| import inspyred | |
| import csv | |
| prng=None | |
| display=True | |
| #Initializing seed with current time | |
| prng = Random() | |
| prng.seed(time()) | |
| problem = inspyred.benchmarks.Kursawe(3) | |
| ea = inspyred.ec.emo.NSGA2(prng) | |
| ea.variator = [inspyred.ec.variators.blend_crossover, | |
| inspyred.ec.variators.gaussian_mutation] | |
| ea.terminator = inspyred.ec.terminators.generation_termination | |
| final_pop = ea.evolve(generator=problem.generator, | |
| evaluator=problem.evaluator, | |
| pop_size=100, | |
| maximize=problem.maximize, | |
| bounder=problem.bounder, | |
| max_generations=100, | |
| crossover_rate = 1, | |
| mutation_rate=0.1) | |
| if display: | |
| final_arc = ea.archive | |
| print('Best Solutions: \n') | |
| #for f in final_arc: | |
| #print(f) | |
| import matplotlib.pyplot as plt | |
| x = [] | |
| y = [] | |
| for f in final_arc: | |
| x.append(f.fitness[0]) | |
| y.append(f.fitness[1]) | |
| plt.scatter(x, y, color='b') | |
| plt.xlabel("Function 1") | |
| plt.ylabel("Function 2") | |
| #Plot and save in pdf format | |
| plt.savefig('{0} Example ({1}).pdf'.format(ea.__class__.__name__, | |
| problem.__class__.__name__), | |
| format='pdf') | |
| plt.show() | |
| #Save Results in csv format | |
| fieldnames = ['x0', 'x1', 'x2','f1','f2'] | |
| listCandidate = [] | |
| for f in final_arc: | |
| listCandidate.append(f.candidate + f.fitness.values) | |
| my_list = [] | |
| for values in listCandidate: | |
| temp = zip(fieldnames, values) | |
| inner_dict = dict(temp) | |
| my_list.append(inner_dict) | |
| with open("Pareto_Optimal_Solutions.csv", "wb") as out_file: | |
| writer = csv.DictWriter(out_file, fieldnames=fieldnames) | |
| writer.writeheader() | |
| for row in my_list: | |
| writer.writerow(row) | |
| out_file.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment