-
Notifications
You must be signed in to change notification settings - Fork 0
/
DDQN.py
220 lines (187 loc) · 9.16 KB
/
DDQN.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
220
import numpy as np
import math
import pandas as pd
from config import Config
import os
import tensorflow as tf
from tensorflow.compat.v1 import placeholder, variable_scope, GraphKeys, get_variable, squared_difference, Session, get_collection, assign, global_variables_initializer, train
from collections import deque
from tensorflow.keras import models, layers, optimizers
from agent import Agent
conf = Config()
# refernce from https://github.com/MorvanZhou
class AgentsDDQN(Agent):
def __init__(self, id, N):
self.id = id
self.path = "./model/DDQN/" + str(N) + "/" + str(id)
self.state = []
self.next_state = []
self.has_model = os.path.exists(self.path)
# learning rate
if self.has_model:
self.greedy = 0.0001
self.epsilon = 0.8
else:
# exploration strategy
self.greedy = 0.001
self.epsilon = 0.5
# discount factor
self.gamma = 0.9
# number of features
self.features = 7
# number of actions
self.actions = 16
self.replace_target_iter = 1000
self.memory_size = 50000
self.epsilon_max = 0.9
self.epsilon_increment = 0.001
self.step_counter = 0
self.memory = np.zeros((self.memory_size, self.features*2+2))
self.build_network()
self.sess = Session()
self.batch_size = 64
# tf.summary.FileWriter("logs/", self.sess.graph)
print(self.id, self.sess)
self.saver = train.Saver()
if not(os.path.exists(self.path)):
self.sess.run(global_variables_initializer())
else:
self.load_model()
self.cost_history = []
def set_state(self, state):
self.state = state
# try to give up get_state in DQN, just use original state
def build_network(self):
tf.compat.v1.disable_eager_execution()
# evaluate network
self.s_eval = placeholder(tf.float32, [None, self.features], name='s')
self.q_target = placeholder(tf.float32, [None, self.actions], name='Q_target')
with variable_scope('eval_net' + str(self.id)) as scope:
#scope.reuse_variables()
c_names = ['eval_net_params' + str(self.id), GraphKeys.GLOBAL_VARIABLES]
n_l1 = 100
w_init = tf.random_normal_initializer(0.01)
b_init = tf.constant_initializer(0.01)
# first layer. collections is used later when assign to target net
with variable_scope('l1'):
w1 = get_variable('w1', [self.features, n_l1], initializer=w_init, collections=c_names)
b1 = get_variable('b1', [1, n_l1], initializer=b_init, collections=c_names)
l1 = tf.nn.relu(tf.matmul(self.s_eval, w1) + b1)
# second layer. collections is used later when assign to target net
with variable_scope('l2'):
w2 = get_variable('w2', [n_l1, self.actions], initializer=w_init, collections=c_names)
b2 = get_variable('b2', [1, self.actions], initializer=b_init, collections=c_names)
self.q_eval = tf.matmul(l1, w2) + b2
with variable_scope('loss'):
self.loss = tf.reduce_mean(tf.math.squared_difference(self.q_target, self.q_eval))
with variable_scope('train'):
#self._train_op = tf.compat.v1.train.RMSPropOptimizer(self.alpha).minimize(self.loss)
self._train_op = tf.compat.v1.train.AdagradOptimizer(self.greedy).minimize(self.loss)
# target network
self.s_target = placeholder(tf.float32, [None, self.features], name='s_') # input
with variable_scope('target_net' + str(self.id)):
# c_names(collections_names) are the collections to store variables
c_names = ['target_net_params' + str(self.id), GraphKeys.GLOBAL_VARIABLES]
# first layer. collections is used later when assign to target net
with variable_scope('l1'):
w1 = get_variable('w1', [self.features, n_l1], initializer=w_init, collections=c_names)
b1 = get_variable('b1', [1, n_l1], initializer=b_init, collections=c_names)
l1 = tf.nn.relu(tf.matmul(self.s_target, w1) + b1)
# second layer. collections is used later when assign to target net
with variable_scope('l2'):
w2 = get_variable('w2', [n_l1, self.actions], initializer=w_init, collections=c_names)
b2 = get_variable('b2', [1, self.actions], initializer=b_init, collections=c_names)
self.q_next = tf.matmul(l1, w2) + b2
def store_transition(self, action, reward, state_new):
if not hasattr(self, 'memory_counter'):
self.memory_counter = 0
action_number = action[0] - 1 + action[1] * 8
transition = np.hstack((self.state, [action_number, reward], state_new))
index = self.memory_counter % self.memory_size
self.memory[index, :] = transition
self.memory_counter += 1
self.state = state_new
def make_decision(self, no_random = False):
# observation = observation[np.newaxis, :]
observation = np.array(self.state).reshape([1, self.features])
actions_value = self.sess.run(self.q_eval, feed_dict={self.s_eval: observation})
action = np.argmax(actions_value[0][:])
action_0 = action % 8 + 1
action_1 = math.floor(action / 8)
if not hasattr(self, 'q'): # 记录选的 Qmax 值
self.q = []
self.running_q = 0
self.running_q = self.running_q*0.99 + 0.01 * np.max(actions_value)
self.q.append(self.running_q)
if np.random.uniform() > self.epsilon and not(no_random):
return self.make_random_decision()
return [action_0, action_1]
def make_random_decision(self):
action_0 = np.random.randint(1, 9)
action_1 = np.random.randint(0, 2)
return [action_0, action_1]
def replace_target_params(self):
t_params = get_collection('target_net_params' + str(self.id))
e_params = get_collection('eval_net_params' + str(self.id))
self.sess.run([assign(t, e) for t, e in zip(t_params, e_params)])
def update(self):
# check to replace target parameters
if self.step_counter % self.replace_target_iter == 0:
self.replace_target_params()
print('\ntarget_params_replaced\n')
# sample batch memory from all memory
if self.memory_counter > self.memory_size:
sample_index = np.random.choice(self.memory_size, size=self.batch_size)
else:
sample_index = np.random.choice(self.memory_counter, size=self.batch_size)
batch_memory = self.memory[sample_index, :]
q_next, q_eval_for_next = self.sess.run(
[self.q_next, self.q_eval],
feed_dict={
self.s_target: batch_memory[:, -self.features:], # next observation
self.s_eval: batch_memory[:, -self.features:] # next observation
})
q_eval = self.sess.run(self.q_eval, {self.s_eval: batch_memory[:, :self.features]})
# change q_target w.r.t q_eval's action
q_target = q_eval.copy()
batch_index = np.arange(self.batch_size, dtype=np.int32)
eval_act_index = batch_memory[:, self.features].astype(int)
reward = batch_memory[:, self.features + 1]
q_target[batch_index, eval_act_index] = reward + self.gamma * np.max(q_next, axis=1)
max_act_for_next = np.argmax(q_eval_for_next, axis=1) # q_eval 得出的最高奖励动作
selected_q_next = q_next[batch_index, max_act_for_next] # Double DQN 选择 q_next 依据 q_eval 选出的动作
q_target[batch_index, eval_act_index] = reward + self.gamma * selected_q_next
# train eval network
_, self.cost = self.sess.run([self._train_op, self.loss],
feed_dict={self.s_eval: batch_memory[:, :self.features],
self.q_target: q_target})
self.cost_history.append(self.cost)
# increasing epsilon
self.epsilon = self.epsilon + self.epsilon_increment if self.epsilon < self.epsilon_max else self.epsilon_max
self.step_counter += 1
def plot_cost(self):
import matplotlib.pyplot as plt
plt.plot(np.arange(len(self.cost_history)), self.cost_history)
plt.ylabel('Cost')
plt.xlabel('training steps')
plt.show()
def update_greedy(self):
self.greedy *= 0.95
def load_model(self):
self.saver.restore(self.sess, self.path)
def plot_qvalue(self):
import matplotlib.pyplot as plt
plt.plot(np.array(self.q), label=self.id)
plt.ylabel('Q eval')
plt.xlabel('training steps')
plt.grid()
plt.show()
def save_model(self, if_plot=False, postfix=''):
try:
self.saver.save(self.sess, self.path+postfix)
print(self.path+postfix + ' saved successfully')
np.save(self.path + postfix +".npy", self.memory)
if if_plot:
self.plot_cost()
except:
print('ERROR: can not save the model')