Main Content

rlTRPOAgent

Trust region policy optimization reinforcement learning agent

Description

Trust region policy optimization (TRPO) is a model-free, online, on-policy, policy gradient reinforcement learning method. This algorithm prevents significant performance drops compared to standard policy gradient methods by keeping the updated policy within a trust region close to the current policy. The action space can be either discrete or continuous.

For more information on TRPO agents, see Trust Region Policy Optimization 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 = rlTRPOAgent(observationInfo,actionInfo) creates a trust region policy optimization (TRPO) 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 = rlTRPOAgent(observationInfo,actionInfo,initOpts) creates a TRPO agent for an environment with the given observation and action specifications. The agent uses default networks configured using options specified in the initOpts object. TRPO agents do not support recurrent neural networks. For more information on the initialization options, see rlAgentInitializationOptions.

Create Agent from Actor and Critic

example

agent = rlTRPOAgent(actor,critic) creates a TRPO agent with the specified actor and critic, using the default options for the agent.

Specify Agent Options

example

agent = rlTRPOAgent(___,agentOptions) creates a TRPO 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.

TRPO agents do not support recurrent neural networks. Therefore initOpts.UseRNNmust be false.

Actor that implements the policy, specified as an rlDiscreteCategoricalActor or rlContinuousGaussianActor function approximator object. For more information on creating actor approximators, see Create Policies and Value Functions.

Critic that estimates the discounted long-term reward, specified as an rlValueFunction object. For more information on creating critic approximators, 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.

For a discrete action space, you must specify actionInfo as an rlFiniteSetSpec object.

For 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 rlFiniteSetSpec or rlNumericSpec.

Agent options, specified as an rlTRPOAgentOptions object.

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 in sim and generatePolicyFunction. In this case, the agent selects its actions by sampling its probability distribution, the policy is therefore stochastic and the agent explores its observation space.

  • false — Use the base agent greedy policy (the action with maximum likelihood) when selecting actions in sim and generatePolicyFunction. In this case, the simulated agent and generated policy behave deterministically.

Note

This option affects only simulation and deployment; it does not affect training.

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 discrete action space, and obtain its observation and action specifications. For this example, load the environment used in the example Create Agent Using Deep Network Designer and Train Using Image Observations. 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 with five possible elements (a torque of either -2, -1, 0, 1, or 2 Nm applied to a swinging pole).

% load predefined environment
env = rlPredefinedEnv("SimplePendulumWithImage-Discrete");

Obtain the observation and action specifications for this environment.

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

The agent creation function initializes the actor and critic networks randomly. You can ensure reproducibility by fixing the seed of the random generator. To do so, uncomment the following line.

% rng(0)

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

agent = rlTRPOAgent(obsInfo,actInfo);

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
    {[-2]}

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 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 for this environment.

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

Create an agent initialization options object, specifying that each hidden fully connected layer in the network must have 128 neurons.

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. To do so, uncomment the following line.

% rng(0)

Create a TRPO agent from the environment observation and action specifications using the specified initialization options.

agent = rlTRPOAgent(obsInfo,actInfo,initOpts);

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

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

You can verify that the networks have 128 units in their hidden fully connected layers. For example, display the layers of the critic network.

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

     1   'concat'         Concatenation     Concatenation of 2 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   'output'         Fully Connected   1 fully connected layer

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

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

Create an environment interface, and obtain its observation and action specifications.

env = rlPredefinedEnv("CartPole-Discrete");
obsInfo = getObservationInfo(env);
actInfo = getActionInfo(env);

For TRPO agents, the critic estimates a value function, therefore it must take the observation signal as input and return a scalar value. Create a deep neural network to be used as approximation model within the critic. Define the network as an array of layer objects.

criticNet = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(100)
    reluLayer
    fullyConnectedLayer(1)
    ];

Convert to a dlnetwork object and display the number of parameters.

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

   Number of learnables: 601

   Inputs:
      1   'input'   4 features

Create the critic using criticNet. TRPO agents use an rlValueFunction object to implement the critic.

critic = rlValueFunction(criticNet,obsInfo);

Check the critic with a random observation input.

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

To approximate the policy within the actor use a neural network. For TRPO agents, the actor executes a stochastic policy, which for discrete action spaces is implemented by a discrete categorical actor. In this case the approximator must take the observation signal as input and return a probability for each 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, getting the dimension of the observation space and the number of possible actions from the environment specification objects.

actorNet = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(200)
    reluLayer
    fullyConnectedLayer(numel(actInfo.Dimension))
    ];

Convert to a dlnetwork object and display the number of parameters.

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

   Number of learnables: 1.4k

   Inputs:
      1   'input'   4 features

Create the actor using actorNet. PPO agents use an rlDiscreteCategoricalActor object to implement the actor for discrete action spaces.

actor = rlDiscreteCategoricalActor(actorNet,obsInfo,actInfo);

Check the actor with a random observation input.

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

Create a TRPO agent using the actor and the critic.

agent = rlTRPOAgent(actor,critic)
agent = 
  rlTRPOAgent with properties:

            AgentOptions: [1x1 rl.option.rlTRPOAgentOptions]
    UseExplorationPolicy: 1
         ObservationInfo: [1x1 rl.util.rlNumericSpec]
              ActionInfo: [1x1 rl.util.rlFiniteSetSpec]
              SampleTime: 1

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

agent.AgentOptions.ExperienceHorizon = 1024;
agent.AgentOptions.DiscountFactor = 0.95;
 
agent.AgentOptions.CriticOptimizerOptions.LearnRate = 8e-3;
agent.AgentOptions.CriticOptimizerOptions.GradientThreshold = 1;

Check your agent with a random observation input.

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

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

Create an environment with a continuous action space, and obtain its observation and action specifications. For this example, load the double integrator continuous action space 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");
obsInfo = getObservationInfo(env)
obsInfo = 
  rlNumericSpec with properties:

     LowerLimit: -Inf
     UpperLimit: Inf
           Name: "states"
    Description: "x, dx"
      Dimension: [2 1]
       DataType: "double"

actInfo = getActionInfo(env)
actInfo = 
  rlNumericSpec with properties:

     LowerLimit: -Inf
     UpperLimit: Inf
           Name: "force"
    Description: [0x0 string]
      Dimension: [1 1]
       DataType: "double"

In this example, the action is a scalar value representing a force ranging from -2 to 2 Newton. To make sure that the output from the agent is in this range, you perform an appropriate scaling operation. Store these limits so you can easily access them later.

actInfo.LowerLimit=-2;
actInfo.UpperLimit=2;

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

rng(0)

Create a deep neural network to be used as approximation model within the critic. For TRPO agents, the critic estimates a value function, therefore it must take the observation signal as input and return a scalar value.

criticNet = [
    featureInputLayer(prod(obsInfo.Dimension))
    fullyConnectedLayer(100)
    reluLayer
    fullyConnectedLayer(1)];

Convert to a dlnetwork object and display the number of parameters.

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

   Number of learnables: 401

   Inputs:
      1   'input'   2 features

Create the critic using criticNet. PPO agents use an rlValueFunction object to implement the critic.

critic = rlValueFunction(criticNet,obsInfo);

Check the critic with a random observation input.

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

To approximate the policy within the actor, use a neural network. For TRPO agents, the actor executes a stochastic policy, which for continuous action spaces is implemented by a continuous Gaussian actor. In this case the network must take the observation signal as input and return both a mean value and a standard deviation value for each action. Therefore it must have two output layers (one for the mean values the other for the standard deviation values), each having as many elements as the dimension of the action space.

Note that standard deviations must be nonnegative and mean values must fall within the range of the action. Therefore the output layer that returns the standard deviations must be a softplus or ReLU layer, to enforce nonnegativity, while the output layer that returns the mean values must be a scaling layer, to scale the mean values to the output range.

Define each network path as an array of layer objects. Get the dimensions of the observation and action spaces, and the action range limits from the environment specification objects. Specify a name for the input and output layers, so you can later explicitly associate them with the appropriate environment channel.

% Define common input path layer
commonPath = [ 
    featureInputLayer(prod(obsInfo.Dimension),Name="comPathIn")
    fullyConnectedLayer(100)
    reluLayer
    fullyConnectedLayer(1,Name="comPathOut") ];
 
% Define mean value path
meanPath = [
    fullyConnectedLayer(32,Name="meanPathIn")
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension));
    tanhLayer;
    scalingLayer(Name="meanPathOut",Scale=actInfo.UpperLimit) ];
 
% Define standard deviation path
sdevPath = [
    fullyConnectedLayer(32,'Name',"stdPathIn")
    reluLayer
    fullyConnectedLayer(prod(actInfo.Dimension));
    softplusLayer(Name="stdPathOut") ];
 
% Add layers to layerGraph object
actorNet = layerGraph(commonPath);
actorNet = addLayers(actorNet,meanPath);
actorNet = addLayers(actorNet,sdevPath);
 
% Connect paths
actorNet = connectLayers(actorNet,"comPathOut","meanPathIn/in");
actorNet = connectLayers(actorNet,"comPathOut",'stdPathIn/in');
 
% Plot network 
plot(actorNet)

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

% Convert to dlnetwork and display number of weights
actorNet = dlnetwork(actorNet);
summary(actorNet)
   Initialized: true

   Number of learnables: 595

   Inputs:
      1   'comPathIn'   2 features

Create the actor using actorNet. TRPO agents use an rlContinuousGaussianActor object to implement the actor for continuous action spaces.

actor = rlContinuousGaussianActor(actorNet, obsInfo, actInfo, ...
    'ActionMeanOutputNames',"meanPathOut",...
    'ActionStandardDeviationOutputNames',"stdPathOut",...
    'ObservationInputNames',"comPathIn");

Check the actor with a random observation input.

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

Create a TRPO agent using the actor and the critic.

agent = rlTRPOAgent(actor,critic)
agent = 
  rlTRPOAgent with properties:

            AgentOptions: [1x1 rl.option.rlTRPOAgentOptions]
    UseExplorationPolicy: 1
         ObservationInfo: [1x1 rl.util.rlNumericSpec]
              ActionInfo: [1x1 rl.util.rlNumericSpec]
              SampleTime: 1

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

agent.AgentOptions.ExperienceHorizon = 1024;
agent.AgentOptions.DiscountFactor = 0.95;

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

Check your agent with a random observation input.

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

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

Tips

  • For continuous action spaces, this agent does not enforce the constraints set by the action specification. In this case, you must enforce action space constraints within the environment.

  • While tuning the learning rate of the actor network is necessary for PPO agents, it is not necessary for TRPO agents.

  • For high-dimensional observations, such as for images, it is recommended to use PPO, SAC, or TD3 agents.

Version History

Introduced in R2021b