Main Content

Train DDPG Agent to Swing Up and Balance Cart-Pole System

This example shows how to train a deep deterministic policy gradient (DDPG) agent to swing up and balance a cart-pole system modeled in Simscape™ Multibody™.

For more information on DDPG agents, see Deep Deterministic Policy Gradient (DDPG) Agents. For an example showing how to train a DDPG agent in MATLAB®, see Compare DDPG Agent to LQR Controller.

Cart-Pole Simscape Model

The reinforcement learning environment for this example is a pole attached to an unactuated joint on a cart, which moves along a frictionless track. The training goal is to make the pole stand upright without falling over using minimal control effort.

Open the model.

mdl = "rlCartPoleSimscapeModel";
open_system(mdl)

The cart-pole system is modeled using Simscape Multibody.

For this model:

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

  • The force action signal from the agent to the environment is from –15 to 15 N.

  • The observations from the environment are the position and velocity of the cart, and the sine, cosine, and derivative of the pole angle.

  • The episode terminates if the cart moves more than 3.5 m from the original position.

  • The reward rt, provided at every timestep, is

rt=-0.1(5θt2+xt2+0.05ut-12)-100B

Here:

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

  • xt is the position displacement from the center position of the cart.

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

  • B is a flag (1 or 0) that indicates whether the cart is out of bounds.

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

Create Environment Interface

Create a predefined environment interface for the pole.

env = rlPredefinedEnv("CartPoleSimscapeModel-Continuous")
env = 
SimulinkEnvWithAgent with properties:

           Model : rlCartPoleSimscapeModel
      AgentBlock : rlCartPoleSimscapeModel/RL Agent
        ResetFcn : []
  UseFastRestart : on

The interface has a continuous action space where the agent can apply possible torque values from –15 to 15 N to the pole.

Obtain the observation and action information from the environment interface.

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

Specify the simulation time Tf and the agent sample time Ts in seconds.

Ts = 0.02;
Tf = 25;

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 neural network with two input layers (one for the 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). Note that prod(obsInfo.Dimension) and prod(actInfo.Dimension) return the number of dimensions of the observation and action spaces, respectively, regardless of whether they are arranged as row vectors, column vectors, or matrices.

Define the network as an array of layer objects. Assign names to the input and output layers of each path. 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 a deep neural network value function representation, see Create Policies and Value Functions.

% Define path for the observation input.
obsPath = [
    featureInputLayer(prod(obsInfo.Dimension),Name="obsInLayer")
    concatenationLayer(1,2,Name="cat")
    fullyConnectedLayer(128)
    reluLayer
    fullyConnectedLayer(200)
    reluLayer
    fullyConnectedLayer(1,Name="CriticOutput")
    ];

% Define path for the action input.
actPath = featureInputLayer(prod(actInfo.Dimension),Name="actInLayer");

Create dlnetwork object and add layers.

criticNetwork = addLayers(dlnetwork(),obsPath);
criticNetwork = addLayers(criticNetwork,actPath);

Connect paths and initialize network.

criticNetwork = connectLayers(criticNetwork,"actInLayer","cat/in2");
criticNetwork = initialize(criticNetwork);

Display the number of weights and plot the network configuration.

summary(criticNetwork)
   Initialized: true

   Number of learnables: 26.8k

   Inputs:
      1   'obsInLayer'   5 features
      2   'actInLayer'   1 features
plot(criticNetwork)

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

Create the critic using the specified deep neural network. You must also specify the action and observation information for the critic, which you already obtained from the environment interface. For more information, see rlQValueFunction.

critic = rlQValueFunction(criticNetwork, ...
    obsInfo,actInfo,...
    ObservationInputNames="obsInLayer", ...
    ActionInputNames="actInLayer");

DDPG agents use a parametrized deterministic policy over continuous action spaces, which is learned by a continuous deterministic actor. 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 one input layer (which receives the content of the environment observation channel, as specified by obsInfo) and one output layer (which returns the action to the environment action channel, as specified by actInfo).

Since the output of tanhLayer is limited between -1 and 1, scale the network output to the range of the action using scalingLayer.

actorNetwork = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(128)
    reluLayer
    fullyConnectedLayer(200)
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension))
    tanhLayer
    scalingLayer(Scale=max(actInfo.UpperLimit))
    ];

Convert to dlnetwork, initialize object and display the number of weights.

actorNetwork = dlnetwork(actorNetwork);
actorNetwork = initialize(actorNetwork);
summary(actorNetwork)
   Initialized: true

   Number of learnables: 26.7k

   Inputs:
      1   'input'   5 features

Create the actor in a similar manner to the critic. For more information, see rlContinuousDeterministicActor.

actor = rlContinuousDeterministicActor(actorNetwork,obsInfo,actInfo);

Specify training options for the critic and the actor using rlOptimizerOptions.

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

Specify the DDPG agent options using rlDDPGAgentOptions, and include the training options for the actor and critic.

agentOptions = rlDDPGAgentOptions(...
    SampleTime=Ts,...
    ActorOptimizerOptions=actorOptions,...
    CriticOptimizerOptions=criticOptions,...
    ExperienceBufferLength=1e5,...
    TargetSmoothFactor=5e-3,...
    MaxMiniBatchPerEpoch=200);

You can also modify the agent options using dot notation.

agentOptions.NoiseOptions.StandardDeviation = 1.0/sqrt(Ts);
agentOptions.NoiseOptions.MeanAttractionConstant = 0.1/Ts;

Alternatively, you can also create the agent first, and then access its option object and modify the options using dot notation.

Then, create the agent using the actor, critic and agent options objects. 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 episode for at most 2000 episodes, with each episode lasting at most ceil(Tf/Ts) time steps.

  • Display the training progress in the Reinforcement Learning Training Monitor dialog box (set the Plots option) and disable the command line display (set the Verbose option to false).

  • Stop training when the greedy policy evaluation exceeds –390. At this point, the agent can quickly balance the pole in the upright position using minimal control effort.

For more information, see rlTrainingOptions.

maxepisodes = 2000;
maxsteps = ceil(Tf/Ts);
trainingOptions = rlTrainingOptions(...
    MaxEpisodes=maxepisodes,...
    MaxStepsPerEpisode=maxsteps,...
    ScoreAveragingWindowLength=5,...
    Verbose=false,...
    Plots="training-progress",...
    StopTrainingCriteria="EvaluationStatistic",...
    StopTrainingValue=-390);

Train the agent using the train function. Training this agent process is computationally intensive and 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    
    % evaluate the greedy policy every 10 training episodes
    evaluator = rlEvaluator(NumEpisodes=1,EvaluationFrequency=10);
    % Train the agent.
    trainingStats = train(agent,env,trainingOptions,Evaluator=evaluator);
else
    % Load the pretrained agent for the example.
    load("SimscapeCartPoleDDPG.mat","agent")
end

Simulate DDPG Agent

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

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

bdclose(mdl)

See Also

Apps

Functions

Objects

Blocks

Related Examples

More About