Main Content

rlTRPOAgent

Trust region policy optimization (TRPO) reinforcement learning agent

Since R2021b

Description

Trust region policy optimization (TRPO) is an on-policy, policy gradient reinforcement learning method for environments with a discrete or continuous action space. It directly estimates a stochastic policy and uses a value function critic to estimate the value of the policy. 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 continuous action spaces, this agent does not enforce constraints set in the action specification; therefore, if you need to enforce action constraints, you must do so within the environment.

Note

For TRPO agents, you can only use actors or critics with deep network that support calculating higher order derivatives. Actors and critics that use recurrent networks, custom basis functions, or tables are not supported.

For more information on TRPO agents, see Trust Region Policy Optimization (TRPO) 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 = 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.

example

Create Agent from Actor and Critic

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

example

Specify Agent Options

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.

example

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 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 either as an rlFiniteSetSpec (for discrete action spaces) or rlNumericSpec (for continuous action spaces) 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 rlFiniteSetSpec or rlNumericSpec.

Example: rlNumericSpec([2 1])

Agent options, specified as an rlTRPOAgentOptions object.

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 rlStochasticActorPolicy policy with the UseMaxLikelihoodAction property set to false. Since the agent selects its actions by sampling its probability distribution, the policy is stochastic and 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 rlStochasticActorPolicy policy with the UseMaxLikelihoodAction property set to true. Since the agent selects its actions greedily 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.

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 and obtain its observation and action specifications. For this example, load the environment used in the example Create DQN 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 -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. Ensure reproducibility by fixing the seed of the random generator.

rng(0)

Create a TRPO agent from the environment observation and action specifications. Since actInfo is an rlFiniteSetSpec object, rlTRPOAgent creates an agent with a discrete action space. When actInfo is an rlNumericSpec object, rlTRPOAgent creates an agent with a continuous action space.

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 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. TRPO agents do not support recurrent networks, so setting the UseRNN option to true generates an error when the agent is created.

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 TRPO agent from the environment observation and action specifications using the specified initialization options. Since actInfo is an rlNumericSpec object, rlTRPOAgent creates an agent with a continuous action space. When actInfo is an rlFiniteSetSpec object, rlTRPOAgent creates an agent with a discrete action space.

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));

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

criticNet.Layers

or visualize the structure interactively using analyzeNetwork.

analyzeNetwork(criticNet)

Plot the critic and actor networks.

plot(criticNet)

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

plot(actorNet)

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

TRPO agents use a parametrized value function approximator to estimate the value of the policy. A value-function critic takes the current observation as input and returns a single scalar as output (the estimated discounted cumulative long-term reward for following the policy from the state corresponding to the current observation).

To model the parametrized value function within the critic, use a neural network with one input layer (which receives the content of the observation channel, as specified by obsInfo) and one output layer (which returns the scalar value). Note that prod(obsInfo.Dimension) returns the total number of dimensions of the observation space regardless of whether the observation space is a column vector, row vector, or matrix.

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 approximator object using criticNet and the observation specification. For more information on value function approximators, see rlValueFunction.

critic = rlValueFunction(criticNet,obsInfo);

Check the critic with a random observation input.

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

-0.2479

TRPO agents use a parametrized stochastic policy, which for discrete action spaces is implemented by a discrete categorical actor. This actor takes an observation as input and returns as output a random action sampled (among the finite number of possible actions) from a categorical probability distribution.

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. The output layer must return a vector of probabilities for each possible action, as specified by actInfo. Note that numel(actInfo.Dimension) returns the number of possible actions.

Define the network as an array of layer 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 and the observation and action specifications. For more information on discrete categorical actors, see rlDiscreteCategoricalActor.

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 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)
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. Ensure reproducibility by fixing the seed of the random generator.

rng(0)

TRPO agents use a parametrized value function approximator to estimate the value of the policy. A value-function critic takes the current observation as input and returns a single scalar as output (the estimated discounted cumulative long-term reward for following the policy from the state corresponding to the current observation).

To model the parametrized value function within the critic, use a neural network with one input layer (which receives the content of the observation channel, as specified by obsInfo) and one output layer (which returns the scalar value). Note that prod(obsInfo.Dimension) returns the total number of dimensions of the observation space regardless of whether the observation space is a column vector, row vector, or matrix.

Define the network as an array of layer objects.

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

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

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

   Number of learnables: 401

   Inputs:
      1   'input'   2 features

Create the critic approximator object using criticNet and the observation specification. For more information on value function approximators, see rlValueFunction.

critic = rlValueFunction(criticNet,obsInfo);

Check the critic with a random observation input.

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

-0.0899

TRPO agents use a parametrized stochastic policy, which for continuous action spaces is implemented by a continuous Gaussian actor. This actor takes an observation as input and returns as output a random action sampled from a Gaussian probability distribution.

To approximate the mean values and standard deviations of the Gaussian distribution, you must use a neural network with two output layers, each having as many elements as the dimension of the action space. One output layer must return a vector containing the mean values for each action dimension. The other must return a vector containing the standard deviation for each action dimension.

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.

For this example the environment has only one observation channel and therefore the network has only one input layer.

Define each network path as an array of layer objects, and assign names to the input and output layers of each path. These names allow you to connect the paths and then later explicitly associate the network input and output layers 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") 
    ];

Create dlnetwork object and add layers.

actorNet = dlnetwork();
actorNet = addLayers(actorNet,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.

Initialize network and display number of weights.

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

   Number of learnables: 595

   Inputs:
      1   'comPathIn'   2 features

Create the actor approximator object using actorNet and the environment specifications. For more information, on continuous Gaussian actors, see rlContinuousGaussianActor.

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.

TRPO agents do not support actors or critics that use recurrent networks, custom basis functions, or tables. You can, however, avoid these limitations by creating a custom layer for your network. To illustrate this possibility, this example shows how to solve the grid world environment shown in Train Reinforcement Learning Agent in Basic Grid World using a TRPO agent in which both the actor and the critic use a deep network that uses a custom layer that emulates a table model.

The example code may involve computation of random numbers at various stages such as initialization of the agent, creation of the actor and critic, resetting the environment during simulations, initializing the environment state, generating observations (for stochastic environments), generating exploration actions, and sampling min-batches of experiences for learning. Fixing the random number stream preserves the sequence of the random numbers every time you run the code and improves reproducibility of results. You will fix the random number stream at various locations in the example.

Fix the random number stream with seed zero and random number algorithm Mersenne Twister. For more information on random number generation see rng.

previousRngState = rng(0,"twister")
previousRngState = struct with fields:
     Type: 'twister'
     Seed: 0
    State: [625x1 uint32]

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.

Create Grid World Environment

The grid world environment has the following configuration and rules:

  1. The grid world is 5-by-5 and bounded by borders, with four possible actions (North = 1, South = 2, East = 3, West = 4).

  2. The agent begins from cell [2,1] (second row, first column).

  3. The agent receives a reward +10 if it reaches the terminal state at cell [5,5] (blue).

  4. The environment contains a special jump from cell [2,4] to cell [4,4] with a reward of +5.

  5. The agent is blocked by obstacles (black cells).

  6. All other actions result in –1 reward.

Create the basic grid world environment.

env = rlPredefinedEnv("BasicGridWorld");

To specify that the initial state of the agent is always [2,1], create a reset function that returns the state number for the initial agent state. This function is called at the start of each training episode and simulation. States are numbered starting at position [1,1]. The state number increases as you move down the first column and then down each subsequent column. Therefore, create an anonymous function handle that sets the initial state to 2.

env.ResetFcn = @() 2;

Extract the observation and action specifications.

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

Extract the number of possible observations and actions.

nObs=numel(obsInfo.Elements);
nAct=numel(actInfo.Elements);

Fix the random generator seed for reproducibility.

rng(0)

Create Actor

To create the TRPO agent, first create a discrete categorical actor in which the approximation model is a neural network that mimics a table. First, create the initial table.

ActTable0 = 1+4*rand(nObs,nAct);

The custom one-hot layer myOHLayerV is implemented in the file myOHLayerV.m. Its input is a scalar ranging from 1 to numel(obsInfo.Elements). The output of the custom layer is a vector of dimension numel(obsInfo.Elements) in which the element corresponding to the value at the input of the layer is equal to 1, while all the other elements are equal to zero.

The layer constructor function takes as input the number of observation and stores it in its n property. The predict function takes as second argument the output of the previous layer, featureInputLayer(1). This is the dlarray X, which is a row vector having as many elements as the number of sequential observations in the batch, nbtc. It then creates a zero dlarray Z with as many rows as the number of possible observations (stored in its n property) and as many columns as the number of sequential observations in the batch, nbtc. The loop then cycles through each column of Z and sets its X(k) element to 1. For example, if the 42th observation in the batch is 13, then X(42)=13, and Z(13,42) is set to 1.

For more information on custom layers, see Define Custom Deep Learning Layers.

type myOHLayerV
classdef myOHLayerV < nnet.layer.Layer

    properties
        n
    end

    methods

        function obj = myOHLayerV(outsize)
            obj.Description = "One Hot Layer for Value Fcn";
            obj.n = outsize;
        end

        function Z = predict(obj, X)

            nbtc = size(X,2);
            Z = dlarray(zeros(obj.n,nbtc));
            for k = 1:nbtc
                if X(1,k) 
                    Z(X(1,k),k) = 1; 
                end
            end
        
        end

    end
    
end

Create the actor network as a vector of layer object. The feature input layer inputs the feature data to the network. The last fully connected layer maps the output of myOHLayerV (a vector in which the element equal to 1 corresponds to the current observation) to the action number. Set the initial value of the fully connected layer weights to the initial table. Also, set the bias and its learning rate to zero.

anet = [
    featureInputLayer(1)
    myOHLayerV(nObs)
    fullyConnectedLayer( ...
        nAct, ...
        Weights=ActTable0', ...
        Bias=zeros(nAct,1), ...
        BiasLearnRateFactor=0)
    ];

Convert to dlnetwork.

anet = dlnetwork(anet);

Create the actor.

actor = rlDiscreteCategoricalActor(anet,obsInfo,actInfo);

Check the actor using a random input observation.

getAction(actor,{randi(nObs)})
ans = 1x1 cell array
    {[4]}

Create Critic

Create a value function critic in which the approximation model is a neural network that mimics a table. First, create the initial table.

ValTable0 = rand(nObs,1);

Create the critic network as a vector of layer object. The last fully connected layer maps the output of myOHLayerV to the estimated value of the policy.

cnet = [
    featureInputLayer(1)
    myOHLayerV(nObs)
    fullyConnectedLayer( ...
        1, ...
        Weights = ValTable0', ...
        Bias=0, ...
        BiasLearnRateFactor=0)
    ];

Convert to dlnetwork.

cnet = dlnetwork(cnet);

Create the critic.

critic = rlValueFunction(cnet,obsInfo);

Check the critic using a random input observation.

getValue(critic,{randi(nObs)})
ans = single

0.0838

Create Agent

Create the agent using the actor and the critic.

agent = rlTRPOAgent(actor,critic);

Train Agent

To train the agent, first specify the training options. For this example, use the following options:

  • Train for at most 200 episodes. Specify that each episode lasts for most 50 time steps.

  • Stop training when the agent receives an average cumulative reward greater than 10 over 30 consecutive episodes.

For more information, see rlTrainingOptions.

trainOpts = rlTrainingOptions;
trainOpts.MaxStepsPerEpisode = 50;
trainOpts.MaxEpisodes= 2000;
trainOpts.StopTrainingCriteria = "AverageReward";
trainOpts.StopTrainingValue = 11;
trainOpts.ScoreAveragingWindowLength = 30;

Train the agent. Training can take several minutes 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,trainOpts);
else
    % Load the pretrained agent for the example.
    load("trpoGWQAgent.mat","agent")
end

The Reinforcement Learning Training Monitor window opens and displays the training progress.

Validate Q-Learning Results

To validate the training results, simulate the agent in the training environment.

Before running the simulation, visualize the environment and configure the visualization to maintain a trace of the agent states.

plot(env)
env.Model.Viewer.ShowTrace = true;
env.Model.Viewer.clearTrace;

Simulate the agent in the environment using the sim function.

sim(agent,env)

Figure contains an axes object. The hidden axes object contains 14 objects of type line, patch.

The agent trace shows that the agent successfully finds the jump from cell [2,4] to cell [4,4].

Restore the random number stream using the information stored in previousRngState.

rng(previousRngState);

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