-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcarracing_es.py
153 lines (112 loc) · 3.22 KB
/
carracing_es.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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# Trains the car racing problem using ES
import es
import nn
import comm
import matplotlib.pyplot as plt
import numpy as np
import gym
import multiprocessing as mp
import sys
env = gym.make('CarRacing-v0')
# plt.ion()
# define network architecture
x = i = nn.Input((2*96//8*96//8*3//3,))
x = nn.Dense(20)(x)
x = nn.Dense(3)(x)
net = nn.Model(i, x)
del x, i
# vectorized weights and original shape information
outw, outs = nn.get_vectorized_weights(net)
# run car racing problem
def fitness_car_race(w, render: bool=False, steps=1000):
score = 0
nn.set_vectorized_weights(net, w, outs)
n = 2
for _ in range(n):
# env._max_episode_steps = steps
obs = env.reset()
last_obs = np.array(obs) / 255.0
# net.clear()
# fitness
s = 0
while True:
close = False
if render:
close = not env.render()
# print(obs)
obs = obs / 255.0
# if render:
# plt.cla()
# plt.imshow(obs[::8,::8,1])
# plt.pause(0.00001)
# determine action
res = net.predict(np.expand_dims(np.concatenate([
last_obs[::8,::8,1].flatten(),
obs[::8,::8,1].flatten()
]), 0))[0]
res = res * 2 - 1
action = res #np.argmax(res)
last_obs = obs
obs, reward, done, _ = env.step(action)
s += reward
if done or close:
break
score += s
if render:
print(s)
env.close()
if close:
break
return score / n
if __name__ == "__main__":
# init ES
e = es.EvolutionStrategy(
outw,
1.0,
100,
10,
min_sigma=1e-3,
big_sigma=1e1,
wait_iter=5
)
# multiprocessing
pool = mp.Pool()
LENGTH = 1000
times = 0
best = -float('inf')
hist = open('car_es_hist.txt', 'w')
try:
for i in range(1000):
scores = []
pop = e.ask()
# eval population
for ind in pop:
scores.append(pool.apply_async(fitness_car_race, ((ind, False, LENGTH))))
thread_scores = scores
scores = []
ii = 0
for s in thread_scores:
scores.append(s.get())
ii += 1
print("{} / {}".format(ii, len(thread_scores)), end='\r')
e.tell(scores)
max_score = np.max(scores)
if max_score > best:
best = max_score
# log score info
print("Writing...", end='')
hist.write("{}, {} \n".format(
max_score,
np.mean(scores)
))
hist.flush()
ind = pop[np.argmax(scores)]
# save best individual
f = open('models/car_{:03d}.es'.format(i+1), 'wb')
out = comm.encode(ind)
f.write(out)
f.close()
print("Done")
fitness_car_race(ind, render=True)
finally:
pass