Train DDPG Agent to Swing Up and Balance Pendulum with Image Observation

This example shows how to train a deep deterministic policy gradient (DDPG) agent to swing up and balance a pendulum with an image observation modeled in MATLAB®.

Simple Pendulum with Image MATLAB Environment

The reinforcement learning environment for this example is a simple frictionless pendulum that initially hangs in a downward position. The training goal is to make the pendulum stand upright without falling over using minimal control effort.

For this environment:

• The upward balanced pendulum position is 0 radians, and the downward hanging position is pi radians.

• The torque action signal from the agent to the environment is from –2 to 2 N·m.

• The observations from the environment are an image indicating the location of the pendulum mass and the pendulum angular velocity.

• The reward ${\mathit{r}}_{\mathit{t}}$, provided at every time step, is

${\mathit{r}}_{\mathit{t}}=-\left({{\theta }_{\mathit{t}}}^{2}+0.1{\stackrel{˙}{{\theta }_{\mathit{t}}}}^{2}+0.001{{\mathit{u}}_{\mathit{t}-1}}^{2}\right)$

Here:

• ${\theta }_{\mathit{t}}$ is the angle of displacement from the upright position.

• $\stackrel{˙}{{\theta }_{\mathit{t}}}$ is the derivative of the displacement angle.

• ${\mathit{u}}_{\mathit{t}-1}$ is the control effort from the previous time step.

Create Environment Interface

Create a predefined environment interface for the pendulum.

env = rlPredefinedEnv("SimplePendulumWithImage-Continuous")
env =
SimplePendlumWithImageContinuousAction with properties:

Mass: 1
RodLength: 1
RodInertia: 0
Gravity: 9.8100
DampingRatio: 0
MaximumTorque: 2
Ts: 0.0500
State: [2x1 double]
Q: [2x2 double]
R: 1.0000e-03

The interface has a continuous action space where the agent can apply a torque between –2 to 2 N·m.

Obtain the observation and action specification from the environment interface.

obsInfo = getObservationInfo(env);
actInfo = getActionInfo(env);

Fix the random generator seed for reproducibility.

rng(0)

Create DDPG Agent

DDPG agents use a parametrized Q-value function approximator to estimate the value of the policy. A Q-value function critic takes the current observation and an action as inputs and returns a single scalar as output (the estimated discounted cumulative long-term reward for which receives the action from the state corresponding to the current observation, and following the policy thereafter).

To model the parametrized Q-value function within the critic, use a convolutional neural network (CNN) with three input layers (one for each observation channel, as specified by obsInfo, and the other for the action channel, as specified by actInfo) and one output layer (which returns the scalar value).

Define each network path as an array of layer objects, and assign names to the input and output layers of each path, as well as to the addition and concatenation layers. These names allow you to connect the paths and then later explicitly associate the network input and output layers with the appropriate environment channel. For more information on creating representations, see Create Policies and Value Functions.

hiddenLayerSize1 = 400;
hiddenLayerSize2 = 300;

% Image input path
imgPath = [
imageInputLayer(obsInfo(1).Dimension, ...
Normalization="none", ...
Name=obsInfo(1).Name)
reluLayer
fullyConnectedLayer(2)
concatenationLayer(3,2,Name="cat1")
fullyConnectedLayer(hiddenLayerSize1)
reluLayer
fullyConnectedLayer(hiddenLayerSize2)
reluLayer
fullyConnectedLayer(1,Name="fc4")
];

% d(theta)/dt input path
dthPath = [
imageInputLayer(obsInfo(2).Dimension, ...
Normalization="none", ...
Name=obsInfo(2).Name)
fullyConnectedLayer(1,Name="fc5", ...
BiasLearnRateFactor=0, ...
Bias=0)
];

% Action path
actPath =[
imageInputLayer(actInfo(1).Dimension, ...
Normalization="none", ...
Name="action")
fullyConnectedLayer(hiddenLayerSize2, ...
Name="fc6", ...
BiasLearnRateFactor=0, ...
Bias=zeros(hiddenLayerSize2,1))
];

% Assemble paths
criticNetwork = layerGraph(imgPath);
criticNetwork = connectLayers(criticNetwork,"fc5","cat1/in2");

View the critic network configuration and display the number of parameters.

figure
plot(criticNetwork)

%summary(criticNetwork)

Create the critic representation using the specified neural network and the environment action and observation specifications. Pass as additional arguments also the names of the network layers to be connected with the observation and action channels. For more information, see rlQValueFunction.

critic = rlQValueFunction(criticNetwork, ...
obsInfo,actInfo,...
ObservationInputNames={"pendImage","angularRate"}, ...
ActionInputNames={"action"});

DDPG agents use a parametrized deterministic policy over continuous action spaces, which is implemented by a continuous deterministic actor. A continuous deterministic actor implements a parametrized deterministic policy for a continuous action space. This actor takes the current observation as input and returns as output an action that is a deterministic function of the observation.

To model the parametrized policy within the actor, use a neural network with two input layers (receiving the content of the two environment observation channels, as specified by obsInfo) and one output layer (which returns the action to the environment action channel, as specified by actInfo).

Define the network as an array of layer objects.

% Image input path
imgPath = [
imageInputLayer(obsInfo(1).Dimension, ...
Normalization="none", ...
Name=obsInfo(1).Name)
reluLayer
fullyConnectedLayer(2,Name="fc1")
concatenationLayer(3,2,Name="cat1")
fullyConnectedLayer(hiddenLayerSize1,Name="fc2")
reluLayer
fullyConnectedLayer(hiddenLayerSize2,Name="fc3")
reluLayer
fullyConnectedLayer(1,Name="fc4")
tanhLayer
scalingLayer(Name="scale1", ...
Scale=max(actInfo.UpperLimit))
];

% d(theta)/dt input layer
dthPath = [
imageInputLayer(obsInfo(2).Dimension, ...
Normalization="none", ...
Name=obsInfo(2).Name)
fullyConnectedLayer(1, ...
Name="fc5", ...
BiasLearnRateFactor=0, ...
Bias=0)
];

% Assemble actor network
actorNetwork = layerGraph(imgPath);
actorNetwork = connectLayers(actorNetwork,"fc5","cat1/in2");

Create the actor using the specified neural network. For more information, see rlContinuousDeterministicActor.

actor = rlContinuousDeterministicActor(actorNetwork, ...
obsInfo,actInfo, ...
ObservationInputNames={"pendImage","angularRate"});

View the actor network configuration and display the number of weights.

figure
plot(actorNetwork)

%summary(actorNetwork)

Specify options for the actor and critic using rlOptimizerOptions.

Training performance using the GPU is impacted by the batch size, network structure, and the hardware itself. Therefore, using a GPU does not always guarantee a better training performance. For more information on supported GPUs, see GPU Computing Requirements (Parallel Computing Toolbox).

Uncomment the following line to train the critic using a GPU.

% criticOptions.UseDevice = "gpu";

Uncomment the following line to train the actor using a GPU.

% actorOptions.UseDevice = "gpu";

Specify the DDPG agent options using rlDDPGAgentOptions.

agentOptions = rlDDPGAgentOptions(...
SampleTime=env.Ts,...
TargetSmoothFactor=1e-3,...
ExperienceBufferLength=1e6,...
DiscountFactor=0.99,...
MiniBatchSize=128);

You can also specify options using dot notation.

agentOptions.NoiseOptions.Variance = 0.6;
agentOptions.NoiseOptions.VarianceDecayRate = 1e-6;

Specify the training options for the function approximator objects.

agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;

Then create the agent using the specified actor representation, critic representation, and agent options. For more information, see rlDDPGAgent.

agent = rlDDPGAgent(actor,critic,agentOptions);

Train Agent

To train the agent, first specify the training options. For this example, use the following options.

• Run each training for at most 5000 episodes, with each episode lasting at most 400 time steps.

• Display the training progress in the Episode Manager dialog box (set the Plots option).

• Stop training when the agent receives a moving average cumulative reward greater than -740 over ten consecutive episodes. At this point, the agent can quickly balance the pendulum in the upright position using minimal control effort.

maxepisodes = 5000;
maxsteps = 400;
trainingOptions = rlTrainingOptions(...
MaxEpisodes=maxepisodes,...
MaxStepsPerEpisode=maxsteps,...
Plots="training-progress",...
StopTrainingCriteria="AverageReward",...
StopTrainingValue=-740);

You can visualize the pendulum by using the plot function during training or simulation.

plot(env)

Train the agent using the train function. Training this agent is a computationally intensive process that takes several hours to complete. To save time while running this example, load a pretrained agent by setting doTraining to false. To train the agent yourself, set doTraining to true.

doTraining = false;
if doTraining
% Train the agent.
trainingStats = train(agent,env,trainingOptions);
else
% Load pretrained agent for the example.
end

Simulate DDPG Agent

To validate the performance of the trained agent, simulate it within the pendulum environment. For more information on agent simulation, see rlSimulationOptions and sim.

simOptions = rlSimulationOptions(MaxSteps=500);
experience = sim(env,agent,simOptions);