rlACAgent
Actor-critic reinforcement learning agent
Description
Actor-critic (AC) agents implement actor-critic algorithms such as A2C and A3C, which are model-free, online, on-policy reinforcement learning methods. The actor-critic agent optimizes the policy (actor) directly and uses a critic to estimate the return or future rewards. The action space can be either discrete or continuous.
For more information, see Actor-Critic 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 an actor-critic 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
= rlACAgent(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 an actor-critic 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
= rlACAgent(observationInfo
,actionInfo
,initOpts
)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
Specify Agent Options
creates an actor-critic agent and sets the AgentOptions
property to the agent
= rlACAgent(___,agentOptions
)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. Actor-critic 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
— Critic
rlValueFunction
object
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
rlACAgentOptions
object
Agent options, specified as an rlACAgentOptions
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.false
— Use the base agent greedy policy when selecting actions.
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 or actor 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 | Create function that evaluates trained policy of reinforcement learning agent |
Examples
Create Discrete Actor-Critic 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 a swinging pole).
% load predefined environment env = rlPredefinedEnv("SimplePendulumWithImage-Discrete"); % obtain observation and action specifications 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 an actor-critic agent from the environment observation and action specifications.
agent = rlACAgent(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 Actor-Critic 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.
% 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
). Actor-critic 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. You can ensure reproducibility by fixing the seed of the random generator. To do so, uncomment the following line.
% rng(0)
Create an actor-critic agent from the environment observation and action specifications.
agent = rlACAgent(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))
plot(layerGraph(criticNet))
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 Discrete Actor-Critic Agent from Actor and 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 DQN Agent to Balance Cart-Pole System. This environment has a four-dimensional observation vector (cart position and velocity, pole angle, and pole angle derivative), and a scalar action with two possible elements (a force of either -10
or +10
N applied on the cart).
% load predefined environment env = rlPredefinedEnv("CartPole-Discrete"); % obtain observation specifications obsInfo = getObservationInfo(env)
obsInfo = rlNumericSpec with properties: LowerLimit: -Inf UpperLimit: Inf Name: "CartPole States" Description: "x, dx, theta, dtheta" Dimension: [4 1] DataType: "double"
% obtain action specifications
actInfo = getActionInfo(env)
actInfo = rlFiniteSetSpec with properties: Elements: [-10 10] Name: "CartPole Action" Description: [0x0 string] Dimension: [1 1] DataType: "double"
The agent creation function initializes the actor and critic networks 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 actor-critic 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') fullyConnectedLayer(1,'Name','CriticFC')];
Create the critic using criticNetwork
. Actor-critic agents use an rlValueFunction
object to implement the critic.
critic = rlValueFunction(criticNetwork,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 actor-critic 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') fullyConnectedLayer(numel(actInfo.Dimension),'Name','action')];
Create the actor using actorNetwork
. Actor-critic 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 an AC agent using the actor and the critic.
agentOpts = rlACAgentOptions( ... 'NumStepsToLookAhead',32, ... 'DiscountFactor',0.99, ... 'CriticOptimizerOptions',criticOpts, ... 'ActorOptimizerOptions',actorOpts); agent = rlACAgent(actor,critic,agentOpts)
agent = rlACAgent with properties: AgentOptions: [1x1 rl.option.rlACAgentOptions] 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 within the environment.
Create Continuous Actor-Critic Agent from Actor and 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.
% load predefined environment env = rlPredefinedEnv("DoubleIntegrator-Continuous"); % obtain observation specifications obsInfo = getObservationInfo(env)
obsInfo = rlNumericSpec with properties: LowerLimit: -Inf UpperLimit: Inf Name: "states" Description: "x, dx" Dimension: [2 1] DataType: "double"
% obtain action specifications
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 input representing a force ranging from -2
to 2
Newton, so it is a good idea to set the upper and lower limit of the action signal accordingly, so we can easily retrieve them when building the actor network.
% make sure action space upper and lower limits are finite
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 actor-critic 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
. Actor-critic 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 actor-critic 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 layers inPath = [ featureInputLayer(prod(obsInfo.Dimension), ... 'Normalization','none','Name','netObsIn') fullyConnectedLayer(prod(actInfo.Dimension), ... 'Name','infc') ]; % path layers for mean value meanPath = [ tanhLayer('Name','tanhMean'); fullyConnectedLayer(prod(actInfo.Dimension)); scalingLayer('Name','scale', ... 'Scale',actInfo.UpperLimit) ]; % scale to range % path layers for standard deviations sdevPath = [ tanhLayer('Name','tanhStdv'); fullyConnectedLayer(prod(actInfo.Dimension)); softplusLayer('Name','splus') ]; % nonnegative % add layers to network object net = layerGraph(inPath); net = addLayers(net,meanPath); net = addLayers(net,sdevPath); % connect layers net = connectLayers(net,'infc','tanhMean/in'); net = connectLayers(net,'infc','tanhStdv/in'); % plot network plot(net)
Create the actor using net
. Actor-critic agents use an rlContinuousGaussianActor
object to implement the actor for continuous action spaces.
actor = rlContinuousGaussianActor(net, obsInfo, actInfo, ... 'ActionMeanOutputNames','scale',... 'ActionStandardDeviationOutputNames','splus',... 'ObservationInputNames','netObsIn');
Set some training options for the actor.
actorOpts = rlOptimizerOptions( ... 'LearnRate',8e-3,'GradientThreshold',1);
Specify agent options, and create an AC agent using actor, critic, and agent options.
agentOpts = rlACAgentOptions( ... 'NumStepsToLookAhead',32, ... 'DiscountFactor',0.99, ... 'CriticOptimizerOptions',criticOpts, ... 'ActorOptimizerOptions',actorOpts); agent = rlACAgent(actor,critic,agentOpts)
agent = rlACAgent with properties: AgentOptions: [1x1 rl.option.rlACAgentOptions] 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
{[1.6791]}
You can now test and train the agent within the environment.
Create a Discrete Actor-Critic Agent with Recurrent Neural Networks
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 four-dimensional observation vector (cart position and velocity, pole angle, and pole angle derivative), and a scalar action with two possible elements (a force of either -10 or +10 N applied on the cart).
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.
rng(0)
Create a deep neural network to be used as approximation model within the critic. For actor-critic 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') lstmLayer(8,'OutputMode','sequence','Name','lstm') fullyConnectedLayer(1,'Name','CriticFC')];
Create the critic using criticNetwork
. Actor-critic agents use an rlValueFunction
object to implement the critic.
critic = rlValueFunction(criticNetwork,obsInfo);
Set some training options for the critic.
criticOpts = rlOptimizerOptions( ... 'LearnRate',8e-3,'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 actor-critic 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') lstmLayer(8,'OutputMode','sequence','Name','lstm') fullyConnectedLayer(numel(actInfo.Elements),'Name','action')];
Create the actor using actorNetwork
. Actor-critic 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 an AC agent using the actor, the critic, and the agent options object. Since the agent uses recurrent neural networks, NumStepsToLookAhead
is treated as the training trajectory length.
agentOpts = rlACAgentOptions( ... 'NumStepsToLookAhead',32, ... 'DiscountFactor',0.99, ... 'CriticOptimizerOptions',criticOpts, ... 'ActorOptimizerOptions',actorOpts); agent = rlACAgent(actor,critic,agentOpts);
To check your agent, use getAction
to return the action from a random observation.
getAction(agent,{rand(obsInfo.Dimension)})
ans = 1×1 cell array
{[-10]}
You can now test and train the agent within the environment.
Tips
For continuous action spaces, the
rlACAgent
object does not enforce the constraints set by the action specification, so you must enforce action space constraints within the environment.
Version History
Open Example
You have a modified version of this example. Do you want to open this example with your edits?
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
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)