Main Content

rlPPOAgent

Proximal policy optimization reinforcement learning agent

Description

Proximal policy optimization (PPO) is a model-free, online, on-policy, policy gradient reinforcement learning method. This algorithm alternates between sampling data through environmental interaction and optimizing a clipped surrogate objective function using stochastic gradient descent. The action space can be either discrete or continuous.

For more information on PPO agents, see Proximal 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 = rlPPOAgent(observationInfo,actionInfo) creates a proximal policy optimization (PPO) 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 = rlPPOAgent(observationInfo,actionInfo,initOpts) creates a PPO agent for an environment with the given observation and action specifications. The agent uses default networks configured using options specified in the initOpts object. Actor-critic agents do not support recurrent neural networks. For more information on the initialization options, see rlAgentInitializationOptions.

Create Agent from Actor and Critic

example

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

Specify Agent Options

example

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

Your critic can use a recurrent neural network as its function approximator. In this case, your actor must also use a recurrent neural network. For an example, see Create PPO Agent with Recurrent Neural Networks.

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

  • 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 or actor 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
generatePolicyFunctionCreate function that evaluates trained policy of reinforcement learning agent

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

agent = rlPPOAgent(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.

% 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. You can ensure reproducibility by fixing the seed of the random generator. To do so, uncomment the following line.

% rng(0)

Create a PPO actor-critic agent from the environment observation and action specifications.

agent = rlPPOAgent(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 = 
  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'         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

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

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

criticNetwork = [
    featureInputLayer(prod(obsInfo.Dimension), ...
        'Normalization','none','Name','state')
    fullyConnectedLayer(1,'Name','CriticFC')];

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

critic = rlValueFunction(criticNetwork,obsInfo);

Set some training options for the critic.

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

Create a deep neural network to be used as approximation model within the actor. For PPO agents, the actor executes a stochastic policy, which for discrete action spaces is implemented by a discrete categorical actor. In this case the network 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.

actorNetwork = [
    featureInputLayer(prod(obsInfo.Dimension), ...
        'Normalization','none','Name','state')
    fullyConnectedLayer(numel(actInfo.Dimension), ...
        'Name','action') ];

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

actor = rlDiscreteCategoricalActor(actorNetwork,obsInfo,actInfo);

Set some training options for the actor.

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

Specify agent options, and create a PPO agent using the actor, critic, and the agent options object.

agentOpts = rlPPOAgentOptions(...
    'ExperienceHorizon',1024, ...
    'DiscountFactor',0.95, ...
    'CriticOptimizerOptions',criticOpts, ...
    'ActorOptimizerOptions',actorOpts);
agent = rlPPOAgent(actor,critic,agentOpts)
agent = 
  rlPPOAgent with properties:

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

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

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"

Since the action must be contained in a limited range, set the upper and lower limit of the action signal accordingly, so you can easily retrieve them when building the actor network.

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 PPO 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), ...
        'Normalization','none','Name','state')
    fullyConnectedLayer(10,'Name', 'fc_in')
    reluLayer('Name', 'relu')
    fullyConnectedLayer(1,'Name','out')];

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

critic = rlValueFunction(criticNet,obsInfo);

Set some training options for the critic.

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

Create a deep neural network to be used as approximation model within the actor. For PPO 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.

% input path layer
inPath = [ 
    featureInputLayer(prod(obsInfo.Dimension), ...
        'Normalization','none','Name','state')
    fullyConnectedLayer(10,'Name', 'ip_fc')
    reluLayer('Name', 'ip_relu')
    fullyConnectedLayer(1,'Name','ip_out') ];

% path layers for mean value
meanPath = [
    fullyConnectedLayer(15,'Name', 'mp_fc1')
    reluLayer('Name', 'mp_relu')
    fullyConnectedLayer(1,'Name','mp_fc2');
    tanhLayer('Name','tanh');
    scalingLayer('Name','mp_out', ...
         'Scale',actInfo.UpperLimit) ]; % range: (-2N,2N)

% path layers for standard deviation 
sdevPath = [
    fullyConnectedLayer(15,'Name', 'vp_fc1')
    reluLayer('Name', 'vp_relu')
    fullyConnectedLayer(1,'Name','vp_fc2');
    softplusLayer('Name', 'vp_out') ]; % range: (0,+Inf)

% add layers to layerGraph network object
actorNet = layerGraph(inPath);
actorNet = addLayers(actorNet,meanPath);
actorNet = addLayers(actorNet,sdevPath);

% connect layers
actorNet = connectLayers(actorNet,'ip_out','mp_fc1/in');
actorNet = connectLayers(actorNet,'ip_out','vp_fc1/in');

% plot network 
plot(actorNet)

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

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

actor = rlContinuousGaussianActor(actorNet, obsInfo, actInfo, ...
    'ActionMeanOutputNames','mp_out',...
    'ActionStandardDeviationOutputNames','vp_out',...
    'ObservationInputNames','state');

Set some training options for the actor.

actorOpts = rlOptimizerOptions( ...
    'LearnRate',8e-3,'GradientThreshold',1)
actorOpts = 
  rlOptimizerOptions with properties:

                  LearnRate: 0.0080
          GradientThreshold: 1
    GradientThresholdMethod: "l2norm"
     L2RegularizationFactor: 1.0000e-04
                  Algorithm: "adam"
        OptimizerParameters: [1x1 rl.option.OptimizerParameters]

Specify agent options, and create a PPO agent using the actor, critic and agent options.

agentOpts = rlPPOAgentOptions(...
    'ExperienceHorizon',1024, ...
    'DiscountFactor',0.95);
agent = rlPPOAgent(actor,critic,agentOpts)
agent = 
  rlPPOAgent with properties:

            AgentOptions: [1x1 rl.option.rlPPOAgentOptions]
    UseExplorationPolicy: 1
         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(2,1)})
ans = 1x1 cell array
    {[0.6668]}

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

For this example load the predefined environment used for the Train DQN Agent to Balance Cart-Pole System example.

env = rlPredefinedEnv('CartPole-Discrete');

Get observation and action information. This environment has a continuous four-dimensional observation space (the positions and velocities of both cart and pole) and a discrete one-dimensional action space consisting on the application of two possible forces, -10N or 10N.

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

Create a recurrent deep neural network for the critic. For PPO agents, the critic estimates a value function, therefore it must take the observation signal as input and return a scalar value. To create a recurrent neural network, use a sequenceInputLayer as the input layer and include an lstmLayer as one of the other network layers.

criticNetwork = [
    sequenceInputLayer(prod(obsInfo.Dimension), ...
        'Normalization','none','Name','myobs')
    fullyConnectedLayer(8, 'Name', 'fc')
    reluLayer('Name','relu')
    lstmLayer(8,'OutputMode','sequence','Name','lstm')
    fullyConnectedLayer(1,'Name','output')];

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

critic = rlValueFunction(criticNetwork,obsInfo);

Set some training option for the critic.

criticOptions = rlOptimizerOptions( ...
    'LearnRate',1e-2,'GradientThreshold',1);

Create a neural network to be used as approximation model within the actor. Since the critic has a recurrent network, the actor must have a recurrent network too. For PPO agents, the actor executes a stochastic policy, which for discrete action spaces is implemented by a discrete categorical actor. In this case the network 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.

actorNetwork = [
    sequenceInputLayer(prod(obsInfo.Dimension), ...
        'Normalization','none','Name','myobs')
    fullyConnectedLayer(8,'Name','fc')
    reluLayer('Name','relu')
    lstmLayer(8,'OutputMode','sequence','Name','lstm')
    fullyConnectedLayer(numel(actInfo.Elements),'Name','output')
    softmaxLayer('Name','actionProb')];

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

actor = rlDiscreteCategoricalActor(actorNetwork,obsInfo,actInfo);

Set some training options for the actor.

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

Create the agent options object.

agentOptions = rlPPOAgentOptions(...
    'AdvantageEstimateMethod', 'finite-horizon', ...
    'ClipFactor', 0.1, ...
    'CriticOptimizerOptions',criticOptions, ...
    'ActorOptimizerOptions',actorOptions);

When recurrent neural networks are used, the MiniBatchSize property is the length of the learning trajectory.

agentOptions.MiniBatchSize
ans = 128

Create the agent using the actor and critic, as well as the agent options object.

agent = rlPPOAgent(actor,critic,agentOptions);

Check your agent using getAction to return the action from a random observation.

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

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.

Version History

Introduced in R2019b