Algorithm API
Dynamic programming
gym_classics2.algorithms.dynamic_programming
This file implements dynamic programming algorithms for solving Markov Decision Processes (MDPs) in gym-classics environments with model access. The algorithms include value iteration and policy iteration, which are fundamental methods in reinforcement learning for computing optimal policies and value functions.
backup
Computes the Bellman backup for a given state and action.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A gym-classics environment with model access. |
required | |
discount
|
The discount factor. |
required | |
V
|
The current value function. |
required | |
state
|
The current state. |
required | |
action
|
The action to evaluate. |
required |
Returns: The computed Q-value for the given state and action.
Source code in gym_classics2/algorithms/dynamic_programming.py
value_iteration
Performs value iteration for the given environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A gym-classics environment with model access. |
required | |
discount
|
The discount factor (0 <= discount <= 1). |
required | |
precision
|
The precision for convergence (default: 1e-3). |
0.001
|
|
history
|
If True, returns a list of intermediate value functions. |
False
|
|
verbose
|
If True, prints progress information. |
False
|
Returns:
| Type | Description |
|---|---|
|
The optimal value function V. If history is True, returns a list of intermediate value functions. |
Source code in gym_classics2/algorithms/dynamic_programming.py
policy_evaluation
Evaluates a given policy to compute its value function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A gym-classics environment with model access. |
required | |
discount
|
The discount factor (0 <= discount <= 1). |
required | |
policy
|
The policy to evaluate. |
required | |
precision
|
The precision for convergence (default: 1e-3). |
0.001
|
|
max_backups
|
Maximum number of backups to perform to prevent infinite loops (default: 1000). |
1000
|
Returns:
| Type | Description |
|---|---|
|
The value function for the given policy. |
Source code in gym_classics2/algorithms/dynamic_programming.py
policy_improvement
Improves the policy based on the given value function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A gym-classics environment with model access. |
required | |
discount
|
The discount factor (0 <= discount <= 1). |
required | |
policy
|
The current policy to improve. |
required | |
V_policy
|
The value function of the current policy. |
required | |
precision
|
The precision for determining stability (default: 1e-3). |
0.001
|
Returns:
| Type | Description |
|---|---|
|
A tuple (improved_policy, stable) where stable is True if the policy did not change. |
Source code in gym_classics2/algorithms/dynamic_programming.py
policy_iteration
policy_iteration(env, discount, precision=0.001, max_backups=1000, history=False, verbose=False, rng=None)
Performs policy iteration for the given environment.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A gym-classics environment with model access. |
required | |
discount
|
The discount factor (0 <= discount <= 1). |
required | |
precision
|
The precision for convergence (default: 1e-3). |
0.001
|
|
max_backups
|
Maximum number of iterations used in policy evaluation. Note: this prevents an infinite loop for policies that do not reach a terminal state. |
1000
|
|
history
|
If True, returns lists of intermediate policies and value functions. |
False
|
|
verbose
|
If True, prints progress information. |
False
|
|
rng
|
NumPy generator or integer seed used to initialize the policy. |
None
|
Returns:
| Type | Description |
|---|---|
|
The optimal policy. If history is True, returns a tuple (policy_list, V_list) containing lists of intermediate policies and value functions. |
Source code in gym_classics2/algorithms/dynamic_programming.py
Policy helpers
gym_classics2.algorithms.policy
This file implements different policy representations and functions for working with policies in gym-classics environments. It includes functions for creating random policies, encoding policies for display, and computing greedy policies based
make_multidiscrete_policy
Converts a tabular policy vector to a multi-discrete tabular policy stored in a dictionary that can be used for sample.
Source code in gym_classics2/algorithms/policy.py
random_policy
Create a random policy for the given environment.
The policy is represented as a numpy array where each entry corresponds to an action for a state.
rng may be a NumPy generator or an integer seed.
Source code in gym_classics2/algorithms/policy.py
encode_policy
Encode a policy for display. The policy is represented as a numpy array where each entry corresponds to an action for a state. The function returns a list of action names corresponding to the actions in the policy.
Source code in gym_classics2/algorithms/policy.py
greedy_policy
Calculate the greedy policy for a given value function.
:param env: the environment :param V: the value function as a 1-D numpy array :param discount: discount factor :param rng: NumPy generator or integer seed used for random tie-breaking
Source code in gym_classics2/algorithms/policy.py
greedy_policy_Q
Calculate the greedy policy for a given value function.
:param env: the environment :param Q: the action value function as a state-by-action numpy array :param rng: NumPy generator or integer seed used for random tie-breaking :param discount: discount factor
Source code in gym_classics2/algorithms/policy.py
epsilon_greedy_action
Get an epsilon-greedy action for a given tabular policy.
:param policy: the policy as a 1-D numpy array :param epsilon: the probability of taking a random action :param state: the current state :param rng: NumPy generator or integer seed
Source code in gym_classics2/algorithms/policy.py
Monte Carlo methods
gym_classics2.algorithms.monte_carlo_methods
This file implements tabular Monte Carlo methods for policy evaluation and control in gym-classics environments with discrete state spaces.
states
Returns a list of all states in the environment.
Source code in gym_classics2/algorithms/monte_carlo_methods.py
sample_episode
sample_episode(env, policy=None, start_state=None, start_action=None, epsilon=0, max_len=1000, verbose=False, rng=None)
Samples an episode from the environment using the given policy and starting conditions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
The environment to sample from. |
required | |
policy
|
A mapping from states to actions. For discrete state spaces, use
an action list in state order. If |
None
|
|
start_state
|
The state to start the episode from (if None, the environment's default starting state will be used). |
None
|
|
start_action
|
The action to take in the first step of the episode (if None, the action will be chosen according to the policy or randomly if no policy is given). |
None
|
|
epsilon
|
The probability of taking a random action instead of the policy's action at each step (for epsilon-greedy exploration). |
0
|
|
max_len
|
The maximum length of the episode to prevent infinite loops. |
1000
|
|
verbose
|
If True, prints the state transitions and rewards for each step in the episode. |
False
|
|
rng
|
NumPy generator or integer seed for policy and exploration choices. |
None
|
Returns:
| Type | Description |
|---|---|
|
A list of (state, action, reward, next_state) tuples representing the episode. |
|
|
The episode ends when a terminal state is reached or when max_len steps have been taken. |
|
|
Note that the last tuple in the episode will have a next_state that is either terminal or the |
|
|
state at which the episode was truncated due to max_len. |
Source code in gym_classics2/algorithms/monte_carlo_methods.py
on_policy_state_distribution
Estimate a policy's state distribution using rng for exploration.
Source code in gym_classics2/algorithms/monte_carlo_methods.py
MC_prediction
Estimate a policy's state values with first-visit Monte Carlo prediction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Gymnasium environment with a discrete observation space. |
required | |
policy
|
Array-like mapping from state IDs to action IDs. |
required | |
discount
|
Reward discount factor. |
required | |
n
|
Number of episodes to sample. |
100
|
|
max_episode_len
|
Maximum sampled steps per episode. |
100
|
|
verbose
|
Print episode progress when true. |
False
|
|
rng
|
NumPy generator or integer seed for episode sampling. |
None
|
Returns:
| Type | Description |
|---|---|
|
A NumPy value array with one entry per state. Unvisited states contain |
|
|
|
Source code in gym_classics2/algorithms/monte_carlo_methods.py
MC_control_ES_textbook
MC_control_ES_textbook(env, discount, n=100, Q=None, max_episode_len=100, history=False, verbose=False, rng=None)
Monte Carlo control with exploring starts and stored sample returns.
This direct textbook implementation stores every first-visit return. Prefer
:func:MC_control_ES for larger experiments because its running-average
update uses less memory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
A tabular |
required | |
discount
|
Reward discount factor. |
required | |
n
|
Number of episodes to sample. |
100
|
|
Q
|
Optional initial action-value array. |
None
|
|
max_episode_len
|
Maximum sampled steps per episode. |
100
|
|
history
|
Retain intermediate policies, Q arrays, episodes, and returns. |
False
|
|
verbose
|
Print episode details; values greater than one print transitions. |
False
|
|
rng
|
NumPy generator or integer seed for all algorithm choices. |
None
|
Returns:
| Type | Description |
|---|---|
|
|
|
|
dictionary with |
Source code in gym_classics2/algorithms/monte_carlo_methods.py
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 | |
MC_control_ES
MC_control_ES(env, discount, n=100, Q=None, max_episode_len=100, history=False, verbose=False, rng=None)
Monte Carlo Control with Exploring Starts (incremental version).
This algorithm estimates the optimal action-value function Q and the corresponding greedy policy by sampling episodes with exploring starts. It uses incremental updates to compute the average returns for each (s,a) pair, which is more memory efficient than storing all returns.
Args: env: The environment to interact with. Must have discrete state and action spaces.
discount: The discount factor (gamma) for future rewards. Should be in (0, 1].
n: The number of episodes to sample for learning. Must be a positive integer.
Q: Optional initial action-value function. If None, it will be initialized to zeros.
max_episode_len: Maximum length of each episode to prevent infinite loops. Must be a positive integer.
history: If True, the function will return the history of policies, Q-values, and
and episodes for each iteration. This can be useful for analysis and visualization, but it will consume more memory.
verbose: If True, the function will print progress and episode details. If verbose > 1, it will also print the state transitions and rewards for each step in the episode.
rng: NumPy generator or integer seed for all algorithm choices.
Returns: If history is False: A tuple (policy, Q) where policy is the learned greedy policy and Q is the learned action-value function.
If history is True: A tuple (pol_list, Q_list, ep_list) where pol_list is a list of policies for each iteration, Q
is a list of Q-value functions for each iteration, and ep_list is a list of episodes sampled in each iteration.
Source code in gym_classics2/algorithms/monte_carlo_methods.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 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | |
Temporal-difference learning
gym_classics2.algorithms.temporal_difference_learning
This file implements temporal difference learning algorithms for policy evaluation and control in gym-classics
environments with discrete state spaces. The algorithms include Sarsa(0) and Q-learning, which are fundamental
methods in reinforcement learning for learning value functions and optimal policies from experience without requiring a
model of the environment.
Sarsa_0
Learn action values with one-step on-policy Sarsa.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Gymnasium environment with discrete observation and action spaces. |
required | |
discount
|
Reward discount factor in |
required | |
alpha
|
Scalar step size or a
:class: |
required | |
epsilon
|
Scalar exploration probability or a schedule evaluated once per episode. |
required | |
Q
|
Optional initial action-value array shaped
|
None
|
|
n
|
Number of training episodes. |
100
|
|
verbose
|
Print individual updates when true. |
False
|
|
history
|
Retain Q arrays, discounted episode returns, and episode lengths. |
False
|
|
rng
|
NumPy generator or integer seed for exploration and tie-breaking. |
None
|
Returns:
| Type | Description |
|---|---|
|
The learned Q array. If |
|
|
the dictionary contains |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the observation space is not discrete. |
Source code in gym_classics2/algorithms/temporal_difference_learning.py
Q_learning
Learn action values with one-step off-policy Q-learning.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
env
|
Gymnasium environment with discrete observation and action spaces. |
required | |
discount
|
Reward discount factor in |
required | |
alpha
|
Scalar step size or a
:class: |
required | |
epsilon
|
Scalar exploration probability or a schedule evaluated once per episode. |
required | |
Q
|
Optional initial action-value array shaped
|
None
|
|
n
|
Number of training episodes. |
100
|
|
verbose
|
Print progress information when true. |
False
|
|
history
|
Retain Q arrays, discounted episode returns, episode lengths, and state-visit counts. |
False
|
|
rng
|
NumPy generator or integer seed for exploration and tie-breaking. |
None
|
Returns:
| Type | Description |
|---|---|
|
The learned Q array. If |
|
|
the dictionary contains |
|
|
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the observation space is not discrete. |
Source code in gym_classics2/algorithms/temporal_difference_learning.py
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 191 192 193 194 | |
Linear function approximation
gym_classics2.algorithms.linear_approximation
This file implements linear function approximation algorithms for policy evaluation and control. This is not a tabular approach and does not require discrete state spaces. The user needs to implement the state_features function to convert states to feature vectors.
state_features
Converts a state to a state feature vector. It needs to be overwritten by the user to implement different feature representations. This could be linear features, tile coding, radial basis functions, Fourier basis functions, or even a neural network.
:param s: state :param env: environment instance
:return a state feature vector
Source code in gym_classics2/algorithms/linear_approximation.py
active_weights
state_action_features
Construct a block-coded feature vector for a state-action pair.
v_hat
Estimate Value function
:param s: state id :param w: weight vector :param env: environment instance
:return the state value estimate
q_hat
Estimate the action value function.
:param s: state id :param a: action :param w: weight vector :param env: environment instance :return the state-action value estimate
Source code in gym_classics2/algorithms/linear_approximation.py
epsilon_greedy_action_w
Get an epsilon-greedy action for a given policy.
:param w: weight vector for the action-value function approximator :param env: environment instance :param state: the current state :param epsilon: the probability of taking a random action :param rng: NumPy generator or integer seed
Source code in gym_classics2/algorithms/linear_approximation.py
MSVE
Calculate the (weighted) mean squared value error.
:param V: value function to evaluate :param V_true: the value function to compare to :param weight: weight for each state. Typically the stationary state visit distribution.
Source code in gym_classics2/algorithms/linear_approximation.py
semi_gradient_TD0_estimation
Estimate the state-value function using the semi-gradient TD(0) algorithm.
This function runs TD(0) learning with function approximation over multiple episodes generated from a given policy and environment. Updates are performed using the semi-gradient of the value function approximation.
Parameters
env : Environment following the Gym interface from which episodes are sampled. policy : a deterministic policy as a vector. n : int Number of episodes to run for value estimation. Must be positive. alpha : float Step-size (learning rate) for TD updates. Must be in the interval (0, 1]. gamma : float Discount factor for future rewards. Must be in the interval [0, 1]. max_episode_length : int, optional Maximum number of time steps per episode (default is 1000). verbose : bool, optional If True, prints progress or diagnostic information during training (default is True).
Returns
w Returns the learned weight vector for the approximate value function.
Source code in gym_classics2/algorithms/linear_approximation.py
semi_gradient_Sarsa_0
semi_gradient_Sarsa_0(env, n, epsilon, alpha, gamma, w=None, max_episode_length=1000, verbose=False, history=False, rng=None)
Semi-gradient Sarsa(0): on-policy control with function approximation.
Implements the semi-gradient Sarsa(0) algorithm for estimating the optimal action-value function q_*(s, a) using a differentiable function approximator q̂(s, a, w). Actions are selected according to an ε-greedy policy derived from the current action-value estimate.
Episodes are truncated after max_episode_length time steps.
Parameters
env : Episodic environment used to generate experience. n : int Number of episodes over which to perform control learning. epsilon : float Exploration parameter for the epsilon-greedy behavior policy (0 <= epsilon <= 1). alpha : float Step-size parameter for the weight update (0 < alpha <= 1). gamma : float Discount factor (0 <= gamma <= 1). w : array-like or None, optional Initial weight vector for the action-value function approximator. If None, weights are initialized internally. max_episode_length : int, optional Maximum number of time steps per episode before truncation (default 1000). verbose : bool, optional If True, prints progress diagnostics during learning (default True). rng : numpy.random.Generator or int or None, optional Random generator or seed for exploration and tie-breaking.
Returns
w Returns the learned weight vector for the approximate value function.
Source code in gym_classics2/algorithms/linear_approximation.py
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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
create_fourier_basis_coefs
Create Fourier basis coefficients for given dimension and order. param dim: dimension of the state features param order: order of the Fourier basis
Source code in gym_classics2/algorithms/linear_approximation.py
transformation_fourier_basis
Create a Fourier basis transformation function for given min/max ranges and order.
To use this transformation with semi_gradient_Sarsa you need to overwrite the state_features function like this:
def state_features(s, env): return trans_fb(env.decode(s)) gym_classics2.algorithms.linear_approximation.state_features = state_features
param min: minimum values for each dimension param max: maximum values for each dimension param order: order of the Fourier basis
Source code in gym_classics2/algorithms/linear_approximation.py
Eligibility traces
gym_classics2.algorithms.eligibility_traces
This file implements the semi-gradient SARSA(lambda) algorithm for control with linear function approximation and eligibility traces. The user needs to implement the state_features function to convert states to feature vectors.
active_weights
semi_gradient_Sarsa_lambda
semi_gradient_Sarsa_lambda(env, n, epsilon, alpha, gamma, lam, w=None, max_episode_length=1000, verbose=False, history=False, rng=None)
Semi-gradient SARSA(lambda): on-policy control with linear function approximation and eligibility traces.
Parameters
env : GymClassicsBaseEnv Episodic environment used to generate experience. n : int Number of episodes. epsilon : float Exploration rate for epsilon-greedy policy. alpha : float Step size. gamma : float Discount factor. lam : float Trace-decay parameter lambda in [0, 1]. w : array-like or None Initial weights. If None, initializes to zeros. max_episode_length : int Maximum number of steps per episode. verbose : bool Whether to print step-by-step diagnostics. rng : numpy.random.Generator or int or None Random generator or seed for exploration and tie-breaking.
Returns
w : np.ndarray Learned weight vector.
Source code in gym_classics2/algorithms/eligibility_traces.py
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 | |
Policy-gradient methods
gym_classics2.algorithms.policy_gradient_methods
This file implements policy gradient methods for learning parameterized policies. The main algorithm implemented is REINFORCE, which is a Monte Carlo policy gradient method that updates policy parameters based on the returns observed in sampled episodes. The policy is represented using a softmax function over linear state-action features, and the algorithm estimates the policy gradient using the log-likelihood of actions taken in the episodes. This implementation allows for learning stochastic policies that can handle exploration and exploitation in reinforcement learning tasks.
The user has to overwrite the state_features function to convert state ids into feature vectors suitable for the environment being used.
h
pi
Return the softmax action-probability vector for a state.
sample_episode_approx_policy
Sample an episode using the policy defined by pi and theta.
:param env: the environment to sample from :param pi: the policy function that takes state, theta, and env as input and returns a probability distribution over actions :param theta: the policy parameters :param max_episode_length: maximum number of steps to sample in the episode :param rng: NumPy generator or integer seed used to sample actions :return: a list of (state, action, reward, next_state) tuples representing the sampled episode
Source code in gym_classics2/algorithms/policy_gradient_methods.py
choose_action_w
Choose an action based on the policy defined by pi and theta for the given state.
:param env: the environment :param pi: the policy function that takes state, theta, and env as input and returns a probability distribution over actions :param theta: the policy parameters :param state: the current state :param rng: NumPy generator or integer seed used to sample the action :return: the chosen action
Source code in gym_classics2/algorithms/policy_gradient_methods.py
REINFORCE
REINFORCE(env, n, alpha, gamma, theta=None, max_episode_length=1000, verbose=False, history=False, rng=None)
REINFORCE: Monte Carlo policy gradient method with linear function approximation. Parameters
env : GymClassicsBaseEnv
Episodic environment used to generate experience.
n : int
Number of episodes.
alpha : float
Step size.
gamma : float
Discount factor.
theta : array-like or None
Initial policy parameters. If None, initializes to zeros.
max_episode_length : int
Maximum number of steps per episode.
verbose : bool
Whether to print step-by-step diagnostics.
history : bool
Whether to return learning history (returns, episode lengths, parameter values).
rng : numpy.random.Generator or int or None
Random generator or seed used to sample actions.
Source code in gym_classics2/algorithms/policy_gradient_methods.py
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 | |
AC
AC(env, n, alpha_policy, alpha_value, gamma, max_episode_length=1000, verbose=False, history=False, rng=None)
Actor-Critic: Policy gradient method with linear function approximation and TD learning for the value function.
Parameters
env : Episodic environment used to generate experience. n : int Number of episodes. alpha_policy : float or Schedule Step size for policy updates. If a float is provided, it will be converted to a ConstantSchedule. If a Schedule is provided, it will be used directly. alpha_value : float or Schedule Step size for value function updates. If a float is provided, it will be converted to a ConstantSchedule. If a Schedule is provided, it will be used directly. gamma : float Discount factor. max_episode_length : int Maximum number of steps per episode. verbose : bool Whether to print step-by-step diagnostics. history : bool Whether to return learning history (returns, episode lengths, parameter values). rng : numpy.random.Generator or int or None Random generator or seed used to sample actions.
Returns
-------
theta : array-like
Final policy parameters after training.
w : array-like
Final value function parameters after training.
history : dict (optional)
If history=True, a dictionary containing the learning history with keys:
'thetas': list of policy parameter vectors at each episode,
'ws': list of value function parameter vectors at each episode,
'returns': list of returns observed at the end of each episode,
'ep_lens': list of episode lengths (number of steps) for each episode.
Source code in gym_classics2/algorithms/policy_gradient_methods.py
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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 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 261 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 | |
Schedules
gym_classics2.algorithms.schedules
This file implements different schedules to reduce the learning rate alpha or the exploration rate epsilon over time (used in on-policy methods for GLIE). These are commonly used in reinforcement learning algorithms to improve convergence and performance.
Schedule
Base class for schedules.
Source code in gym_classics2/algorithms/schedules.py
ConstantSchedule
Bases: Schedule
A schedule that always returns a constant value.
Source code in gym_classics2/algorithms/schedules.py
StepSchedule
Bases: Schedule
A schedule that always returns a constant value.
Source code in gym_classics2/algorithms/schedules.py
LinearDecaySchedule
Bases: Schedule
A schedule that decays linearly from initial_value to min_value over decay_steps.
Source code in gym_classics2/algorithms/schedules.py
ExponentialDecaySchedule
Bases: Schedule
A schedule that decays exponentially with a given decay_rate. Value at time t is max(min_value, initial_value * (decay_rate ** t)).
Source code in gym_classics2/algorithms/schedules.py
InverseDecaySchedule
Bases: Schedule
A schedule that decays inversely proportional to t. Value at time t is max(min_value, initial_value / t) for t > 0.
Source code in gym_classics2/algorithms/schedules.py
plot_schedule
Plots the values of a schedule over a given number of steps.
Example
from gym_classics2.algorithms.schedules import ConstantSchedule, LinearDecaySchedule, ExponentialDecaySchedule, InverseDecaySchedule, plot_schedule
Create different schedules
constant_sched = ConstantSchedule(0.1) linear_sched = LinearDecaySchedule(initial_value=1.0, min_value=0.1, decay_steps=1000) exponential_sched = ExponentialDecaySchedule(initial_value=1.0, min_value=0.1, decay_rate=0.99) inverse_sched = InverseDecaySchedule(initial_value=10.0, min_value=0.1)
Plot them
plot_schedule(constant_sched, steps=500) plot_schedule(linear_sched, steps=1000) plot_schedule(exponential_sched, steps=1000) plot_schedule(inverse_sched, steps=1000)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
A Schedule instance (or any callable taking an integer step). |
required | |
steps
|
The number of steps to plot. |
1000
|