-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimization.py
132 lines (108 loc) · 3.78 KB
/
optimization.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# https://mlrose.readthedocs.io/en/stable/source/tutorial1.html
import matplotlib.pyplot as plt
import mlrose_hiive as rose
import numpy as np
def queens_max(state):
# Initialize counter
fitness_cnt = 0
# For all pairs of queens
for i in range(len(state) - 1):
for j in range(i + 1, len(state)):
# Check for horizontal, diagonal-up and diagonal-down attacks
if (state[j] != state[i]) \
and (state[j] != state[i] + (j - i)) \
and (state[j] != state[i] - (j - i)):
# If no attacks, then increment counter
fitness_cnt += 1
return fitness_cnt
fitness_funcs = [
{
'name' : 'Queens',
'func' : rose.CustomFitness(queens_max),
'len' : 8,
'val' : 8
},
{
'name' : 'Peaks',
'func' : rose.ContinuousPeaks(),
'len' : 20,
'val' : 2
},
{
'name' : 'FF',
'func' : rose.FlipFlop(),
'len' : 50,
'val' : 2
},
]
problems = [rose.DiscreteOpt(length=x['len'], fitness_fn = x['func'], max_val=x['val']) for x in fitness_funcs]
algos = [
{
'name' : 'RHC',
'algo' : rose.random_hill_climb,
'kwargs' : {
'restarts' : 10,
}
},
{
'name' : 'GA',
'algo' : rose.genetic_alg,
'kwargs' : { }
},
{
'name' : 'SA',
'algo' : rose.simulated_annealing,
'kwargs' : { }
},
{
'name' : 'MIMIC',
'algo' : rose.mimic,
'kwargs' : { }
},
]
def get_filename(algo_name, fitness_name, suffix):
tail = [suffix] if suffix else []
return 'optimization_results/' + '_'.join([ fitness_name, algo_name, ] + tail) + '.txt'
def get_discrete_data(suffix=''):
results = [[x['algo'](problem, curve=True, random_state=12345, **x['kwargs']) for problem in problems] for x in algos]
for i, algo in enumerate(results):
for j, problem in enumerate(algo):
with open(get_filename(algos[i]['name'], fitness_funcs[j]['name'], suffix), 'w') as f:
np.savetxt(f, problem[0])
f.write(str(problem[1]) + '\n')
np.savetxt(f, problem[2])
def get_discrete_fitness(suffix=''):
for func in fitness_funcs:
for algo in algos:
with open(get_filename(algo['name'], func['name'], suffix), 'r') as f:
best_state = np.loadtxt(f, max_rows=func['len'])
best_fitness = float(f.readline())
fitness_curve = np.loadtxt(f)
plt.plot(fitness_curve[:,0], label=algo['name'])
tail = [suffix] if suffix else []
plt.xlabel('Number of Iterations')
plt.ylabel('Fitness')
plt.legend()
plt.savefig('optimization_results/' + '_'.join( [func['name']] + tail + ['fitness']) + '.png')
plt.clf()
def get_discrete_fitness_evals(suffix=''):
for func in fitness_funcs:
for algo in algos:
with open(get_filename(algo['name'], func['name'], suffix), 'r') as f:
best_state = np.loadtxt(f, max_rows=func['len'])
best_fitness = float(f.readline())
fitness_curve = np.loadtxt(f)
plt.plot(fitness_curve[:,1], label=algo['name'], alpha=0.7)
tail = [suffix] if suffix else []
plt.xlabel('Logarithmic Number of Iterations')
plt.ylabel('Logarithmic Number of Total Fitness Evaluations')
plt.yscale('log')
plt.xscale('log')
plt.legend()
plt.savefig('optimization_results/' + '_'.join( [func['name']] + tail + ['eval', 'count']) + '.png')
plt.clf()
if __name__ == '__main__':
suffix = ''
# get_discrete_data(suffix=suffix)
get_discrete_fitness(suffix=suffix)
get_discrete_fitness_evals(suffix=suffix)