-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq_learning_agent_greedy.py
156 lines (117 loc) · 4.94 KB
/
q_learning_agent_greedy.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
import os
import random
import numpy as np
class QLearningAgentGreedy:
def __init__(self, is_training):
self.training = is_training
self.episode = 0
self.discount_factor = 0.95
self.learning_rate = 0.7
self.previous_state = [96, 47, 0]
self.previous_action = 0
self.epsilon = 0.1
self.final_epsilon = 0.0
self.epsilon_decay = 0.00001
self.moves = []
self.scores = []
self.max_score = 0
self.x_dimension = 130
self.y_dimension = 130
self.v_dimension = 20
self.q_values = np.zeros((self.x_dimension, self.y_dimension, self.v_dimension, 2))
self.initialize_model()
def initialize_model(self):
if os.path.exists("model_greedy.txt"):
q_file = open("model_greedy.txt", "r")
line = q_file.readline()
if self.training:
[self.episode, self.epsilon] = [int(line.split(',')[0]), float(line.split(',')[1])]
line = q_file.readline()
while len(line) != 0:
state = line.split(',')
self.q_values[int(state[0]), int(state[1]), int(state[2]), int(state[3])] = float(state[4])
line = q_file.readline()
q_file.close()
def action(self, x_distance, y_distance, velocity):
"""
The action stores the transition from the previous state to the
current state. That transition is the action that led from the
previous to the current.
"""
if self.training:
state = [x_distance, y_distance, velocity]
self.moves.append([self.previous_state, self.previous_action, state, 0])
self.previous_state = state
# Get an action epsilon greedy policy.
if random.random() <= self.epsilon:
self.previous_action = random.randrange(2)
elif self.q_values[x_distance, y_distance, velocity][0] >= self.q_values[x_distance, y_distance, velocity][1]:
self.previous_action = 0
else:
self.previous_action = 1
else:
if self.q_values[x_distance, y_distance, velocity][0] >= self.q_values[x_distance, y_distance, velocity][1]:
self.previous_action = 0
else:
self.previous_action = 1
return self.previous_action
def record_reward(self, reward):
self.moves[-1][3] = reward
def update_q_values(self, score):
self.episode += 1
self.max_score = max(self.max_score, score)
print("Episode: " + str(self.episode) +
" Epsilon: " + str(self.epsilon) +
" Score: " + str(score) +
" Max Score: " + str(self.max_score))
self.scores.append(score)
if self.training:
history = list(reversed(self.moves))
first = True
second = True
jump = True
if history[0][1] < 69:
jump = False
for move in history:
[x, y, v] = move[0]
action = move[1]
[x1, y1, z1] = move[2]
reward = move[3]
# Penalize the last two states before a collision.
if first or second:
reward = -1
if first:
first = False
else:
second = False
# Penalize the last jump before a collision.
if jump and action:
reward = -1
jump = False
self.q_values[x, y, v, action] = (1 - self.learning_rate) * \
(self.q_values[x, y, v, action]) + self.learning_rate * \
(reward + self.discount_factor *
max(self.q_values[x1, y1, z1, 0],
self.q_values[x1, y1, z1, 1]))
self.moves = []
# Decay epsilon linearly.
if self.epsilon > self.final_epsilon:
self.epsilon -= self.epsilon_decay
def save_model(self):
data = str(self.episode) + "," + str(self.epsilon) + "\n"
for x in range(self.x_dimension):
for y in range(self.y_dimension):
for v in range(self.v_dimension):
for a in range(2):
data += str(x) + ", " + str(y) + \
", " + str(v) + \
", " + str(a) + ", " + str(self.q_values[x, y, v, a]) + "\n"
q_file = open("model_greedy.txt", "w")
q_file.write(data)
q_file.close()
data1 = ''
for i in range(len(self.scores)):
data1 += str(self.scores[i]) + "\n"
s_file = open("model_scores_greedy.txt", "a+")
s_file.write(data1)
s_file.close()