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) Agent. For an example showing how to train a DDPG agent in MATLAB®, see Compare DDPG Agent to LQR Controller.
The example code might involve computation of random numbers at various stages. Fixing the random number stream at the beginning of various sections in the example code preserves the random number sequence in the section every time you run it, and increases the likelihood of reproducing the results. For more information, see Results Reproducibility.
Fix Random Number Stream for Reproducibility
The example code might involve computation of random numbers at various stages. Fixing the random number stream preserves the sequence of the random numbers every time you run the code and improves the likelihood to reproduce the results. You will fix the random number stream at various locations in the example. Fix the random number stream with seed 0
, using the Mersenne Twister random number algorithm. For more information on controlling the seed used for random number generation, see rng
.
previousRngState = rng(0,"twister");
The output previousRngState
is a structure that contains information about the previous state of the stream. You will restore the state at the end of the example.
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 using minimal control effort.
Open the model.
mdl = "rlCartPoleSimscapeModel";
open_system(mdl)
The cart-pole system is modeled using Simscape Multibody.
In this model:
The upright pole angle is
0
radians, and the downward hanging pendulum position ispi
radians.The force (rightward-positive) 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 , provided at every time step, is
Here:
is the angle of displacement from the upright position of the pole (counterclockwise-positive).
is the position displacement from the center position of the cart (rightward-positive).
is the control effort from the previous time step.
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 Object
Create a predefined environment object for the pole.
env = rlPredefinedEnv("CartPoleSimscapeModel-Continuous")
env = SimulinkEnvWithAgent with properties: Model : rlCartPoleSimscapeModel AgentBlock : rlCartPoleSimscapeModel/RL Agent ResetFcn : [] UseFastRestart : on
The environment has a continuous action space where the agent can apply an horizontal force (from –15 to 15 N) to the cart.
Obtain the observation and action information from the environment object.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
Specify the agent sample time Ts
and the simulation time Tf
in seconds.
Ts = 0.02; Tf = 25;
Create DDPG Agent
You will create and train a DDPG agent in this example. The agent uses:
A Q-value function critic to estimate the value of the policy. The critic takes the current observation and an action as inputs and returns a single scalar as output (the estimated discounted cumulative long-term reward given the action from the state corresponding to the current observation, and following the policy thereafter).
A deterministic policy over a continuous action space, 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.
The actor and critic functions are approximated using neural network representations. Create an agent initialization object to initialize the networks with the hidden layer size 200.
initOpts = rlAgentInitializationOptions(NumHiddenUnit=200);
Configure the hyperparameters for training using rlDDPGAgentOptions
.
Specify the actor and critic learning rates as 5e-3. A large learning rate causes drastic updates which may lead to divergent behaviors, while a low value may require many updates before reaching the optimal point.
Specify a gradient threshold value of 1. Clipping the gradient improves learning stability.
Specify the experience buffer capcity to be 1e5. A large capacity enables storing a diverse set of experiences.
Specify a smoothing factor of 5e-3 to update the target critic network.
Specify the sample time of the agent as
Ts
.Learn with a maximum of 200 mini batches per training epoch.
criticOptions = rlOptimizerOptions( ... LearnRate=5e-03, ... GradientThreshold=1); actorOptions = rlOptimizerOptions( ... LearnRate=5e-03, ... GradientThreshold=1); agentOptions = rlDDPGAgentOptions(... SampleTime=Ts,... ActorOptimizerOptions=actorOptions,... CriticOptimizerOptions=criticOptions,... ExperienceBufferLength=1e5,... TargetSmoothFactor=5e-3,... MaxMiniBatchPerEpoch=200);
Alternatively, you can also create the agent first, and then access its option object and modify the options using dot notation.
The DDPG agent in this example uses an Ornstein-Uhlenbeck (OU) noise model for exploration. Specify the following noise options using dot notation:
Specify a mean attraction value of . A larger mean attraction value keeps the noise values close to the mean.
Specify a standard deviation value of to improve exploration during training.
agentOptions.NoiseOptions.StandardDeviation = 1.0/sqrt(Ts); agentOptions.NoiseOptions.MeanAttractionConstant = 0.1/Ts;
Fix the random stream for reproducibility.
rng(0,"twister");
Then, create the agent using the input specification and agent options objects. For more information, see rlDDPGAgent
.
agent = rlDDPGAgent(obsInfo,actInfo,initOpts,agentOptions);
Train Agent
To train the agent, first specify the training options. For this example, use the following options.
Run each training episode for a maximum of 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 theVerbose
option tofalse
).Evaluate the performance of the greedy policy by running 1 simulation every 10 training episodes.
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 on training options, see rlTrainingOptions
and rlEvaluator
.
% training options maxepisodes = 2000; maxsteps = ceil(Tf/Ts); trainingOptions = rlTrainingOptions(... MaxEpisodes=maxepisodes,... MaxStepsPerEpisode=maxsteps,... ScoreAveragingWindowLength=5,... Verbose=false,... Plots="training-progress",... StopTrainingCriteria="EvaluationStatistic",... StopTrainingValue=-390); % agent evaluation evl = rlEvaluator(NumEpisodes=1,EvaluationFrequency=10);
Fix the random stream for reproducibility.
rng(0,"twister");
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 % Train the agent. trainingStats = train(agent,env,trainingOptions,Evaluator=evl); else % Load the pretrained agent for the example. load("SimscapeCartPoleDDPG.mat","agent") end
A snapshot of training progress is shown in the figure below. You can expect different results due to randomness in the training process.
Simulate DDPG Agent
Fix the random stream for reproducibility.
rng(0,"twister");
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);
Restore the random number stream using the information stored in previousRngState
.
rng(previousRngState);
See Also
Apps
Functions
train
|sim
|rlSimulinkEnv
Objects
rlDDPGAgent
|rlDDPGAgentOptions
|rlQValueFunction
|rlContinuousDeterministicActor
|rlTrainingOptions
|rlSimulationOptions
|rlOptimizerOptions
Blocks
Topics
- Train PG Agent to Balance Discrete Cart-Pole System
- Train DDPG Agent to Swing Up and Balance Pendulum with Bus Signal
- Train DDPG Agent to Swing Up and Balance Pendulum with Image Observation
- Create Policies and Value Functions
- Deep Deterministic Policy Gradient (DDPG) Agent
- Train Reinforcement Learning Agents