viberl.agents.reinforce
REINFORCE: Monte-Carlo policy gradient method for reinforcement learning.
Algorithm Overview:
REINFORCE is a policy gradient method that uses complete episode returns to update the policy parameters. It directly optimizes the policy without requiring a value function, making it conceptually simple but potentially high-variance.
Key Concepts:
- Policy Gradient: Directly optimizes policy parameters \(\theta\) to maximize expected return
- Likelihood Ratio Trick: Uses \(\nabla_\theta \log \pi_\theta(a|s)\) for gradient computation
- Monte-Carlo Returns: Uses complete episode returns \(G_t\) for unbiased estimates
- High Variance: Large variance in gradient estimates but unbiased
- Episode-based Learning: Requires complete episodes before parameter updates
Mathematical Foundation:
Optimization Objective:
Return Calculation:
Reference: Williams, R.J. Simple statistical gradient-following algorithms for connectionist reinforcement learning. Machine Learning 8, 229-256 (1992). PDF
Classes:
Name | Description |
---|---|
REINFORCEAgent |
REINFORCE agent implementation with policy gradient optimization. |
REINFORCEAgent
REINFORCEAgent(
state_size: int,
action_size: int,
learning_rate: float = 0.001,
gamma: float = 0.99,
hidden_size: int = 128,
num_hidden_layers: int = 2,
)
Bases: Agent
REINFORCE agent implementation with policy gradient optimization.
This agent implements the REINFORCE algorithm using a policy network to directly optimize the policy parameters via Monte-Carlo gradient estimates.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state_size
|
int
|
Dimension of the state space. Must be positive. |
required |
action_size
|
int
|
Number of possible actions. Must be positive. |
required |
learning_rate
|
float
|
Learning rate for the Adam optimizer. Must be positive. |
0.001
|
gamma
|
float
|
Discount factor for future rewards. Should be in (0, 1]. |
0.99
|
hidden_size
|
int
|
Number of neurons in each hidden layer. Must be positive. |
128
|
num_hidden_layers
|
int
|
Number of hidden layers. Must be non-negative. |
2
|
Raises:
Type | Description |
---|---|
ValueError
|
If any parameter is invalid (e.g., negative dimensions). |
Initialize the REINFORCE agent.
Methods:
Name | Description |
---|---|
act |
Select action using the current policy. |
learn |
Update policy parameters using the REINFORCE gradient algorithm. |
save |
Save the agent's policy network parameters to a file. |
load |
Load the agent's policy network parameters from a file. |
Attributes:
Name | Type | Description |
---|---|---|
gamma |
|
|
policy_network |
|
|
optimizer |
|
Source code in viberl/agents/reinforce.py
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 |
|
gamma
instance-attribute
gamma = gamma
policy_network
instance-attribute
policy_network = PolicyNetwork(state_size, action_size, hidden_size, num_hidden_layers)
optimizer
instance-attribute
optimizer = Adam(parameters(), lr=learning_rate)
act
act(state: ndarray, training: bool = True) -> Action
Select action using the current policy.
Uses the policy network to compute action probabilities and selects an action based on the current mode (training vs evaluation).
In training mode, samples from the policy distribution to ensure exploration. In evaluation mode, selects the most probable action (greedy selection).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state
|
ndarray
|
Current state observation as a numpy array. Should have shape (state_size,) or be convertible to a tensor of that shape. |
required |
training
|
bool
|
Whether in training mode. If True, samples from the policy distribution for exploration. If False, selects the action with highest probability (greedy selection). |
True
|
Returns:
Type | Description |
---|---|
Action
|
Action containing the selected action index as an integer. |
Raises:
Type | Description |
---|---|
ValueError
|
If the state has incorrect shape or type. |
RuntimeError
|
If there's an error during action computation. |
Source code in viberl/agents/reinforce.py
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 |
|
learn
learn(trajectories: list[Trajectory]) -> dict[str, float]
Update policy parameters using the REINFORCE gradient algorithm.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
trajectories
|
list[Trajectory]
|
List of trajectories to learn from |
required |
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary containing training metrics: |
dict[str, float]
|
|
dict[str, float]
|
|
dict[str, float]
|
|
Raises:
Type | Description |
---|---|
ValueError
|
If no trajectories are provided or contains invalid data. |
RuntimeError
|
If there's an error during gradient computation. |
Source code in viberl/agents/reinforce.py
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 |
|
save
save(filepath: str) -> None
Save the agent's policy network parameters to a file.
Saves the complete state of the policy network, including all parameters and buffers. The saved file can be loaded later to restore the exact same policy.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
str
|
Path where to save the model. Should include the .pth extension. The directory will be created if it doesn't exist. |
required |
Raises:
Type | Description |
---|---|
IOError
|
If there's an error writing to the file. |
ValueError
|
If filepath is empty or invalid. |
Example
agent.save('models/reinforce_policy.pth')
Later: agent.load('models/reinforce_policy.pth')
Source code in viberl/agents/reinforce.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 |
|
load
load(filepath: str) -> None
Load the agent's policy network parameters from a file.
Loads previously saved policy network parameters from disk. Can be used to restore an agent to a previously saved state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filepath
|
str
|
Path from which to load the model. Should point to a .pth file created by the save() method. |
required |
Raises:
Type | Description |
---|---|
IOError
|
If the file doesn't exist or can't be read. |
ValueError
|
If filepath is empty or the file contains invalid data. |
RuntimeError
|
If there's a mismatch between saved and current network architecture. |
Example
agent.load('models/reinforce_policy.pth')
Agent is now restored to the saved state
Source code in viberl/agents/reinforce.py
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 |
|