Main Content

rlDDPGAgent

Deep deterministic policy gradient (DDPG) reinforcement learning agent

Description

The deep deterministic policy gradient (DDPG) algorithm is an actor-critic, model-free, online, off-policy reinforcement learning method which computes an optimal policy that maximizes the long-term reward. The action space can only be continuous.

For more information, see Deep Deterministic Policy Gradient (DDPG) Agents. For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.

Creation

Description

Create Agent from Observation and Action Specifications

example

agent = rlDDPGAgent(observationInfo,actionInfo) creates a deep deterministic policy gradient agent for an environment with the given observation and action specifications, using default initialization options. The actor and critic in the agent use default deep neural networks built from the observation specification observationInfo and the action specification actionInfo. The ObservationInfo and ActionInfo properties of agent are set to the observationInfo and actionInfo input arguments, respectively.

example

agent = rlDDPGAgent(observationInfo,actionInfo,initOpts) creates a deep deterministic policy gradient agent for an environment with the given observation and action specifications. The agent uses default networks configured using options specified in the initOpts object. For more information on the initialization options, see rlAgentInitializationOptions.

Create Agent from Actor and Critic

example

agent = rlDDPGAgent(actor,critic,agentOptions) creates a DDPG agent with the specified actor and critic, using default DDPG agent options.

Specify Agent Options

agent = rlDDPGAgent(___,agentOptions) creates a DDPG agent and sets the AgentOptions property to the agentOptions input argument. Use this syntax after any of the input arguments in the previous syntaxes.

Input Arguments

expand all

Agent initialization options, specified as an rlAgentInitializationOptions object.

Actor, specified as an rlContinuousDeterministicActor. For more information on creating actors, see Create Policies and Value Functions.

Critic, specified as an rlQValueFunction object. For more information on creating critics, see Create Policies and Value Functions.

Properties

expand all

Observation specifications, specified as a reinforcement learning specification object or an array of specification objects defining properties such as dimensions, data type, and names of the observation signals.

If you create the agent by specifying an actor and critic, the value of ObservationInfo matches the value specified in the actor and critic objects.

You can extract observationInfo from an existing environment or agent using getObservationInfo. You can also construct the specifications manually using rlFiniteSetSpec or rlNumericSpec.

Action specifications, specified as a reinforcement learning specification object defining properties such as dimensions, data type, and names of the action signals.

Since a DDPG agent operates in a continuous action space, you must specify actionInfo as an rlNumericSpec object.

If you create the agent by specifying an actor and critic, the value of ActionInfo matches the value specified in the actor and critic objects.

You can extract actionInfo from an existing environment or agent using getActionInfo. You can also construct the specification manually using rlNumericSpec.

Agent options, specified as an rlDDPGAgentOptions object.

If you create a DDPG agent with default actor and critic that use recurrent neural networks, the default value of AgentOptions.SequenceLength is 32.

Experience buffer, specified as an rlReplayMemory object. During training the agent stores each of its experiences (S,A,R,S',D) in a buffer. Here:

  • S is the current observation of the environment.

  • A is the action taken by the agent.

  • R is the reward for taking action A.

  • S' is the next observation after taking action A.

  • D is the is-done signal after taking action A.

Option to use exploration policy when selecting actions, specified as a one of the following logical values.

  • true — Use the base agent exploration policy when selecting actions.

  • false — Use the base agent greedy policy when selecting actions.

Sample time of agent, specified as a positive scalar or as -1. Setting this parameter to -1 allows for event-based simulations. The value of SampleTime matches the value specified in AgentOptions.

Within a Simulink® environment, the RL Agent block in which the agent is specified to execute every SampleTime seconds of simulation time. If SampleTime is -1, the block inherits the sample time from its parent subsystem.

Within a MATLAB® environment, the agent is executed every time the environment advances. In this case, SampleTime is the time interval between consecutive elements in the output experience returned by sim or train. If SampleTime is -1, the time interval between consecutive elements in the returned output experience reflects the timing of the event that triggers the agent execution.

Object Functions

trainTrain reinforcement learning agents within a specified environment
simSimulate trained reinforcement learning agents within specified environment
getActionObtain action from agent, actor, or policy object given environment observations
getActorGet actor from reinforcement learning agent
setActorSet actor of reinforcement learning agent
getCriticGet critic from reinforcement learning agent
setCriticSet critic of reinforcement learning agent
generatePolicyFunctionGenerate function that evaluates policy of an agent or policy object

Examples

collapse all

Create an environment with a continuous action space, and obtain its observation and action specifications. For this example, load the environment used in the example Train DDPG Agent to Control Double Integrator System. The observation from the environment is a vector containing the position and velocity of a mass. The action is a scalar representing a force, applied to the mass, ranging continuously from -2 to 2 Newton.

env = rlPredefinedEnv("DoubleIntegrator-Continuous");

Obtain observation and action specifications.

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

The agent creation function initializes the actor and critic networks randomly. Ensure reproducibility by fixing the seed of the random generator.

rng(0)

Create a policy gradient agent from the environment observation and action specifications.

agent = rlDDPGAgent(obsInfo,actInfo)
agent = 
  rlDDPGAgent with properties:

        ExperienceBuffer: [1x1 rl.replay.rlReplayMemory]
            AgentOptions: [1x1 rl.option.rlDDPGAgentOptions]
    UseExplorationPolicy: 0
         ObservationInfo: [1x1 rl.util.rlNumericSpec]
              ActionInfo: [1x1 rl.util.rlNumericSpec]
              SampleTime: 1

To check your agent, use getAction to return the action from a random observation.

getAction(agent,{rand(obsInfo(1).Dimension)})
ans = 1x1 cell array
    {[0.0182]}

You can now test and train the agent within the environment. You can also use getActor and getCritic to extract the actor and critic, respectively, and getModel to extract the approximator model (by default a deep neural network) from the actor or critic.

Create an environment with a continuous action space and obtain its observation and action specifications. For this example, load the environment used in the example Train DDPG Agent to Swing Up and Balance Pendulum with Image Observation. This environment has two observations: a 50-by-50 grayscale image and a scalar (the angular velocity of the pendulum). The action is a scalar representing a torque ranging continuously from -2 to 2 Nm.

env = rlPredefinedEnv("SimplePendulumWithImage-Continuous");

Obtain observation and action specifications

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

Create an agent initialization option object, specifying that each hidden fully connected layer in the network must have 128 neurons (instead of the default number, 256).

initOpts = rlAgentInitializationOptions('NumHiddenUnit',128);

The agent creation function initializes the actor and critic networks randomly. You can ensure reproducibility by fixing the seed of the random generator.

rng(0)

Create a DDPG agent from the environment observation and action specifications.

agent = rlDDPGAgent(obsInfo,actInfo,initOpts);

Extract the deep neural networks from both the agent actor and critic.

actorNet = getModel(getActor(agent));
criticNet = getModel(getCritic(agent));

Display the layers of the critic network, and verify that each hidden fully connected layer has 128 neurons

criticNet.Layers
ans = 
  13x1 Layer array with layers:

     1   'concat'         Concatenation     Concatenation of 3 inputs along dimension 1
     2   'relu_body'      ReLU              ReLU
     3   'fc_body'        Fully Connected   128 fully connected layer
     4   'body_output'    ReLU              ReLU
     5   'input_1'        Image Input       50x50x1 images
     6   'conv_1'         2-D Convolution   64 3x3x1 convolutions with stride [1  1] and padding [0  0  0  0]
     7   'relu_input_1'   ReLU              ReLU
     8   'fc_1'           Fully Connected   128 fully connected layer
     9   'input_2'        Feature Input     1 features
    10   'fc_2'           Fully Connected   128 fully connected layer
    11   'input_3'        Feature Input     1 features
    12   'fc_3'           Fully Connected   128 fully connected layer
    13   'output'         Fully Connected   1 fully connected layer

Plot actor and critic networks

plot(layerGraph(actorNet))

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

plot(layerGraph(criticNet))

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

To check your agent, use getAction to return the action from a random observation.

getAction(agent,{rand(obsInfo(1).Dimension),rand(obsInfo(2).Dimension)})
ans = 1x1 cell array
    {[-0.0364]}

You can now test and train the agent within the environment.

Create an environment with a continuous action space and obtain its observation and action specifications. For this example, load the environment used in the example Train DDPG Agent to Control Double Integrator System. The observation from the environment is a vector containing the position and velocity of a mass. The action is a scalar representing a force ranging continuously from -2 to 2 Newton.

env = rlPredefinedEnv("DoubleIntegrator-Continuous");

Obtain the environment observation and action specification objects.

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

The actor and critic networks are initialized randomly. Ensure reproducibility by fixing the seed of the random generator.

rng(0)

For DDPG agents, the critic estimates a Q-value function, therefore it must take both the observation and action signals as inputs and return a scalar value.

To approximate the Q-value function within the critic, use a deep neural network. Define each network path as an array of layer objects. Get the dimensions of the observation and action spaces from the environment specification objects, and specify a name for the input layers, so you can later explicitly associate them with the appropriate environment channel.

% Define observation and action paths
obsPath = featureInputLayer(prod(obsInfo.Dimension),Name="netOin");
actPath = featureInputLayer(prod(actInfo.Dimension),Name="netAin");

% Define common path: concatenate along first dimension
commonPath = [concatenationLayer(1,2,Name="concat")
              fullyConnectedLayer(50)
              reluLayer
              fullyConnectedLayer(1)];

% Add paths to layerGraph network
cNet = layerGraph(obsPath);
cNet = addLayers(cNet, actPath);
cNet = addLayers(cNet, commonPath);

% Connect paths
cNet = connectLayers(cNet,"netOin","concat/in1");
cNet = connectLayers(cNet,"netAin","concat/in2");

% Plot the network
plot(cNet)

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

% Convert to dlnetwork object
cNet = dlnetwork(cNet);

% Display the number of weights
summary(cNet)
   Initialized: true

   Number of learnables: 251

   Inputs:
      1   'netOin'   2 features
      2   'netAin'   1 features

Create the critic using cNet, and the names of the input layers. DDPG agents use an rlQValueFunction object to implement the critic.

critic = rlQValueFunction(cNet,obsInfo,actInfo,...
    ObservationInputNames="netOin", ...
    ActionInputNames="netAin");

Check the critic with random observation and action inputs.

getValue(critic,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
    -0.4260

To approximate the policy within the actor, use a neural network. For DDPG agents, the actor executes a deterministic policy, which is implemented by a continuous deterministic actor. In this case the network must take the observation signal as input and return an action. Therefore the output layer must have as many elements as the number of possible actions.

% create a network to be used as underlying actor approximator
aNet = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(50)
    reluLayer
    fullyConnectedLayer(numel(actInfo))];

% Convert to dlnetwork object
aNet = dlnetwork(aNet);

% Display the number of weights
summary(aNet)
   Initialized: true

   Number of learnables: 201

   Inputs:
      1   'input'   2 features

Create the actor using actorNetwork. DDPG agents use an rlContinuousDeterministicActor object to implement the actor.

actor = rlContinuousDeterministicActor(aNet,obsInfo,actInfo);

Check the actor with a random observation input.

getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
    {[-0.2327]}

Create the DDPG agent using the actor and critic.

agent = rlDDPGAgent(actor,critic);

Specify agent options, including training options for the actor and critic.

agent.AgentOptions.SampleTime=env.Ts;
agent.AgentOptions.TargetSmoothFactor=1e-3;
agent.AgentOptions.ExperienceBufferLength=1e6;
agent.AgentOptions.DiscountFactor=0.99;
agent.AgentOptions.MiniBatchSize=32;

agent.AgentOptions.CriticOptimizerOptions.LearnRate=5e-3;
agent.AgentOptions.CriticOptimizerOptions.GradientThreshold=1;

agent.AgentOptions.ActorOptimizerOptions.LearnRate=1e-4;
agent.AgentOptions.ActorOptimizerOptions.GradientThreshold=1;

Check the agent with a random observation input.

getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
    {[-0.1666]}

You can now train the agent within the environment.

For this example, load the environment used in the example Train DDPG Agent to Control Double Integrator System. The observation from the environment is a vector containing the position and velocity of a mass. The action is a scalar representing a force ranging continuously from -2 to 2 Newton.

env = rlPredefinedEnv("DoubleIntegrator-Continuous");

Get the observation and action specification objects.

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

For DDPG agents, the critic estimates a Q-value function, therefore it must take both the observation and action signals as inputs and return a scalar value.

To approximate the Q-value function within the critic, use a recurrent neural network. Define each network path as an array of layer objects. Get the dimensions of the observation spaces from the environment specification object, and specify a name for the input layers, so you can later explicitly associate them with the correct environment channel. To create a recurrent neural network, use sequenceInputLayer as the input layer and include an lstmLayer as one of the other network layers.

% Define observation and action paths
obsPath = sequenceInputLayer(prod(obsInfo.Dimension),Name="netOin");
actPath = sequenceInputLayer(prod(actInfo.Dimension),Name="netAin");

% Define common path: concatenate along first dimension
commonPath = [concatenationLayer(1,2,Name="cat")
              lstmLayer(50)
              reluLayer
              fullyConnectedLayer(1)];

% Add paths to layerGraph network
cNet = layerGraph(obsPath);
cNet = addLayers(cNet, actPath);
cNet = addLayers(cNet, commonPath);

% Connect paths
cNet = connectLayers(cNet,"netOin","cat/in1");
cNet = connectLayers(cNet,"netAin","cat/in2");

% Plot the network
plot(cNet)

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

% Convert to dlnetwork object
cNet = dlnetwork(cNet);

% Display the number of weights
summary(cNet)
   Initialized: true

   Number of learnables: 10.8k

   Inputs:
      1   'netOin'   Sequence input with 2 dimensions
      2   'netAin'   Sequence input with 1 dimensions

Create the critic using cNet, specifying the names of the input layers. DDPG agents use an rlQValueFunction object to implement the critic.

critic = rlQValueFunction(cNet,obsInfo,actInfo,...
    ObservationInputNames="netOin",ActionInputNames="netAin");

Check the critic with random observation and action inputs.

getValue(critic,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
    -0.0074

Since the critic has a recurrent network, the actor must have a recurrent network too. For DDPG agents, the actor executes a deterministic policy, which is implemented by a continuous deterministic actor. In this case the network must take the observation signal as input and return an action. Therefore the output layer must have as many elements as the number of possible actions.

Define the network as an array of layer objects, and get the dimensions of the observation and action spaces from the environment specification objects.

aNet = [
    sequenceInputLayer(prod(obsInfo.Dimension))
    lstmLayer(10)
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension)) ];

Convert to dlnetwork and display the number of weights.

aNet = dlnetwork(aNet);
summary(aNet)
   Initialized: true

   Number of learnables: 531

   Inputs:
      1   'sequenceinput'   Sequence input with 2 dimensions

Create the actor using aNet. DDPG agents use an rlContinuousDeterministicActor object to implement the actor.

actor = rlContinuousDeterministicActor(aNet,obsInfo,actInfo);

Check the actor with random observation input.

getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
    {[0.0246]}

Specify some training options for the critic.

criticOpts = rlOptimizerOptions( ...
    'LearnRate',5e-3,'GradientThreshold',1);

Specify some training options for the actor.

actorOpts = rlOptimizerOptions( ...
    'LearnRate',1e-4,'GradientThreshold',1);

Specify agent options. To use a DDPG agent with recurrent neural networks, you must specify a SequenceLength greater than 1.

agentOpts = rlDDPGAgentOptions(...
    'SampleTime',env.Ts,...
    'TargetSmoothFactor',1e-3,...
    'ExperienceBufferLength',1e6,...
    'DiscountFactor',0.99,...
    'SequenceLength',20,...
    'MiniBatchSize',32, ...
    'CriticOptimizerOptions',criticOpts, ...
    'ActorOptimizerOptions',actorOpts);

Create the DDPG agent using the actor and critic.

agent = rlDDPGAgent(actor,critic,agentOpts);

To check your agent return the action from a random observation.

getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
    {[0.0158]}

You can now test and train the agent within the environment.

Version History

Introduced in R2019a