-
Notifications
You must be signed in to change notification settings - Fork 0
/
flappy_bot.py
219 lines (183 loc) 路 7.81 KB
/
flappy_bot.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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import random
import numpy
import tensorflow as tf
from keras import backend as K
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import Adam
from PriorityTree import PriorityTree
from ple import PLE
from ple.games.flappybird import *
class FlappyBirdAgent:
def __init__(self, state_len, action_len):
self.state_len = state_len
self.action_len = action_len
self.gamma = 0.98
self.epsilon = 1.0
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.batch_size = 32
self.explored_states = PriorityTree(10000)
self.model = self.build_model()
self.target_model = self.build_model()
self.sync_target_model()
def huber_loss(self, target, prediction):
err = prediction - target
cond = K.abs(err) < 2.0
L2 = 0.5 * K.square(err)
L1 = 2.0 * (K.abs(err) - 0.5 * 2.0)
loss = tf.where(cond, L2, L1)
return K.mean(loss)
def build_model(self):
model = Sequential()
model.add(Dense(24, activation="relu", input_shape=(8,)))
model.add(Dense(24, activation="relu"))
model.add(Dense(2, activation="linear"))
model.compile(optimizer=Adam(lr=self.learning_rate), loss=self.huber_loss)
return model
def sync_target_model(self):
self.target_model.set_weights(self.model.get_weights())
def pick_action(self, state):
if numpy.random.rand() <= self.epsilon:
return random.randrange(2)
q_value = self.model.predict(state)
return numpy.argmax(q_value[0])
def append_sample(self, state, action, reward, next_state, game_over):
if self.epsilon == 1:
game_over = True
# Get TD-error and store it in brain
expected_state = self.model.predict([state])
old_reward = expected_state[0][action]
expected_state_val = self.target_model.predict([next_state])
if game_over:
expected_state[0][action] = reward
else:
expected_state[0][action] = reward + self.gamma * (numpy.amax(expected_state_val[0]))
error = abs(old_reward - expected_state[0][action])
self.add(error, (state, action, reward, next_state, game_over))
def sample(self, n):
batch = []
element = self.explored_states.total() / n
for i in range(n):
a = element * i
b = element * (i + 1)
s = random.uniform(a, b)
(index, priority, data) = self.explored_states.get_sample(s)
batch.append((index, data))
return batch
def priority(self, loss):
return (loss + 0.01) ** 0.9
def update(self, idx, error):
p = self.priority(error)
self.explored_states.update_priority(idx, p)
def add(self, error, sample):
p = self.priority(error)
self.explored_states.add(p, sample)
def replay(self):
if self.epsilon > 0.1:
self.epsilon *= self.epsilon_decay
# Random sample extraction from explored_states in batch size
mini_batch = self.sample(self.batch_size)
errors = numpy.zeros(self.batch_size)
states = numpy.zeros((self.batch_size, self.state_len))
next_states = numpy.zeros((self.batch_size, self.state_len))
actions, rewards, game_overs = [], [], []
for i in range(self.batch_size):
states[i] = mini_batch[i][1][0]
actions.append(mini_batch[i][1][1])
rewards.append(mini_batch[i][1][2])
next_states[i] = mini_batch[i][1][3]
game_overs.append(mini_batch[i][1][4])
expected_output = self.model.predict(states)
expected_output_val = self.target_model.predict(next_states)
# Update expected_output using Bellman optimal equations
for i in range(self.batch_size):
old_val = expected_output[i][actions[i]]
if game_overs[i]:
expected_output[i][actions[i]] = rewards[i]
else:
expected_output[i][actions[i]] = rewards[i] + 0.98 * (
numpy.amax(expected_output_val[i]))
errors[i] = abs(old_val - expected_output[i][actions[i]])
for i in range(self.batch_size):
sol = mini_batch[i][0]
self.explored_states.update_priority(sol, errors[i])
self.model.fit(states, expected_output, batch_size=self.batch_size, epochs=1, verbose=0)
def train(self, environment, game, agent_model_path='model_backup.h5'):
available_actions = [None, K_w]
epoch = 1
while True:
game_over = False
score = 0
environment.reset_game()
state = game.getGameState()
states = []
for key, value in state.items():
states.append(value)
state = numpy.reshape(numpy.array(states), [1, self.state_len])
while not game_over:
epoch += 1
action = self.pick_action(state)
reward = environment.act(available_actions[action])
states = []
for key, value in game.getGameState().items():
states.append(value)
next_state = numpy.array(states)
game_over = environment.game_over()
next_state = numpy.reshape(next_state, [1, self.state_len])
r = reward if not game_over else -10
self.append_sample(state, action, r, next_state, game_over)
if epoch >= 2500:
self.replay()
score += reward
state = next_state
if game_over:
self.sync_target_model()
print("epoch:", epoch, " score:", score, " eps:", self.epsilon)
if epoch % 20 == 0:
print(self.explored_states.total())
self.model.save("model_fb.h5")
self.model.save_weights("model_backup.h5")
print("saved")
def save_agent_experience(self, agent_model_path):
self.model.save(agent_model_path)
print("Saved Model")
def load_agent_experience(self, agent_weight_filepath):
self.model.load_weights(agent_weight_filepath)
self.sync_target_model()
print("Model Loaded")
return self.model
def play(self, environment, game):
score = 0
available_actions = [None, K_w]
environment.reset_game()
while not environment.game_over():
current_state = numpy.array([current_state_attribute
for current_state_attribute in game.getGameState().values()])
current_state = numpy.reshape(current_state, (1, 8))
action_index = numpy.asscalar(numpy.argmax(self.model.predict(current_state)))
action = available_actions[action_index]
reward = environment.act(action)
score += reward
print(f'Current score: {score}')
def play_flappy_bird(play_game=True, train_agent=True, agent_model_path='model.h5'):
game = FlappyBird()
environment = PLE(game, fps=30, display_screen=True)
action_len = 2
states = []
for key, value in game.getGameState().items():
states.append(value)
print(states)
state_len = len(states)
agent_explored_states = FlappyBirdAgent(state_len, action_len)
if os.path.exists(agent_model_path):
agent_explored_states.load_agent_experience(agent_model_path)
# environment.init()
if train_agent:
agent_explored_states.train(environment, game)
print("Trained")
if play_game:
agent_explored_states.play(environment, game)
print("Played")
agent_explored_states.save_agent_experience(agent_model_path)
play_flappy_bird(play_game=True, train_agent=True)