Tutorial 7: Policy gradient method and actor-critic framework¶
Tutorials for course ECE1508 Reinforcement Learning at the University of Toronto.
Author: Yicheng (Eason) Qu
Email: eason.qu@mail.utoronto.ca
The schedule of this tutorial¶
- Policy Network
- Policy Gradient
- Actor-Critic framework
- Example with continuous actions
Policy Networks and Policy Gradient Methods¶
1.Policy Network¶
A policy defines the agent’s behavior in a reinforcement learning (RL) environment. It specifies how actions are chosen given the current state $s$:
$$ \pi(a \mid s) = P(A_t = a \mid S_t = s) $$
In the discrete scenario, this can be achieved by a table. What if both states and actions are from the continuous space?
A policy network parameterizes this policy using a differentiable function $\pi_\theta(a \mid s)$, typically a neural network with parameters $\theta$:
- Input: current state $s$
- Output:
- parameters of a continuous distribution (e.g., mean and variance of a Gaussian).
Thus, the network directly maps states to action probabilities instead of estimating value functions as in Q-learning (DQN).
2. Objective Function: Maximizing Expected Return¶
In policy-based reinforcement learning, the goal is to find the policy parameters θ that maximize the expected cumulative reward (also called the expected return):
$$ \large J(\theta) = \mathbb{E}_{\pi_\theta}\!\left[ \sum_{t=0}^{\infty} \gamma^t r_t \right] $$
where
- $\pi_\theta(a|s)$ — the stochastic policy parameterized by $\theta$,
- $r_t$ — the reward at time step $t$,
- $\gamma \in (0,1]$ — the discount factor, weighting near-term rewards more than distant ones.
Intuitively, $J(\theta)$ measures how good the policy is: it is the expected total discounted reward the agent receives when following $\pi_\theta$.
Formally, this expectation expands over all trajectories $\tau = (s_0, a_0, s_1, a_1, \ldots)$ drawn under the policy and environment dynamics:
$$ \large J(\theta) = \int_\tau P(\tau | \theta) \, R(\tau) \, d\tau, $$
where
- $P(\tau | \theta) = \rho(s_0) \prod_{t=0}^{\infty} \pi_\theta(a_t|s_t) \, P(s_{t+1}|s_t, a_t)$,
- $R(\tau) = \sum_t \gamma^t r_t$.
However, differentiating $P(s_{t+1}|s_t,a_t)$ (the environment dynamics) is intractable. The policy gradient theorem elegantly circumvents this.
3. Policy Gradient Theorem¶
The policy gradient theorem provides a tractable way to compute the gradient of the objective $J(\theta)$ without differentiating through the (often unknown and non-differentiable) environment dynamics.
We begin with the expected return:
$$ \large J(\theta) = \mathbb{E}_{\pi_\theta}[R(\tau)] = \int P(\tau \mid \theta)\, R(\tau)\, d\tau, $$
where $\tau = (s_0, a_0, s_1, a_1, \ldots)$ is a trajectory generated by the policy $\pi_\theta$, and $P(\tau \mid \theta)$ is its probability under the policy and the environment.
Step 1. Differentiate the expectation¶
$$ \large \nabla_\theta J(\theta) = \int \nabla_\theta P(\tau \mid \theta)\, R(\tau)\, d\tau. $$
Directly differentiating $P(\tau \mid \theta)$ is hard because it involves all the transition terms $P(s_{t+1} \mid s_t, a_t)$ of the environment.
Step 2. Apply the log-likelihood trick¶
We multiply and divide by $P(\tau \mid \theta)$:
$$ \large \nabla_\theta P(\tau \mid \theta) = P(\tau \mid \theta)\, \nabla_\theta \log P(\tau \mid \theta). $$
Substituting gives
$$ \large \nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta}\!\big[\, \nabla_\theta \log P(\tau \mid \theta)\, R(\tau) \,\big]. $$
This “log-likelihood trick” (also called the score-function estimator) moves the derivative inside the expectation, allowing us to estimate the gradient from sampled trajectories.
Step 3. Eliminate environment terms¶
The trajectory log-probability decomposes as
$$ \log P(\tau \mid \theta) = \log \rho(s_0) + \sum_t \log P(s_{t+1} \mid s_t, a_t) + \sum_t \log \pi_\theta(a_t \mid s_t). $$
Since the environment transition probabilities do not depend on $\theta$,
$$ \large \nabla_\theta \log P(\tau \mid \theta) = \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t). $$
Hence,
$$ \large \nabla_\theta J(\theta) = \mathbb{E}_{\pi_\theta} \!\left[\, \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, R_t \,\right]. $$
This forms the basis of the REINFORCE algorithm.
Step 4. Policy Gradient Theorem (final form)¶
By expressing the return using the action–value function $Q^{\pi_\theta}(s,a)$ and grouping expectations over visited states and actions, we obtain
$$ \large \nabla_\theta J(\theta) = \mathbb{E}_{s \sim d^{\pi_\theta},\, a \sim \pi_\theta} \left[\, \nabla_\theta \log \pi_\theta(a \mid s)\, Q^{\pi_\theta}(s,a) \,\right], $$
where
- $d^{\pi_\theta}(s)$ — the discounted stationary state distribution under $\pi_\theta$,
- $Q^{\pi_\theta}(s,a)$ — the action–value function, $$ \large Q^{\pi_\theta}(s,a) = \mathbb{E}_{\pi_\theta}\!\left[\sum_{t=0}^\infty \gamma^t r_t \,\big|\, s_0=s, a_0=a \right]. $$
Step 5. Intuition¶
- The term $\nabla_\theta \log \pi_\theta(a|s)$ tells the policy how to shift probability mass toward actions that yield higher return.
- Using $\log$ converts the product of action probabilities over time into a sum, simplifying differentiation.
- This expression depends only on the policy itself, not on environment dynamics, making it practical for Monte Carlo and actor–critic implementations.
4. Actor–Critic Framework and Update Rule¶
The actor–critic method refines basic policy gradient algorithms by introducing a second function approximator—the critic—to estimate value functions and provide low-variance learning signals to the policy (the actor).
• Components¶
Actor: The policy network $\pi_\theta(a|s)$ parameterized by $\theta$, which outputs a probability distribution (or parameters of a distribution) over actions. Its goal is to maximize the expected return $$ \large J(\theta) = \mathbb{E}_{\pi_\theta}\!\left[\sum_{t=0}^{T}\gamma^t r_t\right]. $$
Critic: The value network $V_\phi(s)$ parameterized by $\phi$, which estimates the expected return from each state under the current policy: $$ \large V^{\pi_\theta}(s) \approx V_\phi(s) = \mathbb{E}_{\pi_\theta}\!\left[\sum_{k=0}^\infty \gamma^k r_{t+k}\,\bigg|\,s_t=s\right]. $$ This serves as a baseline that stabilizes and reduces variance in the actor’s gradient estimates.
• Policy (Actor) Update: IMPROVEMENT → ascend policy gradient weighted by the advantage¶
Instead of using the raw Monte-Carlo return $R_t$, the actor updates its parameters using an advantage estimate $$ \large \hat{A}_t = Q^{\pi_\theta}(s_t,a_t) - V^{\pi_\theta}(s_t), $$ which measures how much better an action $a_t$ performed than the critic’s expectation at that state.
In practice, $Q^{\pi_\theta}(s_t,a_t)$ is not computed directly; we use a bootstrapped estimate: $$ \large \hat{A}_t \approx r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t). $$
The actor’s gradient ascent step is then $$ \large \boxed{ \theta \leftarrow \theta + \alpha_\theta \, \nabla_\theta \log \pi_\theta(a_t \mid s_t)\, \hat{A}_t } $$ where $\alpha_\theta$ is the actor’s learning rate.
• Value (Critic) Update: EVALUATION → minimize TD error¶
The critic learns to minimize the temporal-difference (TD) error: $$ \large \delta_t = r_t + \gamma V_\phi(s_{t+1}) - V_\phi(s_t). $$
It updates its parameters by gradient descent on the squared TD error: $$ \large \boxed{ \phi \leftarrow \phi - \alpha_\phi \, \nabla_\phi \big(\delta_t^2\big) } $$ where $\alpha_\phi$ is the critic’s learning rate.
• Combined Intuition¶
- The critic evaluates how good the current policy is by estimating $V_\phi(s)$.
- The actor adjusts its policy probabilities using the critic’s feedback signal $\hat{A}_t$.
- The advantage centers updates around zero:
- if $\hat{A}_t > 0$ → increase the probability of that action
- if $\hat{A}_t < 0$ → decrease it
This structure yields a balance between:
- Low variance (through bootstrapping in the critic), and
- Low bias (through the actor’s policy gradient objective).
Import libraries¶
import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import matplotlib.pyplot as plt
if not hasattr(np, "bool8"): # Fix for Gym ≤0.26 with NumPy ≥1.24
np.bool8 = np.bool_
Gym has been unmaintained since 2022 and does not support NumPy 2.0 amongst other critical functionality. Please upgrade to Gymnasium, the maintained drop-in replacement of Gym, or contact the authors of your software and request that they upgrade. Users of this version of Gym should be able to simply replace 'import gym' with 'import gymnasium as gym' in the vast majority of cases. See the migration guide at https://gymnasium.farama.org/introduction/migration_guide/ for additional information.
Policy Network¶
class ActorCritic(nn.Module):
#Layers are fully-connected
def __init__(self, state_size, action_size, env, fc1_dims=128):
super(ActorCritic, self).__init__()
self.env = env
# Input layer
self.fc1 = nn.Linear(state_size, fc1_dims)
# Discrete actor network. Softmax for ouputting probabilities.
if isinstance(env.action_space, gym.spaces.Discrete):
self.action_head = nn.Linear(fc1_dims, action_size)
self.softmax = nn.Softmax(dim=-1)
# Continuous actior network, needs mean and std for action distributions
if isinstance(env.action_space, gym.spaces.Box):
self.mu_head = nn.Linear(fc1_dims, action_size)
self.std_head = nn.Linear(fc1_dims, action_size)
# Critic network
self.value_head = nn.Linear(fc1_dims, 1)
def forward(self, x):
# Discrete action space
if isinstance(self.env.action_space, gym.spaces.Discrete):
x = torch.relu(self.fc1(x))
action_probs = self.softmax(self.action_head(x))
state_values = self.value_head(x)
return action_probs, state_values
# Continuous action space
if isinstance(self.env.action_space, gym.spaces.Box):
x = torch.relu(self.fc1(x))
action_mean = self.mu_head(x)
action_std = torch.exp(self.std_head(x))
state_values = self.value_head(x)
return action_mean, action_std, state_values
def save_weights(self, path):
torch.save(self.state_dict(), path)
def load_weights(self, path):
self.load_state_dict(torch.load(path))
Episode generating function¶
def generate_episode(env, policy):
state,_ = env.reset()
log_probs = []
state_values = []
rewards = []
masks = []
done = False
while not done:
state = torch.FloatTensor(state).unsqueeze(0)
# Discrete action space
if isinstance(env.action_space, gym.spaces.Discrete):
# Compute probability for each discrete action
probs, state_value = policy(state)
# For discrete action space, use multi-nomial distribution
action_distribution = torch.distributions.Categorical(probs)
action = action_distribution.sample()
log_prob = action_distribution.log_prob(action)
action = action.item()
# Continuous action space
elif isinstance(env.action_space, gym.spaces.Box):
# Compute action mean and std for the continuous action
action_mean, action_std, state_value = policy(state)
# For continuous action space, use normal distribution
action_distribution = torch.distributions.Normal(action_mean, action_std)
action = action_distribution.sample()
log_prob = action_distribution.log_prob(action)
action = action.detach().numpy()
next_state, reward, done, _, _ = env.step(action)
log_probs.append(log_prob)
state_values.append(state_value)
rewards.append(torch.tensor([reward], dtype=torch.float32))
# Masks for handling the terminal state reward = 0
masks.append(torch.tensor([1-done], dtype=torch.float32))
state = next_state.squeeze()
return log_probs, state_values, rewards, masks
def compute_returns(rewards, masks, gamma=0.99):
G = torch.tensor([0.0])
returns = []
for step in reversed(range(len(rewards))):
R = rewards[step] + gamma * G * masks[step]
returns.insert(0, G)
return returns
Policy evaluating function¶
# Evaluate a policy
def evaluate_policy(env, policy, episodes=10, render=False):
total_rewards = []
for _ in range(episodes):
state,_ = env.reset()
done = False
episode_reward = 0
while not done:
state = torch.FloatTensor(state).unsqueeze(0)
with torch.no_grad(): # No need to calculate gradients during evaluation
# Discrete action space
if isinstance(env.action_space, gym.spaces.Discrete):
probs, _ = policy(state)
action = torch.argmax(probs).item() # Select action with highest probability
# Continuous action space
elif isinstance(env.action_space, gym.spaces.Box):
mu, std, _ = policy(state)
action = mu.numpy() # Use the mean of the distribution as the action
next_state, reward, done,_, _ = env.step(action)
if render:
env.render()
state = next_state.squeeze()
episode_reward += reward
total_rewards.append(episode_reward)
average_reward = sum(total_rewards) / episodes
# print(f"Average Reward over {episodes} episodes: {average_reward}")
env.close()
return average_reward
Policy gradient algorithm with Advantage¶
def train_actor_critic(env, policy, optimizer, episodes, gamma=0.99, evaluation_interval=50, save_path='models/model.pth'):
best_reward = -np.inf
episode_rewards = []
for episode in range(episodes):
log_probs, state_values, rewards, masks = generate_episode(env, policy)
episode_rewards.append(sum(rewards))
returns = compute_returns(rewards, masks, gamma)
log_probs = torch.cat(log_probs)
returns = torch.cat(returns).detach()
state_values = torch.cat(state_values)
advantage = returns - state_values
# - A * log pi. Quiz: Why negative sign?
actor_loss = -(log_probs * advantage).mean()
# Mean Squared Error for critic loss
critic_loss = advantage.pow(2).mean()
optimizer.zero_grad()
(actor_loss + critic_loss).backward()
optimizer.step()
# Evaluate the policy periodically
if episode % evaluation_interval == 0:
average_reward = evaluate_policy(env, policy, episodes=evaluation_interval)
print(f'Episode {episode}: Evaluation Average Reward: {average_reward}')
if average_reward > best_reward:
best_reward = average_reward
print(f"New best reward {best_reward} found, saving model.")
policy.save_weights(save_path)
episode_rewards = np.array(episode_rewards)
smooth_rewards = np.zeros(len(episode_rewards) - 50)
# average over last 50 episodes
for t in range(len(episode_rewards)-50):
smooth_rewards[t] = np.mean(episode_rewards[-50+t:t])
plt.figure(figsize=(10, 5))
plt.plot(smooth_rewards)
plt.xlabel('Episodes')
plt.ylabel('Training Rewards')
plt.savefig(f'plots/BPG_{env.spec.id}.png')
plt.show()
return policy
CartPole-v0: discrete action space¶

CartPole-v0 Environment Overview¶
Goal: Balance a pole upright on a moving cart by applying forces to the cart. The agent must prevent the pole from falling or the cart from moving out of bounds.
State (observation): continuous vector $$ s_t = [\,x_t,\; \dot{x}_t,\; \theta_t,\; \dot{\theta}_t\,] $$ where
- $x_t$: cart position (meters) — roughly in $[-2.4, 2.4]$
- $\dot{x}_t$: cart velocity (m/s)
- $\theta_t$: pole angle from vertical (radians, $0$ = upright, $\approx [-12^\circ, 12^\circ]$)
- $\dot{\theta}_t$: pole angular velocity (rad/s)
Actions: discrete set $$ a_t \in \{\,0,\,1\,\} $$
- 0: push cart to the left
- 1: push cart to the right
Reward: scalar feedback each step $$ r_t = \begin{cases} 1, & \text{if pole remains upright and within bounds}\\[4pt] 0, & \text{otherwise (episode ends)} \end{cases} $$
Episode termination conditions:
- $|\theta_t| > 12^\circ$ (pole falls)
- $|x_t| > 2.4$ (cart out of range)
- episode length reaches 200 steps (success)
# Initialize environment and model
env = gym.make('CartPole-v0')
env.seed(42)
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
policy = ActorCritic(state_size, action_size, env, fc1_dims=128)
optimizer = optim.Adam(policy.parameters(), lr=0.001)
# Train the policy
trained_policy = train_actor_critic(env, policy, optimizer, episodes=2000, save_path='models/BPG_'+ env.spec.id)
# Evaluate the trained policy
average_reward = evaluate_policy(env, trained_policy, episodes=10)
Episode 0: Evaluation Average Reward: 9.5 New best reward 9.5 found, saving model. Episode 50: Evaluation Average Reward: 9.32 Episode 100: Evaluation Average Reward: 9.32 Episode 150: Evaluation Average Reward: 9.24 Episode 200: Evaluation Average Reward: 45.72 New best reward 45.72 found, saving model. Episode 250: Evaluation Average Reward: 63.26 New best reward 63.26 found, saving model. Episode 300: Evaluation Average Reward: 32.7 Episode 350: Evaluation Average Reward: 61.22 Episode 400: Evaluation Average Reward: 150.66 New best reward 150.66 found, saving model. Episode 450: Evaluation Average Reward: 95.2 Episode 500: Evaluation Average Reward: 51.02 Episode 550: Evaluation Average Reward: 106.86 Episode 600: Evaluation Average Reward: 177.96 New best reward 177.96 found, saving model. Episode 650: Evaluation Average Reward: 113.82 Episode 700: Evaluation Average Reward: 144.36 Episode 750: Evaluation Average Reward: 166.0 Episode 800: Evaluation Average Reward: 163.24 Episode 850: Evaluation Average Reward: 155.7 Episode 900: Evaluation Average Reward: 186.66 New best reward 186.66 found, saving model. Episode 950: Evaluation Average Reward: 197.16 New best reward 197.16 found, saving model. Episode 1000: Evaluation Average Reward: 200.0 New best reward 200.0 found, saving model. Episode 1050: Evaluation Average Reward: 200.0 Episode 1100: Evaluation Average Reward: 200.0 Episode 1150: Evaluation Average Reward: 200.0 Episode 1200: Evaluation Average Reward: 187.36 Episode 1250: Evaluation Average Reward: 198.4 Episode 1300: Evaluation Average Reward: 199.52 Episode 1350: Evaluation Average Reward: 200.0 Episode 1400: Evaluation Average Reward: 198.76 Episode 1450: Evaluation Average Reward: 200.0 Episode 1500: Evaluation Average Reward: 200.0 Episode 1550: Evaluation Average Reward: 200.0 Episode 1600: Evaluation Average Reward: 200.0 Episode 1650: Evaluation Average Reward: 176.02 Episode 1700: Evaluation Average Reward: 200.0 Episode 1750: Evaluation Average Reward: 200.0 Episode 1800: Evaluation Average Reward: 200.0 Episode 1850: Evaluation Average Reward: 200.0 Episode 1900: Evaluation Average Reward: 175.54 Episode 1950: Evaluation Average Reward: 200.0
Load & Evaluate the trained policy¶
env = gym.make('CartPole-v0')
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
policy = ActorCritic(state_size, action_size, env)
policy.load_weights('models/BPG_CartPole-v0')
policy.eval()
average_reward = evaluate_policy(env, policy, episodes=100, render=False)
print(average_reward)
200.0
MountainCarContinuous-v0: continuous action space¶

Goal: Drive a car up a steep hill on the right by building momentum through forward and backward acceleration. The car’s engine is not strong enough to reach the hilltop directly, so it must first move left to gain kinetic energy.
State (observation): continuous vector $$ s_t = [\,x_t,\; \dot{x}_t\,] $$ where
- $x_t$: car position in the range $[-1.2,\, 0.6]$
- $\dot{x}_t$: car velocity in the range $[-0.07,\, 0.07]$
Action: continuous scalar $$ a_t \in [-1.0,\, 1.0] $$ representing the throttle force (negative for left acceleration, positive for right).
Reward:
- At each time step: $$ r_t = -0.1\, a_t^2 $$ (a small penalty on throttle magnitude to encourage energy efficiency).
- When the car reaches the goal position $x_t \ge 0.45$, it receives an additional terminal reward of +100.
Episode termination conditions:
- Car reaches the goal position ($x_t \ge 0.45$).
- Episode exceeds the maximum number of steps (default 999).
# Initialize environment and model
env = gym.make('MountainCarContinuous-v0')
state_size = env.observation_space.shape[0]
action_size = env.action_space.shape[0] if isinstance(env.action_space, gym.spaces.Box) else env.action_space.n
policy = ActorCritic(state_size, action_size, env)
optimizer = optim.Adam(policy.parameters(), lr=0.001)
# Train the policy
trained_policy = train_actor_critic(env, policy, optimizer, episodes=200, save_path='models/BPG_'+ env.spec.id)
# Evaluate the trained policy
average_reward = evaluate_policy(env, trained_policy, episodes=10, render=False)
/usr/local/lib/python3.10/dist-packages/gym/core.py:317: DeprecationWarning: WARN: Initializing wrapper in old step API which returns one bool instead of two. It is recommended to set `new_step_api=True` to use new step API. This will be the default behaviour in future. deprecation( /usr/local/lib/python3.10/dist-packages/gym/wrappers/step_api_compatibility.py:39: DeprecationWarning: WARN: Initializing environment in old step API which returns one bool instead of two. It is recommended to set `new_step_api=True` to use new step API. This will be the default behaviour in future. deprecation( /usr/local/lib/python3.10/dist-packages/gym/envs/classic_control/continuous_mountain_car.py:171: DeprecationWarning: Conversion of an array with ndim > 0 to a scalar is deprecated, and will error in future. Ensure you extract a single element from your array before performing this operation. (Deprecated NumPy 1.25.) reward -= math.pow(action[0], 2) * 0.1 /usr/local/lib/python3.10/dist-packages/gym/utils/passive_env_checker.py:241: DeprecationWarning: `np.bool8` is a deprecated alias for `np.bool_`. (Deprecated NumPy 1.24) if not isinstance(terminated, (bool, np.bool8)): /usr/local/lib/python3.10/dist-packages/gym/utils/passive_env_checker.py:165: UserWarning: WARN: The obs returned by the `step()` method is not within the observation space. logger.warn(f"{pre} is not within the observation space.")
Episode 0: Evaluation Average Reward: -0.31999701514689877 New best reward -0.31999701514689877 found, saving model. Episode 50: Evaluation Average Reward: -0.05115555008537018 New best reward -0.05115555008537018 found, saving model. Episode 100: Evaluation Average Reward: -0.09888319089505541 Episode 150: Evaluation Average Reward: -0.01923045984482685 New best reward -0.01923045984482685 found, saving model.
/usr/local/lib/python3.10/dist-packages/numpy/core/fromnumeric.py:3504: RuntimeWarning: Mean of empty slice. return _methods._mean(a, axis=axis, dtype=dtype, /usr/local/lib/python3.10/dist-packages/numpy/core/_methods.py:129: RuntimeWarning: invalid value encountered in divide ret = ret.dtype.type(ret / rcount)
Pendulum-v1: continuous action space¶

Goal: Swing the pendulum upright and keep it balanced vertically by applying continuous torque to its base. The agent must minimize the pendulum’s angle deviation and angular velocity while using as little control effort as possible.
State (observation): continuous vector $$ s_t = [\,\cos\theta_t,\; \sin\theta_t,\; \dot{\theta}_t\,] $$ where
- $\theta_t$: pendulum angle (radians) — 0 means perfectly upright
- $\dot{\theta}_t$: angular velocity (rad/s) Using both $\sin\theta_t$ and $\cos\theta_t$ avoids angle discontinuities around $\pm \pi$.
Action: continuous scalar $$ a_t \in [-2.0,\, 2.0] $$ representing the torque applied at the pendulum’s joint (negative = counterclockwise, positive = clockwise).
Reward: At each step, the environment provides a negative cost proportional to energy loss: $$ r_t = -\!\left(\theta_t^2 + 0.1\,\dot{\theta}_t^2 + 0.001\,a_t^2\right) $$
- Penalizes large angles (deviation from upright),
- Penalizes fast spinning (large $\dot{\theta}$),
- Penalizes strong torque (energy cost).
Episode termination:
- Episodes last a fixed number of time steps (default 200).
- There is no explicit “success” termination; performance is judged by cumulative reward.
# Initialize environment and model
env = gym.make('Pendulum-v1', g=9.81)
env = gym.wrappers.TimeLimit(env, max_episode_steps=200)
state_size = env.observation_space.shape[0]
action_size = env.action_space.shape[0] if isinstance(env.action_space, gym.spaces.Box) else env.action_space.n
policy = ActorCritic(state_size, action_size, env)
optimizer = optim.Adam(policy.parameters(), lr=0.001)
# Train the policy
trained_policy = train_actor_critic(env, policy, optimizer, episodes=1000, save_path='models/BPG_'+ env.spec.id)
# Evaluate the trained policy
average_reward = evaluate_policy(env, trained_policy, episodes=10, render=False)
/usr/local/lib/python3.10/dist-packages/gym/utils/passive_env_checker.py:260: UserWarning: WARN: The reward returned by `step()` must be a float, int, np.integer or np.floating, actual type: <class 'numpy.ndarray'>
logger.warn(
Episode 49: Evaluation Average Reward: [-1369.6434] New best reward [-1369.6434] found, saving model. Episode 99: Evaluation Average Reward: [-1431.47] Episode 149: Evaluation Average Reward: [-1339.1016] New best reward [-1339.1016] found, saving model. Episode 199: Evaluation Average Reward: [-1376.5563] Episode 249: Evaluation Average Reward: [-1423.9058] Episode 299: Evaluation Average Reward: [-1487.7756] Episode 349: Evaluation Average Reward: [-1432.0552] Episode 399: Evaluation Average Reward: [-1613.418] Episode 449: Evaluation Average Reward: [-1438.3214] Episode 499: Evaluation Average Reward: [-1443.9603] Episode 549: Evaluation Average Reward: [-1461.8059] Episode 599: Evaluation Average Reward: [-1542.5703] Episode 649: Evaluation Average Reward: [-1518.2075] Episode 699: Evaluation Average Reward: [-1531.2661] Episode 749: Evaluation Average Reward: [-1438.9958] Episode 799: Evaluation Average Reward: [-1512.4388] Episode 849: Evaluation Average Reward: [-1396.4768] Episode 899: Evaluation Average Reward: [-1564.2498] Episode 949: Evaluation Average Reward: [-1427.5104] Episode 999: Evaluation Average Reward: [-1506.0969]
Conclusion¶
In this tutorial, we explored the Actor-Critic method, an important approach in reinforcement learning that combines the benefits of both policy-based and value-based approaches. As we wrap up, let's highlight some of the key takeaways:
Integration of Baseline for Variance Reduction:
The Actor-Critic method introduces a baseline function, typically the state value function, which helps to reduce the variance of the policy gradient estimates. As long as the baseline function is independent of the action, the policy gradient is unbiased. This approach stabilizes learning by providing a reference point (the critic) against which the policy's actions (the actor) can be evaluated, improving the efficiency of the learning process.
Continuous and Discrete Action Spaces:
Actor-Critic frameworks are versatile, applicable to both continuous and discrete action spaces, making them suitable for a wide range of problems from robotic control (continuous actions) to game playing (discrete actions). The method’s flexibility stems from its ability to model the policy and value functions as neural networks that can output probabilities for discrete actions or mean and variance for continuous actions.
Separation of Policy and Value Estimation:
By decoupling the policy and value function estimations, Actor-Critic methods can leverage the strengths of both: using the critic to assess the quality of actions taken by the actor, and updating the policy based on this feedback. This separation allows for more flexible and potentially more powerful learning dynamics compared to methods that only estimate a value function or solely optimize a policy.