Documentation

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

Simple Pendulum with Image MATLAB Environment

The reinforcement learning environment for this example is a simple frictionless pendulum that is initially hanging 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 Nm

• The observations from the environment are an image indicating the location of the pendulum's 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)$

where:

• ${\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

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

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

A DDPG agent approximates the long-term reward given observations and actions using a critic value function representation. To create the critic, first create a deep convolutional neural network (CNN) with three inputs (the image, angular velocity, and action) and one output. For more information on creating representations, see Create Policy and Value Function Representations.

hiddenLayerSize1 = 400;
hiddenLayerSize2 = 300;

imgPath = [
imageInputLayer(obsInfo(1).Dimension,'Normalization','none','Name',obsInfo(1).Name)
reluLayer('Name','relu1')
fullyConnectedLayer(2,'Name','fc1')
concatenationLayer(3,2,'Name','cat1')
fullyConnectedLayer(hiddenLayerSize1,'Name','fc2')
reluLayer('Name','relu2')
fullyConnectedLayer(hiddenLayerSize2,'Name','fc3')
reluLayer('Name','relu3')
fullyConnectedLayer(1,'Name','fc4')
];
dthetaPath = [
imageInputLayer(obsInfo(2).Dimension,'Normalization','none','Name',obsInfo(2).Name)
fullyConnectedLayer(1,'Name','fc5','BiasLearnRateFactor',0,'Bias',0)
];
actPath =[
imageInputLayer(actInfo(1).Dimension,'Normalization','none','Name','action')
fullyConnectedLayer(hiddenLayerSize2,'Name','fc6','BiasLearnRateFactor',0,'Bias',zeros(hiddenLayerSize2,1))
];

criticNetwork = layerGraph(imgPath);
criticNetwork = connectLayers(criticNetwork,'fc5','cat1/in2');

View the critic network configuration.

figure
plot(criticNetwork) Specify options for the critic representation using rlRepresentationOptions.

Uncomment the following line to use the GPU to accelerate training of the CNN.

% criticOptions.UseDevice = 'gpu';

Create the critic representation using the specified neural network and options. You must also specify the action and observation info for the critic, which you obtain from the environment interface. For more information, see rlRepresentation.

critic = rlRepresentation(criticNetwork,obsInfo,actInfo,...
'Observation',{'pendImage','angularRate'},'Action',{'action'},criticOptions);

A DDPG agent decides which action to take given observations using an actor representation. To create the actor, first create a deep convolutional neural network (CNN) with two inputs (the image and angular velocity) and one output (the action).

Construct the actor in a similar manner to the critic.

imgPath = [
imageInputLayer(obsInfo(1).Dimension,'Normalization','none','Name',obsInfo(1).Name)
reluLayer('Name','relu1')
fullyConnectedLayer(2,'Name','fc1')
concatenationLayer(3,2,'Name','cat1')
fullyConnectedLayer(hiddenLayerSize1,'Name','fc2')
reluLayer('Name','relu2')
fullyConnectedLayer(hiddenLayerSize2,'Name','fc3')
reluLayer('Name','relu3')
fullyConnectedLayer(1,'Name','fc4')
tanhLayer('Name','tanh1')
scalingLayer('Name','scale1','Scale',max(actInfo.UpperLimit))
];
dthetaPath = [
imageInputLayer(obsInfo(2).Dimension,'Normalization','none','Name',obsInfo(2).Name)
fullyConnectedLayer(1,'Name','fc5','BiasLearnRateFactor',0,'Bias',0)
];

actorNetwork = layerGraph(imgPath);
actorNetwork = connectLayers(actorNetwork,'fc5','cat1/in2');

Uncomment the following line to use the GPU to accelerate training of the CNN.

% criticOptions.UseDevice = 'gpu';

Create the actor representation using the specified neural network and options.

actor = rlRepresentation(actorNetwork,obsInfo,actInfo,'Observation',{'pendImage','angularRate'},'Action',{'scale1'},actorOptions);

View the actor network configuration.

figure
plot(actorNetwork) To create the DDPG agent, first specify the DDPG agent options using rlDDPGAgentOptions.

agentOptions = rlDDPGAgentOptions(...
'SampleTime',env.Ts,...
'TargetSmoothFactor',1e-3,...
'ExperienceBufferLength',1e6,...
'DiscountFactor',0.99,...
'MiniBatchSize',128);
agentOptions.NoiseOptions.Variance = 0.6;
agentOptions.NoiseOptions.VarianceDecayRate = 1e-6;

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 500 time steps.

• Display the training progress at the command line (set the Verbose option) and in the Episode Manager dialog box (set the Plots option).

• Stop training when the agent receives an average cumulative reward greater than -1000 over five 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);

The pendulum system can be visualized with plot during training or simulation.

plot(env) Train the agent using the train function. This 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);  