-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAgent.py
58 lines (49 loc) · 1.88 KB
/
Agent.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
import numpy as np
from collections import defaultdict
class Agent:
def update_Q(self, Qsa, Qsa_next, reward):
return Qsa + (self.alpha * (reward + (self.gamma * Qsa_next) - Qsa))
def epsilon_greedy_probs(self, Q_s, i_episode, eps=None):
epsilon = 1.0 / i_episode
if eps is not None:
epsilon = eps
policy_s = np.ones(self.nA) * epsilon / self.nA
policy_s[np.argmax(Q_s)] = 1 - epsilon + (epsilon / self.nA)
return policy_s
def __init__(self, nA=6):
""" Initialize agent.
Params
======
- nA: number of actions available to the agent
"""
self.nA = nA
self.Q = defaultdict(lambda: np.zeros(self.nA))
self.epsilon = 0.005
self.alpha = 0.3
self.gamma = 1.0
self.policy_s = None
self.i_episode = 1
def select_action(self,state):
""" Given the state, select an action.
Params
======
- state: the current state of the environment
Returns
=======
- action: an integer, compatible with the task's action space
"""
self.policy_s = self.epsilon_greedy_probs(self.Q[state],self.i_episode)
self.i_episode += 1
return np.random.choice(np.arange(self.nA),p = self.policy_s)
def step(self, state, action, reward, next_state, done):
""" Update the agent's knowledge, using the most recently sampled tuple.
Params
======
- state: the previous state of the environment
- action: the agent's previous choice of action
- reward: last reward received
- next_state: the current state of the environment
- done: whether the episode is complete (True or False)
"""
self.Q[state][action] = self.update_Q(self.Q[state][action],np.max(self.Q[next_state]),\
reward)