rlPGAgent
Policy gradient reinforcement learning agent
Description
The policy gradient (PG) algorithm is a model-free, online, on-policy reinforcement learning method. A PG agent is a policy-based reinforcement learning agent that uses the REINFORCE algorithm to directly compute an optimal policy which maximizes the long-term reward. The action space can be either discrete or continuous.
For more information on PG agents and the REINFORCE algorithm, see Policy Gradient Agents. For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.
Creation
Syntax
Description
Create Agent from Observation and Action Specifications
creates a policy gradient agent for an environment with the given observation and action
specifications, using default initialization options. The actor and critic in the agent
use default deep neural networks built from the observation specification
agent
= rlPGAgent(observationInfo
,actionInfo
)observationInfo
and the action specification
actionInfo
. The ObservationInfo
and
ActionInfo
properties of agent
are set to
the observationInfo
and actionInfo
input
arguments, respectively.
creates a policy gradient agent for an environment with the given observation and action
specifications. The agent uses default networks in which each hidden fully connected
layer has the number of units specified in the agent
= rlPGAgent(observationInfo
,actionInfo
,initOpts
)initOpts
object.
Policy gradient agents do not support recurrent neural networks. For more information on
the initialization options, see rlAgentInitializationOptions
.
Create Agent from Actor and Critic
creates a PG agent with the specified actor network. By default, the
agent
= rlPGAgent(actor
)UseBaseline
property of the agent is false
in
this case.
Specify Agent Options
creates a PG agent and sets the agent
= rlPGAgent(___,agentOptions
)AgentOptions
property to the agentOptions
input argument. Use this syntax after
any of the input arguments in the previous syntaxes.
Input Arguments
initOpts
— Agent initialization options
rlAgentInitializationOptions
object
Agent initialization options, specified as an rlAgentInitializationOptions
object. Policy gradient agents do not support
recurrent neural networks.
actor
— Actor
rlDiscreteCategoricalActor
object | rlContinuousGaussianActor
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
— Baseline critic
rlValueFunction
object
Baseline 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
ObservationInfo
— Observation specifications
specification object | array of specification objects
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
.
ActionInfo
— Action specification
specification object
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
.
AgentOptions
— Agent options
rlPGAgentOptions
object
Agent options, specified as an rlPGAgentOptions
object.
UseExplorationPolicy
— Option to use exploration policy
true
(default) | false
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 insim
andgeneratePolicyFunction
. 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 insim
andgeneratePolicyFunction
. In this case, the simulated agent and generated policy behave deterministically.
Note
This option affects only simulation and deployment; it does not affect training.
SampleTime
— Sample time of agent
positive scalar | -1
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
train | Train reinforcement learning agents within a specified environment |
sim | Simulate trained reinforcement learning agents within specified environment |
getAction | Obtain action from agent, actor, or policy object given environment observations |
getActor | Get actor from reinforcement learning agent |
setActor | Set actor of reinforcement learning agent |
getCritic | Get critic from reinforcement learning agent |
setCritic | Set critic of reinforcement learning agent |
generatePolicyFunction | Generate function that evaluates policy of an agent or policy object |
Examples
Create Discrete Policy Gradient Agent from Observation and Action Specifications
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 the pole).
env = rlPredefinedEnv("SimplePendulumWithImage-Discrete");
Obtain observation and action specification objects.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
The agent creation function initializes the actor and critic networks randomly. Ensure reproducibility by fixing the seed of the random generator.
rng(0)
Create a policy gradient agent from the environment observation and action specifications.
agent = rlPGAgent(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 Continuous Policy Gradient Agent Using Initialization Options
Create an environment with a continuous action space and obtain its observation and action specifications. For this example, load the environment used in the example Train DDPG Agent to Swing Up and Balance Pendulum with Image Observation. This environment has two observations: a 50-by-50 grayscale image and a scalar (the angular velocity of the pendulum). The action is a scalar representing a torque ranging continuously from -2 to 2 Nm.
env = rlPredefinedEnv("SimplePendulumWithImage-Continuous");
Obtain observation and action specifications
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
Create an agent initialization option object, specifying that each hidden fully connected layer in the network must have 128 neurons (instead of the default number, 256). Policy gradient 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 policy gradient agent from the environment observation and action specifications.
agent = rlPGAgent(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' 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
Plot actor and critic networks, and display their number of weights.
plot(layerGraph(actorNet))
summary(actorNet)
Initialized: true Number of learnables: 18.9M Inputs: 1 'input_1' 50x50x1 images 2 'input_2' 1 features
plot(layerGraph(criticNet))
summary(criticNet)
Initialized: true Number of learnables: 18.9M Inputs: 1 'input_1' 50x50x1 images 2 'input_2' 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.9228]}
You can now test and train the agent within the environment.
Create a Discrete PG Agent from Actor and Baseline Critic
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 Train PG Agent with Baseline 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, having three possible values (-2, 0, or 2 Newton).
env = rlPredefinedEnv("DoubleIntegrator-Discrete");
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 = rlFiniteSetSpec with properties: Elements: [-2 0 2] Name: "force" Description: [0x0 string] Dimension: [1 1] DataType: "double"
For policy gradient agents, the baseline critic estimates a value function, therefore it must take the observation signal as input and return a scalar value.
Define the network as an array of layer objects, and get the dimension of the observation space from the environment specification object.
baselineNet = [ featureInputLayer(prod(obsInfo.Dimension)) fullyConnectedLayer(64) reluLayer fullyConnectedLayer(1)];
Convert to a dlnetwork
object and display the number of weights.
baselineNet = dlnetwork(baselineNet); summary(baselineNet)
Initialized: true Number of learnables: 257 Inputs: 1 'input' 2 features
Create a critic to use as a baseline. Policy gradient agents use an rlValueFunction
object to implement the critic.
baseline = rlValueFunction(baselineNet,obsInfo);
Check the critic with a random input observation.
getValue(baseline,{rand(obsInfo.Dimension)})
ans = single
-0.1204
To approximate the policy within the actor, use a deep neural network. For policy gradient 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.
Define the network as an array of layer objects, and get the dimension of the observation space and the number of possible actions from the environment specification objects.
actorNet = [ featureInputLayer(prod(obsInfo.Dimension)) fullyConnectedLayer(64) reluLayer fullyConnectedLayer(numel(actInfo.Elements))];
Convert to a dlnetwork
object and display the number of weights.
actorNet = dlnetwork(actorNet); summary(actorNet)
Initialized: true Number of learnables: 387 Inputs: 1 'input' 2 features
Create the actor using rlDiscreteCategoricalActor
, as well as the observation and action specifications.
actor = rlDiscreteCategoricalActor(actorNet,obsInfo,actInfo);
Check the actor with a random observation input.
getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[-2]}
Create the PG agent using the actor and the baseline critic.
agent = rlPGAgent(actor,baseline)
agent = rlPGAgent with properties: AgentOptions: [1x1 rl.option.rlPGAgentOptions] UseExplorationPolicy: 1 ObservationInfo: [1x1 rl.util.rlNumericSpec] ActionInfo: [1x1 rl.util.rlFiniteSetSpec] SampleTime: 1
Specify options for the agent, including training options for the actor and critic.
agent.AgentOptions.UseBaseline = true; agent.AgentOptions.DiscountFactor = 0.99; agent.AgentOptions.CriticOptimizerOptions.LearnRate = 5e-3; agent.AgentOptions.CriticOptimizerOptions.GradientThreshold = 1; agent.AgentOptions.ActorOptimizerOptions.LearnRate = 5e-3; agent.AgentOptions.ActorOptimizerOptions.GradientThreshold = 1;
Check the agent with a random observation input.
getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[-2]}
You can now test and train the agent within the environment.
Create a Continuous PG Agent from Actor and Baseline Critic
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.
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;
For policy gradient agents, the baseline critic estimates a value function, therefore it must take the observation signal as input and return a scalar value. To approximate the value function within the baseline, use a neural network.
Define the network as an array of layer objects, and get the dimensions of the observation space from the environment specification object.
baselineNet = [ featureInputLayer(prod(obsInfo.Dimension)) fullyConnectedLayer(64) reluLayer fullyConnectedLayer(1)];
Convert to a dlnetwork
object and display the number of weights.
baselineNet = dlnetwork(baselineNet); summary(baselineNet)
Initialized: true Number of learnables: 257 Inputs: 1 'input' 2 features
Create a critic to use as a baseline. Policy gradient agents use an rlValueFunction
object to implement the critic.
baseline = rlValueFunction(baselineNet,obsInfo);
Check the critic with a random input observation.
getValue(baseline,{rand(obsInfo.Dimension)})
ans = single
-0.1204
To approximate the policy within the actor, use a deep neural network as approximation model. For policy gradient 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 from the environment specification objects, and specify a name for the input layers, so you can later explicitly associate them with the appropriate environment channel.
% Input path inPath = [ featureInputLayer(prod(obsInfo.Dimension),Name="obs_in") fullyConnectedLayer(32) reluLayer(Name="ip_out") ]; % Mean path meanPath = [ fullyConnectedLayer(16,Name="mp_fc1") reluLayer fullyConnectedLayer(1) tanhLayer(Name="tanh"); % range: -1,1 scalingLayer(Name="mp_out", ... Scale=actInfo.UpperLimit) ]; % range: -2,2 % Standard deviation path sdevPath = [ fullyConnectedLayer(16,Name="sp_fc1") reluLayer fullyConnectedLayer(1); softplusLayer(Name="sp_out") ]; % non negative % Add layers to layerGraph object actorNet = layerGraph(inPath); actorNet = addLayers(actorNet,meanPath); actorNet = addLayers(actorNet,sdevPath); % Connect output of inPath to meanPath input actorNet = connectLayers(actorNet,"ip_out","mp_fc1/in"); % Connect output of inPath to variancePath input actorNet = connectLayers(actorNet,"ip_out","sp_fc1/in"); % plot network plot(actorNet)
% Convert to dlnetwork object actorNet = dlnetwork(actorNet); % Display the number of weights summary(actorNet)
Initialized: true Number of learnables: 1.1k Inputs: 1 'obs_in' 2 features
Create the actor using rlContinuousGaussianActor
, together with actorNet
, the observation and action specifications, as well as the names of the network input and output layers.
actor = rlContinuousGaussianActor(actorNet, ... obsInfo,actInfo, ... ObservationInputNames="obs_in", ... ActionMeanOutputNames="mp_out", ... ActionStandardDeviationOutputNames="sp_out");
Check the actor with a random input observation.
getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[0.0963]}
Create the PG agent using the actor and the baseline critic.
agent = rlPGAgent(actor,baseline)
agent = rlPGAgent with properties: AgentOptions: [1x1 rl.option.rlPGAgentOptions] UseExplorationPolicy: 1 ObservationInfo: [1x1 rl.util.rlNumericSpec] ActionInfo: [1x1 rl.util.rlNumericSpec] SampleTime: 1
Specify options for the agent, including training options for the actor and critic.
agent.AgentOptions.UseBaseline = true; agent.AgentOptions.DiscountFactor = 0.99; agent.AgentOptions.CriticOptimizerOptions.LearnRate = 5e-3; agent.AgentOptions.CriticOptimizerOptions.GradientThreshold = 1; agent.AgentOptions.ActorOptimizerOptions.LearnRate = 5e-3; agent.AgentOptions.ActorOptimizerOptions.GradientThreshold = 1;
Check your agent with a random input observation.
getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[1.1197]}
You can now test and train the agent within the environment.
Create a Discrete PG Agent with Recurrent Neural Networks
For this example, load the environment used in the example Train PG Agent with Baseline 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, having three possible values (-2, 0, or 2 Newton).
env = rlPredefinedEnv("DoubleIntegrator-Discrete");
Get observation and specification information.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
Create a critic to use as a baseline. For policy gradient agents, the baseline critic estimates a value function, therefore it must take the observation signal as input and return a scalar value. To approximate the value function within the critic, use a recurrent neural network.
Define the network as an array of layer objects, and get the dimension of the observation space from the environment specification object. To create a recurrent neural network for the critic, use sequenceInputLayer
as the input layer and include an lstmLayer
as one of the other network layers.
baselineNet = [ sequenceInputLayer(prod(obsInfo.Dimension)) lstmLayer(32) reluLayer fullyConnectedLayer(1)];
Convert to a dlnetwork
object and display the number of weights.
baselineNet = dlnetwork(baselineNet); summary(baselineNet)
Initialized: true Number of learnables: 4.5k Inputs: 1 'sequenceinput' Sequence input with 2 dimensions
Create the critic based on the network approximator model. Policy gradient agents use an rlValueFunction
object to implement the critic.
baseline = rlValueFunction(baselineNet,obsInfo);
Check the baseline critic with a random input observation.
getValue(baseline,{rand(obsInfo.Dimension)})
ans = single
-0.0065
Since the critic has a recurrent network, the actor must have a recurrent network too. Define a recurrent neural network for the actor. For policy gradient 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.
Define the network as an array of layer objects, and get the dimension of the observation space and the number of possible actions from the environment specification objects.
actorNet = [ sequenceInputLayer(prod(obsInfo.Dimension)) lstmLayer(32) reluLayer fullyConnectedLayer(numel(actInfo.Elements))];
Convert to a dlnetwork
object and display the number of weights.
actorNet = dlnetwork(actorNet); summary(actorNet)
Initialized: true Number of learnables: 4.5k Inputs: 1 'sequenceinput' Sequence input with 2 dimensions
Create the actor. Policy gradient agents use stochastic actors, which for discrete action spaces are implemented by rlDiscreteCategoricalActor
objects.
actor = rlDiscreteCategoricalActor(actorNet,obsInfo,actInfo);
Check the actor with a random observation input.
getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[0]}
Set some training options for the critic.
baselineOpts = rlOptimizerOptions( ... 'LearnRate',5e-3,'GradientThreshold',1);
Set some training options for the actor.
actorOpts = rlOptimizerOptions( ... 'LearnRate',5e-3,'GradientThreshold',1);
Specify agent options, including training options for the actor and the critic.
agentOpts = rlPGAgentOptions(... 'UseBaseline',true, ... 'DiscountFactor', 0.99, ... 'CriticOptimizerOptions',baselineOpts, ... 'ActorOptimizerOptions', actorOpts);
create a PG agent using the actor, the critic and the agent option object.
agent = rlPGAgent(actor,baseline,agentOpts);
For PG agent with recurrent neural networks, the training sequence length is the whole episode.
Check the agent with a random observation input.
getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[0]}
You can now test and train the agent within the environment.
Tips
For continuous action spaces, the
rlPGAgent
agent does not enforce the constraints set by the action specification, so you must enforce action space constraints within the environment.
Version History
Introduced in R2019a
Beispiel öffnen
Sie haben eine geänderte Version dieses Beispiels. Möchten Sie dieses Beispiel mit Ihren Änderungen öffnen?
MATLAB-Befehl
Sie haben auf einen Link geklickt, der diesem MATLAB-Befehl entspricht:
Führen Sie den Befehl durch Eingabe in das MATLAB-Befehlsfenster aus. Webbrowser unterstützen keine MATLAB-Befehle.
Select a Web Site
Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .
You can also select a web site from the following list:
How to Get Best Site Performance
Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.
Americas
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)