Main Content

rlTD3Agent

Twin-delayed deep deterministic (TD3) policy gradient reinforcement learning agent

Since R2020a

Description

The twin-delayed deep deterministic (TD3) policy gradient algorithm is an off-policy actor-critic method for environments with a continuous action-space. A TD3 agent learns a deterministic policy while also using two critics to estimate the value of the optimal policy. It features a target actor and target critics as well as an experience buffer. TD3 agents supports offline training (training from saved data, without an environment).

Use rlTD3Agent to create one of the following types of agents.

  • Twin-delayed deep deterministic policy gradient (TD3) agent with two Q-value functions. This agent prevents overestimation of the value function by learning two Q value functions and using the minimum values for policy updates.

  • Delayed deep deterministic policy gradient (delayed DDPG) agent with a single Q value function. This agent is a DDPG agent with target policy smoothing and delayed policy and target updates.

For more information, see Twin-Delayed Deep Deterministic (TD3) Policy Gradient Agent. For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.

Creation

Description

Create Agent from Observation and Action Specifications

agent = rlTD3Agent(observationInfo,actionInfo) creates a TD3 agent for an environment with the given observation and action specifications, using default initialization options. The actor and critics 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 = rlTD3Agent(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.

example

Create Agent from Actor and Critic

agent = rlTD3Agent(actor,critics,agentOptions) creates an agent with the specified actor and critic. To create a:

  • TD3 agent, specify a two-element row vector of critic.

  • Delayed DDPG agent, specify a single critic.

example

Specify Agent Options

agent = rlTD3Agent(___,agentOptions) creates a TD3 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 one of the following:

  • rlQValueFunction object — Create a delayed DDPG agent with a single Q value function. This agent is a DDPG agent with target policy smoothing and delayed policy and target updates.

  • Two-element row vector of rlQValueFunction objects — Create a TD3 agent with two critic value functions. The two critic networks must be unique rlQValueFunction objects with the same observation and action specifications. The critics can either have different structures or the same structure but with different initial parameters.

For more information on creating critics, see Create Policies and Value Functions.

Properties

expand all

Observation specifications, specified as an rlFiniteSetSpec or rlNumericSpec object or an array containing a mix of such objects. Each element in the array defines the properties of an environment observation channel, such as its dimensions, data type, and name.

If you create the agent by specifying an actor or critic, the value of ObservationInfo matches the value specified in the actor and critic objects. If you create a default agent, the agent constructor function sets the ObservationInfo property to the input argument observationInfo.

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

Example: [rlNumericSpec([2 1]) rlFiniteSetSpec([3,5,7])]

Action specifications, specified as an rlNumericSpec object. This object defines the properties of the environment action channel, such as its dimensions, data type, and name.

Note

For this agent, only one action channel is allowed.

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. If you create a default agent, the agent constructor function sets the ActionInfo property to the input argument ActionInfo.

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

Example: rlNumericSpec([2 1])

Agent options, specified as an rlTD3AgentOptions object.

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

Option to use exploration policy when selecting actions during simulation or after deployment, specified as a one of the following logical values.

  • true — Use the base agent exploration policy when selecting actions in sim and generatePolicyFunction. Specifically, in this case the agent uses the rlAdditiveNoisePolicy. Since the action selection has a random component, the agent explores its action and observation spaces.

  • false — Force the agent to use the base agent greedy policy (the action with maximum likelihood) when selecting actions in sim and generatePolicyFunction. Specifically, in this case the agent uses the rlDeterministicActorPolicy policy. Since the action selection is greedy the policy behaves deterministically and the agent does not explore its action and observation spaces.

Note

This option affects only simulation and deployment; it does not affect training. When you train an agent using train, the agent always uses its exploration policy independently of the value of this property.

Experience buffer, specified as one of the following replay memory objects.

Note

Agents with recursive neural networks only support rlReplayMemory and rlHindsightReplayMemory buffers.

During training the agent stores each of its experiences (S,A,R,S',D) in the 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.

The agent then samples mini-batches of experiences from the buffer and uses these mini-batches to update its actor and critic function approximators.

Sample time of the agent, specified as a positive scalar or as -1.

Within a MATLAB® environment, the agent is executed every time the environment advances, so, SampleTime does not affect the timing of the agent execution.

Within a Simulink® environment, the RL Agent block that uses the agent object executes every SampleTime seconds of simulation time. If SampleTime is -1 the block inherits the sample time from its input signals. Set SampleTime to -1 when the block is a child of an event-driven subsystem.

Note

Set SampleTime to a positive scalar when the block is not a child of an event-driven subsystem. Doing so ensures that the block executes at appropriate intervals when input signal sample times change due to model variations.

Regardless of the type of environment, the time interval between consecutive elements in the output experience returned by sim or train is always SampleTime.

If SampleTime is -1, for Simulink environments, the time interval between consecutive elements in the returned output experience reflects the timing of the events that trigger the RL Agent block execution, while for MATLAB environments, this time interval is considered equal to 1.

This property is shared between the agent and the agent options object within the agent. Therefore, if you change it in the agent options object, it gets changed in the agent, and vice versa.

Example: SampleTime=-1

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
getActorExtract actor from reinforcement learning agent
setActorSet actor of reinforcement learning agent
getCriticExtract critic from reinforcement learning agent
setCriticSet critic of reinforcement learning agent
generatePolicyFunctionGenerate MATLAB 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 Compare DDPG Agent to LQR Controller. 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");

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 TD3 agent from the environment observation and action specifications.

agent = rlTD3Agent(obsInfo,actInfo);

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

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

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.

% Load predefined environment
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. Ensure reproducibility by fixing the seed of the random generator.

rng(0)

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

agent = rlTD3Agent(obsInfo,actInfo,initOpts);

Extract the deep neural networks from the actor.

actorNet = getModel(getActor(agent));

Extract the deep neural networks from the two critics. Note that getModel(critics) only returns the first critic network.

critics = getCritic(agent);
criticNet1 = getModel(critics(1));
criticNet2 = getModel(critics(2));

To verify that each hidden fully connected layer has 128 neurons, you can display the layers on the MATLAB® command window,

criticNet1.Layers

or visualize the structure interactively using analyzeNetwork.

analyzeNetwork(criticNet1)

Plot the networks of the actor and of the second critic, and display the number of weights.

plot(actorNet)

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

summary(actorNet)
   Initialized: true

   Number of learnables: 18.9M

   Inputs:
      1   'input_1'   50x50x1 images
      2   'input_2'   1 features
plot(criticNet2)

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

summary(criticNet2)
   Initialized: true

   Number of learnables: 18.9M

   Inputs:
      1   'input_1'   50x50x1 images
      2   'input_2'   1 features
      3   'input_3'   1 features

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.0675]}

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 Compare DDPG Agent to LQR Controller. 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");
obsInfo = getObservationInfo(env);
actInfo = getActionInfo(env);

TD3 agents use two Q-value function critics. 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 taking the action from the state corresponding to the current observation, and following the policy thereafter).

To model the parametrized Q-value function within the critics, 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 each network path as an array of layer objects. Assign names to the input and output layers of each path, so you can connect them.

% Observation path
obsPath = [
    featureInputLayer(prod(obsInfo.Dimension),Name="obsPathInLyr")
    fullyConnectedLayer(32)
    reluLayer
    fullyConnectedLayer(16,Name="obsPathOutLyr")
    ];

% Action path
actPath = [
    featureInputLayer(prod(actInfo.Dimension),Name="actPathInLyr")
    fullyConnectedLayer(32)
    reluLayer
    fullyConnectedLayer(16,Name="actPathOutLyr")
    ];

% Common path
commonPath = [
    concatenationLayer(1,2,Name="concat")
    reluLayer
    fullyConnectedLayer(1)
    ];

% Create dlnetwork object and add layers.
criticNet = dlnetwork;
criticNet = addLayers(criticNet,obsPath);
criticNet = addLayers(criticNet,actPath);
criticNet = addLayers(criticNet,commonPath);

% Connect layers
criticNet = connectLayers(criticNet,"obsPathOutLyr","concat/in1");
criticNet = connectLayers(criticNet,"actPathOutLyr","concat/in2");

To initialize the network weights differently for the two critics, create two different dlnetwork objects. You must do this because the agent constructor function does not accept two identical critics.

criticNet1 = initialize(criticNet);
criticNet2 = initialize(criticNet);

Display the number of weights.

summary(criticNet1)
   Initialized: true

   Number of learnables: 1.2k

   Inputs:
      1   'obsPathInLyr'   2 features
      2   'actPathInLyr'   1 features

Create the two critics using the two networks with different weights. Alternatively, if you use exactly the same network with the same weights, you must explicitly initialize the network each time (to make sure weights are initialized differently) before passing it to rlQValueFunction. To do so, use initialize.

critic1 = rlQValueFunction(criticNet1,obsInfo,actInfo);
critic2 = rlQValueFunction(criticNet2,obsInfo,actInfo);

For more information about Q-value function approximators, using rlQValueFunction.

Check the critics with a random observation and action input.

getValue(critic1,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single

-0.1330
getValue(critic2,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single

-0.1526

TD3 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).

Define the network as an array of layer objects.

actorNet = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(400)
    reluLayer
    fullyConnectedLayer(300)
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension))                       
    tanhLayer
];

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

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

   Number of learnables: 121.8k

   Inputs:
      1   'input'   2 features

Create the actor using actorNet, and the environment specification objects.

actor  = rlContinuousDeterministicActor(actorNet,obsInfo,actInfo);

For more information about continuous deterministic actor approximators, see rlContinuousDeterministicActor.

Check the actor with a random observation input.

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

Specify training options for the critics.

criticOptions = rlOptimizerOptions( ...
    Optimizer="adam", ...
    LearnRate=1e-3,... 
    GradientThreshold=1, ...
    L2RegularizationFactor=2e-4);

Specify training options for the actor.

actorOptions = rlOptimizerOptions( ...
    Optimizer="adam", ...
    LearnRate=1e-3,...
    GradientThreshold=1, ...
    L2RegularizationFactor=1e-5);

Specify agent options, including training options for actor and critics.

agentOptions = rlTD3AgentOptions;
agentOptions.DiscountFactor = 0.99;
agentOptions.TargetSmoothFactor = 5e-3;
agentOptions.TargetPolicySmoothModel.Variance = 0.2;
agentOptions.TargetPolicySmoothModel.LowerLimit = -0.5;
agentOptions.TargetPolicySmoothModel.UpperLimit = 0.5;
agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;

Create TD3 agent using actor, critics, and options.

agent = rlTD3Agent(actor,[critic1 critic2],agentOptions);

You can also create an rlTD3Agent object with a single critic. In this case, the object represents a DDPG agent with target policy smoothing and delayed policy and target updates.

delayedDDPGAgent = rlTD3Agent(actor,critic1,agentOptions);

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

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

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

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

For this example, load the environment used in the example Compare DDPG Agent to LQR Controller. 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 observation and action specifications.

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

TD3 agents use two Q-value function critics. To model the parametrized Q-value function within the critics, use a recurrent 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).

Define each network path as an array of layer objects. To create a recurrent network, use a sequenceInputLayer as the input layer and include at least one lstmLayer.

% Define observation path.
obsPath = [
    sequenceInputLayer(prod(obsInfo.Dimension),Name="obsInLyr")
    fullyConnectedLayer(400)
    reluLayer
    fullyConnectedLayer(300,Name="obsOutLyr")
    ];

% Define action path.
actPath = [
    sequenceInputLayer(prod(actInfo.Dimension),Name="actInLyr")
    fullyConnectedLayer(300,Name="actOutLyr")
    ];

% Define common path.
commonPath = [
    concatenationLayer(1,2,Name="cat")
    reluLayer
    lstmLayer(16);
    fullyConnectedLayer(1)
    ];

% Create dlnetwork object and add layers.
criticNet = dlnetwork;
criticNet = addLayers(criticNet,obsPath);
criticNet = addLayers(criticNet,actPath);
criticNet = addLayers(criticNet,commonPath);

% Connect paths.
criticNet = connectLayers(criticNet,"obsOutLyr","cat/in1");
criticNet = connectLayers(criticNet,"actOutLyr","cat/in2");

To initialize the network weights differently for the two critics, create two different dlnetwork objects. You must do this because the agent constructor function does not accept two identical critics.

criticNet1 = initialize(criticNet);
criticNet2 = initialize(criticNet);

Display the number of weights.

summary(criticNet1)
   Initialized: true

   Number of learnables: 161.6k

   Inputs:
      1   'obsInLyr'   Sequence input with 2 dimensions
      2   'actInLyr'   Sequence input with 1 dimensions

Create the critics using the same network structure. The TD3 agent initializes the two networks using different default parameters.

critic1 = rlQValueFunction(criticNet1,obsInfo,actInfo);
critic2 = rlQValueFunction(criticNet2,obsInfo,actInfo);

Check the critics with a random observation and action input.

getValue(critic1,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single

-0.0060
getValue(critic2,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single

0.0481

Since the critics have a recurrent network, the (continuous deterministic) actor must have a recurrent network as approximation model too. The network that models the parametrized policy, must take the observation and return the action.

Define the network as an array of layer objects.

actorNet = [
    sequenceInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(400)
    lstmLayer(8)
    reluLayer
    fullyConnectedLayer(300)
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension))                       
    tanhLayer
    ];

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

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

   Number of learnables: 17.2k

   Inputs:
      1   'sequenceinput'   Sequence input with 2 dimensions

Create the actor using actorNet, and the environment specification objects.

actor  = rlContinuousDeterministicActor(actorNet,obsInfo,actInfo);

Check the actor with a random observation input.

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

Specify training options for the critics.

criticOptions = rlOptimizerOptions( ...
    Optimizer="adam", ...
    LearnRate=1e-3,... 
    GradientThreshold=1, ...
    L2RegularizationFactor=2e-4);

Specify training options for the actor.

actorOptions = rlOptimizerOptions( ...
    Optimizer="adam", ...
    LearnRate=1e-3,...
    GradientThreshold=1, ...
    L2RegularizationFactor=1e-5);

Specify agent options, including training options for actor and critics. To use a TD3 agent with recurrent neural networks, you must specify a SequenceLength greater than 1.

agentOptions = rlTD3AgentOptions;
agentOptions.DiscountFactor = 0.99;
agentOptions.SequenceLength = 32;
agentOptions.TargetSmoothFactor = 5e-3;
agentOptions.TargetPolicySmoothModel.Variance = 0.2;
agentOptions.TargetPolicySmoothModel.LowerLimit = -0.5;
agentOptions.TargetPolicySmoothModel.UpperLimit = 0.5;
agentOptions.CriticOptimizerOptions = criticOptions;
agentOptions.ActorOptimizerOptions = actorOptions;

Create TD3 agent using actor, critics, and options.

agent = rlTD3Agent(actor,[critic1 critic2],agentOptions);

You can also create an rlTD3Agent object with a single critic. In this case, the object represents a DDPG agent with target policy smoothing and delayed policy and target updates.

delayedDDPGAgent = rlTD3Agent(actor,critic1,agentOptions);

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

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

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

To evaluate the agent using sequential observations, use the sequence length (time) dimension. For example, obtain actions for a sequence of 9 observations.

[action,state] = getAction(agent, ...
    {rand([obsInfo.Dimension 1 9])});

Display the action corresponding to the seventh element of the observation.

action = action{1};
action(1,1,1,7)
ans = 
-0.0034

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

Version History

Introduced in R2020a