-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexam_nsga2.py
54 lines (40 loc) · 1.97 KB
/
exam_nsga2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
# Created by "Thieu" at 15:34, 13/12/2024 ----------%
# Email: nguyenthieu2102@gmail.com %
# Github: https://github.com/thieu1995 %
# --------------------------------------------------%
import numpy as np
from metamoo import Problem, FloatVar
from metamoo import NSGA2, OnePointCrossover, GaussianFlipMutator
from metamoo import ScatterPlot
def objective_function1(X):
return np.sum(X ** 2)
def objective_function2(X):
return np.sum((X - 1) ** 2 - np.abs(X))
def objective_function3(X):
return np.sum(np.sin(X) + X**2 - 5*X)
def run_model():
# Create a multi-objective problem
problem = Problem(
objectives=[objective_function1, objective_function2, objective_function3],
bounds=FloatVar(lb=(-1.,) * 15, ub=(1.,) * 15)
)
SEED = 10
# Initialize the NSGA-II algorithm
model = NSGA2(epoch=100, pop_size=50,
crossover=OnePointCrossover(crossover_rate=0.9, seed=SEED),
mutator=GaussianFlipMutator(kind="single", mutation_rate=0.1, loc=0, scale=1, seed=SEED),
seed=SEED)
# Run the evolution process to optimize the objectives
model.solve(problem)
## Plot the resulting Pareto front
plotter = ScatterPlot(fig_size=(10, 6), style=None, title="Pareto front - Scatter",
show_plot=True, save_file_path=None, file_exts=(".png", ".pdf"),
grid=True, view_angle=(30, 30), legend_name='Pareto Front')
# Plot 2D for best pareto front found
plotter.plot(model.fronts_sorted[0], objectives=[1, 2], xyz_labels=None, c="r", marker="o")
# Plot 3D for best pareto front found
plotter.plot(model.fronts_sorted[0], objectives=[1, 2, 3], xyz_labels=["obj 1", "obj 2", "obj 3"])
# Run the example
if __name__ == "__main__":
run_model()