Main Content

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®.

For more information on DDPG agents, see Deep Deterministic Policy Gradient (DDPG) Agents.

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 rt, provided at every time step, is



  • θt is the angle of displacement from the upright position.

  • θt˙ is the derivative of the displacement angle.

  • ut-1 is the control effort from the previous time step.

For more information on this model, see Load Predefined Control System Environments.

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.


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", ...

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

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

% Assemble paths
criticNetwork = layerGraph(imgPath);
criticNetwork = addLayers(criticNetwork,dthPath);
criticNetwork = addLayers(criticNetwork,actPath);
criticNetwork = connectLayers(criticNetwork,"fc5","cat1/in2");
criticNetwork = connectLayers(criticNetwork,"fc6","add/in2");

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


Figure contains an axes object. The axes object contains an object of type graphplot.


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, ...
    ObservationInputNames={"pendImage","angularRate"}, ...

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", ...
    scalingLayer(Name="scale1", ...

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

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

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

actor = rlContinuousDeterministicActor(actorNetwork, ...
    obsInfo,actInfo, ...

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


Figure contains an axes object. The axes object contains an object of type graphplot.


Specify options for the actor and critic using rlOptimizerOptions.

criticOptions = rlOptimizerOptions(LearnRate=1e-03,GradientThreshold=1);
actorOptions = rlOptimizerOptions(LearnRate=1e-04,GradientThreshold=1);

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(...

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.

For more information, see rlTrainingOptions.

maxepisodes = 5000;
maxsteps = 400;
trainingOptions = rlTrainingOptions(...

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


Figure Simple Pendulum Visualizer contains 2 axes objects. Axes object 1 contains 2 objects of type line, rectangle. Axes object 2 contains an object of type image.

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);
    % Load pretrained agent for the example.

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);

Figure Simple Pendulum Visualizer contains 2 axes objects. Axes object 1 contains 2 objects of type line, rectangle. Axes object 2 contains an object of type image.

See Also




Related Examples

More About