-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.py
executable file
·49 lines (39 loc) · 1.31 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
import numpy as np
class Agent:
def __init__(self, env):
self.env = env
def sample(self, horizon, policy):
"""
Sample a rollout from the agent.
Arguments:
horizon (int): the length of the rollout
policy: the policy that the agent will use for actions
"""
rewards = []
states, actions, reward_sum, done = [self.env.reset()], [], 0, False
policy.reset()
for t in range(horizon):
print('time step: {}/{}'.format(t + 1, horizon), end='\r',
flush=True)
actions.append(policy.act(states[t], t))
state, reward, done, info = self.env.step(actions[t])
states.append(state)
reward_sum += reward
rewards.append(reward)
if done:
# print(info['done'])
break
# print("Rollout length: ", len(actions))
return {
"obs": np.array(states),
"ac": np.array(actions),
"reward_sum": reward_sum,
"rewards": np.array(rewards),
}
class RandomPolicy:
def __init__(self, action_dim):
self.action_dim = action_dim
def reset(self):
pass
def act(self, arg1, arg2):
return np.random.uniform(size=self.action_dim) * 2 - 1