-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdeepQlearn.py
190 lines (160 loc) · 7.13 KB
/
deepQlearn.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
'''###########################################
CS221 Final Project: Deep Q-Learning Implementation
Authors:
Kongphop Wongpattananukul ([email protected])
Pouya Rezazadeh Kalehbasti ([email protected])
Dong Hee Song ([email protected])
###########################################'''
import sys, math
import numpy as np
from collections import deque
import random
import copy
import gym
import keras
from keras.models import Sequential
from keras.layers import Dense
############################################################
class QLearningAlgorithm():
def __init__(self, actions, discount, weights, explorationProb=0.2, exploreProbDecay=0.99, explorationProbMin=0.01, batchSize=32):
self.actions = actions
self.discount = discount
self.explorationProb = explorationProb
self.exploreProbDecay = exploreProbDecay
self.explorationProbMin = explorationProbMin
self.weights = weights
self.numIters = 0
self.model = NeuralNetwork(batchSize, weights)
self.cache = deque(maxlen=1000000)
# This algorithm will produce an action given a state.
# Here we use the epsilon-greedy algorithm: with probability
# |explorationProb|, take a random action.
def getAction(self, state):
if np.random.rand() < self.explorationProb:
return random.choice(self.actions)
else:
predScores = self.model.predict(state)[0]
return np.argmax(predScores)
# We will call this function with (s, a, r, s'), which you should use to update |weights|.
# Note that if s is a terminal state, then s' will be None. Remember to check for this.
# You should update the weights using self.getStepSize(); use
# self.getQ() to compute the current estimate of the parameters.
def incorporateFeedback(self, states, actions, rewards, newStates, dones):
# initialize variable
states = np.squeeze(states)
newStates = np.squeeze(newStates)
X = states
y = self.model.predict(states)
# calculate gradient
targets = rewards + self.discount*(np.amax(self.model.predict(newStates), axis=1))*(1-dones)
ind = np.array([i for i in range(len(states))])
y[[ind], [actions]] = targets
# update weight
self.model.fit(X, y)
def updateCache(self, state, action, reward, newState, done):
self.cache.append((state, action, reward, newState, done))
# neural network
class NeuralNetwork():
def __init__(self, batchSize = 32, weights=None):
self.model = Sequential()
self.model.add(Dense(100, input_dim=8, activation='relu'))
self.model.add(Dense(100, activation='relu'))
self.model.add(Dense(4, activation='linear'))
adam = keras.optimizers.adam(lr=0.001)
self.model.compile(loss='mse', optimizer=adam)
if isinstance(weights, str):
self.model.load_weights(weights)
def predict(self, state):
return self.model.predict_on_batch(state)
def fit(self, X, y):
self.model.fit(X, y, epochs=1, verbose=0)
def save(self, weights):
self.model.save_weights(weights)
# Perform |numTrials| of the following:
# On each trial, take the MDP |mdp| and an RLAlgorithm |rl| and simulates the
# RL algorithm according to the dynamics of the MDP.
# Each trial will run for at most |maxIterations|.
# Return the list of rewards that we get for each trial.
def simulate(env, rl, numTrials=10, train=False, verbose=False,
trialDemoInterval=10, batchSize=32):
totalRewards = [] # The rewards we get on each trial
for trial in range(numTrials):
state = np.reshape(env.reset(), (1,8))
totalReward = 0
iteration = 0
while iteration <= 500:
# while True:
action = rl.getAction(state)
newState, reward, done, info = env.step(action)
newState = np.reshape(newState, (1,8))
# Appending the new results to the deque
rl.updateCache(state, action, reward, newState, done)
# update
totalReward += reward
state = newState
iteration += 1
if verbose == True and trial % trialDemoInterval == 0:
still_open = env.render()
if still_open == False: break
# Conducting memory replay
if len(rl.cache) < batchSize: # Waiting till memory size is larger than batch size
continue
else:
batch = random.sample(rl.cache, batchSize)
states = np.array([sample[0] for sample in batch])
actions = np.array([sample[1] for sample in batch])
rewards = np.array([sample[2] for sample in batch])
newStates = np.array([sample[3] for sample in batch])
dones = np.array([sample[4] for sample in batch])
if train:
rl.incorporateFeedback(states, actions, rewards, newStates,
dones)
rl.explorationProb = max(rl.exploreProbDecay * rl.explorationProb,
rl.explorationProbMin)
if done:
break
totalRewards.append(totalReward)
if verbose:
print(('Trial {} Total Reward: {}'.format(trial, totalReward)))
print(('Mean(last 10 total rewards): {}'.format(np.mean(totalRewards[-10:]))))
return totalRewards
## Main variables
# np.random.seed(0)
numEpochs = 300
numTrials = 1
numTestTrials = 1000
trialDemoInterval = numTrials/2
discountFactor = 0.99
explorProbInit = 1.0
exploreProbDecay = 0.999
explorationProbMin = 0.01
batchSize = 64
if __name__ == '__main__':
# Initiate weights
# Cold start weights
weights = None
# Warm start weights
# weights = 'weights.h5'
# TRAIN
print('\n++++++++++++ TRAINING +++++++++++++')
rl = QLearningAlgorithm([0, 1, 2, 3], discountFactor, weights,
explorProbInit, exploreProbDecay,
explorationProbMin, batchSize)
env = gym.make('LunarLander-v2')
# env.seed(0)
for i in range(numEpochs):
totalRewards = simulate(env, rl, numTrials=numTrials, train=True, verbose=False,
trialDemoInterval=trialDemoInterval, batchSize=batchSize)
print('Average Total Reward in Trial {}/{}: {}'.format(i, numEpochs, np.mean(totalRewards)))
env.close()
# Save Weights
rl.model.save('weights.h5')
# TEST
print('\n\n++++++++++++++ TESTING +++++++++++++++')
weights = 'weights.h5'
env = gym.make('LunarLander-v2')
env.seed(3)
rl = QLearningAlgorithm([0, 1, 2, 3], discountFactor, weights, 0.0, 0.0, 0.0, batchSize)
totalRewards = simulate(env, rl, numTrials=numTestTrials, train=False, verbose=False, trialDemoInterval=trialDemoInterval)
env.close()
print('Average Total Testing Reward: {}'.format(np.mean(totalRewards)))