-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.py
67 lines (53 loc) · 1.66 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
59
60
61
62
63
64
65
66
67
"""
This module contains the agent classes.
"""
import numpy as np
from scipy.special import expit
from utils import np_seed
np.random.seed(np_seed)
class Agent:
"""
An agent in the environment.
=== Attributes ===
weights:
The weights used in the agent's linear model of the environment.
"""
weights: np.ndarray
def __init__(self, mean: float=0, std_dev: float=1) -> None:
"""
Initialize weights over Gaussian with <mean> and <std_dev>.
"""
self.weights = std_dev * np.random.randn(4) + mean
def get_action(self, obs: np.ndarray) -> int:
"""
Get the agent's next action, given an observation <obs>.
"""
if (np.dot(self.weights, obs)) >= 0:
return 1
else:
return 0
def init_weights(self, mean: float=0, std_dev: float=1) -> None:
"""
Re-initialize the weights of the agent over Gaussian with <mean> and <std_dev>.
"""
self.weights = std_dev * np.random.rand(4) + mean
def get_weights(self) -> np.ndarray:
"""
Get the agent weights.
"""
return self.weights
def set_weights(self, weights: np.ndarray) -> None:
"""
Set the agents weights to <weights>.
"""
self.weights = weights
class StochasticAgent(Agent):
"""
An agent with a stochastic policy in the environment.
"""
def get_action(self, obs: np.ndarray) -> int:
"""
Sample from the agent's distribution of actions, given an observation <obs>.
"""
prob = expit(np.dot(self.weights, obs))
return np.random.choice([0, 1], p=[1 - prob, prob])