rlSACAgent
Soft actor-critic reinforcement learning agent
Description
The soft actor-critic (SAC) algorithm is a model-free, online, off-policy, actor-critic reinforcement learning method. The SAC algorithm computes an optimal policy that maximizes both the long-term expected reward and the entropy of the policy. The policy entropy is a measure of policy uncertainty given the state. A higher entropy value promotes more exploration. Maximizing both the reward and the entropy balances exploration and exploitation of the environment. The action space can only be continuous.
For more information, see Soft 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 a SAC agent for an environment with the given observation and action
specifications, using default initialization options. The actor and critics in the agent
use default deep neural networks built using the observation specification
agent
= rlSACAgent(observationInfo
,actionInfo
)observationInfo
and action specification
actionInfo
. The ObservationInfo
and
ActionInfo
properties of agent
are set to
the observationInfo
and actionInfo
input
arguments, respectively.
creates a SAC agent with deep neural networks configured using the specified
initialization options (agent
= rlSACAgent(observationInfo
,actionInfo
,initOptions
)initOptions
).
Create Agent from Actor and Critic
Specify Agent Options
sets the AgentOptions
property for any of the previous syntaxes.agent
= rlSACAgent(___,agentOptions
)
Input Arguments
initOptions
— Agent initialization options
rlAgentInitializationOptions
object
Agent initialization options, specified as an
rlAgentInitializationOptions
object.
actor
— Actor
rlContinuousGaussianActor
object
Actor that implements the policy, specified as an rlContinuousGaussianActor
function approximator object. For more
information on creating actor approximators, see Create Policies and Value Functions.
critics
— Critic
rlQValueFunction
object | two-element row vector of rlQValueFunction
objects
Critic, specified as one of the following:
rlQValueFunction
object — Create a SAC agent with a single Q-value function.Two-element row vector of
rlQValueFunction
objects — Create a SAC agent with two critic value functions. The two critic must be uniquerlQValueFunction
objects with the same observation and action specifications. The critics can either have different structures or the same structure but with different initial parameters.
For a SAC agent, each critic must be a single-output
rlQValueFunction
object that takes both the action and observations
as inputs.
For more information on creating critics, 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
rlNumericSpec
object
Action specification for a continuous action space, specified as an rlNumericSpec
object defining properties such as dimensions, data type and name of the action
signals.
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
rlSACAgentOptions
object
Agent options, specified as an rlSACAgentOptions
object.
If you create a SAC agent with default actor and critic that use recurrent neural
networks, the default value of AgentOptions.SequenceLength
is
32
.
ExperienceBuffer
— Experience buffer
rlReplayMemory
object
Experience buffer, specified as an rlReplayMemory
object. During training the agent stores each of its experiences
(S,A,R,S',D)
in a buffer. Here:
S is the current observation of the environment.
A is the action taken by the agent.
R is the reward for taking action A.
S' is the next observation after taking action A.
D is the is-done signal after taking action A.
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 SAC Agent from Observation and Action Specifications
Create environment and obtain observation and action specifications. For this example, load the 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);
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 SAC agent from the environment observation and action specifications.
agent = rlSACAgent(obsInfo,actInfo);
To check your agent, use getAction
to return the action from a random observation.
getAction(agent,{rand(obsInfo(1).Dimension)})
ans = 1x1 cell array
{[0.0546]}
You can now test and train the agent within the environment. You can also use getActor
and getCritic
to extract the actor and critic, respectively, and getModel
to extract the approximator model (by default a deep neural network) from the actor or critic.
Create SAC 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 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);
actInfo = getActionInfo(env);
Create an agent initialization option object, specifying that each hidden fully connected layer in the network must have 128 neurons.
initOpts = rlAgentInitializationOptions(NumHiddenUnit=128);
The agent creation function initializes the actor and critic networks randomly. Ensure reproducibility by fixing the seed of the random generator.
rng(0)
Create a SAC agent from the environment observation and action specifications using the initialization options.
agent = rlSACAgent(obsInfo,actInfo,initOpts);
Extract the deep neural network from the actor.
actorNet = getModel(getActor(agent));
Extract the deep neural networks from the two critics. Note that getModel(critics)
only returns the first critic network.
critics = getCritic(agent); criticNet1 = getModel(critics(1)); criticNet2 = getModel(critics(2));
Display the layers of the first critic network, and verify that each hidden fully connected layer has 128 neurons.
criticNet1.Layers
ans = 9x1 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' Feature Input 2 features 6 'fc_1' Fully Connected 128 fully connected layer 7 'input_2' Feature Input 1 features 8 'fc_2' Fully Connected 128 fully connected layer 9 'output' Fully Connected 1 fully connected layer
Plot the networks of the actor and of the second critic, and display the number of weights.
plot(layerGraph(actorNet))
summary(actorNet)
Initialized: true Number of learnables: 17.1k Inputs: 1 'input_1' 2 features
plot(layerGraph(criticNet2))
summary(criticNet2)
Initialized: true Number of learnables: 33.6k Inputs: 1 'input_1' 2 features 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)})
ans = 1x1 cell array
{[-0.9867]}
You can now test and train the agent within the environment.
Create SAC Agent from Actor and Critics
Create an environment and obtain observation and action specifications. For this example, load the environment used in the example Train DDPG Agent to Control Double Integrator System. The observations 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);
actInfo = getActionInfo(env);
A SAC agent uses two Q-value function critics. To approximate each Q-value function, use a neural network. The network for a single-output Q-value function critic must have two input layers, one for the observation and the other for the action, and return a scalar value representing the expected cumulative long-term reward following from the given observation and action.
Define each network path as an array of layer objects, and the dimensions of the observation and action spaces from the environment specification objects.
% Observation path obsPath = [ featureInputLayer(prod(obsInfo.Dimension),Name="obsPathIn") fullyConnectedLayer(32) reluLayer fullyConnectedLayer(16,Name="obsPathOut") ]; % Action path actPath = [ featureInputLayer(prod(actInfo.Dimension),Name="actPathIn") fullyConnectedLayer(32) reluLayer fullyConnectedLayer(16,Name="actPathOut") ]; % Common path commonPath = [ concatenationLayer(1,2,Name="concat") reluLayer fullyConnectedLayer(1) ]; % Add layers to layergraph object criticNet = layerGraph; criticNet = addLayers(criticNet,obsPath); criticNet = addLayers(criticNet,actPath); criticNet = addLayers(criticNet,commonPath); % Connect layers criticNet = connectLayers(criticNet,"obsPathOut","concat/in1"); criticNet = connectLayers(criticNet,"actPathOut","concat/in2");
To initialize the network weights differently for the two critics, create two different dlnetwork
objects. You must do this because if the agent constructor function does not accept two identical critics.
criticNet1 = dlnetwork(criticNet); criticNet2 = dlnetwork(criticNet);
Display the number of weights.
summary(criticNet1)
Initialized: true Number of learnables: 1.2k Inputs: 1 'obsPathIn' 2 features 2 'actPathIn' 1 features
Create the two critics using rlQValueFunction
, using the two networks with different weights. Alternatively, if you use exactly the same network with the same weights, you must explicitly initialize the network each time (to make sure weights are initialized differently) before passing it to rlQValueFunction
. To do so, use initialize
.
critic1 = rlQValueFunction(criticNet1,obsInfo,actInfo, ... ActionInputNames="actPathIn",ObservationInputNames="obsPathIn"); critic2 = rlQValueFunction(criticNet2,obsInfo,actInfo, ... ActionInputNames="actPathIn",ObservationInputNames="obsPathIn");
Check the critics with a random observation and action input.
getValue(critic1,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
-0.1330
getValue(critic2,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
-0.1526
To approximate the policy within the actor, use a deep neural network. Since SAC agents use a continuous Gaussian actor, 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.
Do not add a tanhLayer
or scalingLayer
in the mean output path. The SAC agent internally transforms the unbounded Gaussian distribution to the bounded distribution to compute the probability density function and entropy properly.
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 and output layers, so you can later explicitly associate them with the appropriate channel.
% Define common input path commonPath = [ featureInputLayer(prod(obsInfo.Dimension),Name="netObsIn") fullyConnectedLayer(400) reluLayer(Name="CommonRelu")]; % Define path for mean value meanPath = [ fullyConnectedLayer(300,Name="meanIn") reluLayer fullyConnectedLayer(prod(actInfo.Dimension),Name="MeanOut") ]; % Define path for standard deviation stdPath = [ fullyConnectedLayer(300,Name="stdIn") reluLayer fullyConnectedLayer(prod(actInfo.Dimension)) softplusLayer(Name="StandardDeviationOut")]; % Add layers to layerGraph object actorNet = layerGraph(commonPath); actorNet = addLayers(actorNet,meanPath); actorNet = addLayers(actorNet,stdPath); % Connect layers actorNet = connectLayers(actorNet,"CommonRelu","meanIn/in"); actorNet = connectLayers(actorNet,"CommonRelu","stdIn/in"); % Convert to dlnetwork and display the number of weights. actorNet = dlnetwork(actorNet); summary(actorNet)
Initialized: true Number of learnables: 242.4k Inputs: 1 'netObsIn' 2 features
Create the actor using actorNet
, the observation and action specification objects, and the names of the input and output layers.
actor = rlContinuousGaussianActor(actorNet, obsInfo, actInfo, ... ActionMeanOutputNames="MeanOut",... ActionStandardDeviationOutputNames="StandardDeviationOut",... ObservationInputNames="netObsIn");
Check your actor with a random input observation.
getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[-0.2589]}
Specify training options for the critics.
criticOptions = rlOptimizerOptions( ... Optimizer="adam", ... LearnRate=1e-3,... GradientThreshold=1, ... L2RegularizationFactor=2e-4);
Specify training options for the actor.
actorOptions = rlOptimizerOptions( ... Optimizer="adam", ... LearnRate=1e-3,... GradientThreshold=1, ... L2RegularizationFactor=1e-5);
Specify agent options, including training options for actor and critics.
agentOptions = rlSACAgentOptions; agentOptions.SampleTime = env.Ts; agentOptions.DiscountFactor = 0.99; agentOptions.TargetSmoothFactor = 1e-3; agentOptions.ExperienceBufferLength = 1e6; agentOptions.MiniBatchSize = 32; agentOptions.CriticOptimizerOptions = criticOptions; agentOptions.ActorOptimizerOptions = actorOptions;
Create SAC agent using actor, critics, and options.
agent = rlSACAgent(actor,[critic1 critic2],agentOptions);
To check your agent, use getAction
to return the action from a random observation.
getAction(agent,{rand(obsInfo(1).Dimension)})
ans = 1x1 cell array
{[0.2504]}
You can now test and train the agent within the environment.
Create SAC Agent using Recurrent Neural Networks
For this example, load the environment used in the example Train DDPG Agent to Control Double Integrator System. The observations 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);
actInfo = getActionInfo(env);
A SAC agent uses two Q-value function critics. To approximate each Q-value function, use a neural network. The network for a single-output Q-value function critic must have two input layers, one for the observation and the other for the action, and return a scalar value representing the expected cumulative long-term reward following from the given observation and action.
Define each network path as an array of layer objects, and the dimensions of the observation and action spaces from the environment specification objects. To create a recurrent neural network, use sequenceInputLayer
as the input layer and include an lstmLayer
as one of the other network layers.
% Define observation path obsPath = [ sequenceInputLayer(prod(obsInfo.Dimension),Name="obsIn") fullyConnectedLayer(400) reluLayer fullyConnectedLayer(300,Name = "obsOut") ]; % Define action path actPath = [ sequenceInputLayer(prod(actInfo.Dimension),Name="actIn") fullyConnectedLayer(300,Name="actOut") ]; % Define common path commonPath = [ concatenationLayer(1,2,Name="cat") lstmLayer(16) reluLayer fullyConnectedLayer(1) ]; % Add layers to layergraph object criticNet = layerGraph(obsPath); criticNet = addLayers(criticNet,actPath); criticNet = addLayers(criticNet,commonPath); % Connect paths criticNet = connectLayers(criticNet,"obsOut","cat/in1"); criticNet = connectLayers(criticNet,"actOut","cat/in2");
To initialize the network weights differently for the two critics, create two different dlnetwork
objects. You must do this because if the agent constructor function does not accept two identical critics.
criticNet1 = dlnetwork(criticNet); criticNet2 = dlnetwork(criticNet);
Display the number of weights.
summary(criticNet1)
Initialized: true Number of learnables: 161.6k Inputs: 1 'obsIn' Sequence input with 2 dimensions 2 'actIn' Sequence input with 1 dimensions
Create the critic using rlQValueFunction
. Use the same network structure for both critics. The SAC agent initializes the two networks using different default parameters.
critic1 = rlQValueFunction(criticNet1,obsInfo,actInfo); critic2 = rlQValueFunction(criticNet2,obsInfo,actInfo);
Check the critics with a random observation and action input.
getValue(critic1,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
-0.0020
getValue(critic2,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})
ans = single
0.0510
To approximate the policy within the actor, use a deep neural network. Since the critic has a recurrent network, the actor must have a recurrent network too. The network 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.
Do not add a tanhLayer
or scalingLayer
in the mean output path. The SAC agent internally transforms the unbounded Gaussian distribution to the bounded distribution to compute the probability density function and entropy properly.
Define each network path as an array of layer objects and specify a name for the input and output layers, so you can later explicitly associate them with the appropriate channel.
% Define common path commonPath = [ sequenceInputLayer(prod(obsInfo.Dimension),Name="obsIn") fullyConnectedLayer(400) lstmLayer(8) reluLayer(Name="CommonOut")]; meanPath = [ fullyConnectedLayer(300,Name="MeanIn") reluLayer fullyConnectedLayer(prod(actInfo.Dimension),Name="Mean") ]; stdPath = [ fullyConnectedLayer(300,Name="StdIn") reluLayer fullyConnectedLayer(prod(actInfo.Dimension)) softplusLayer(Name="StandardDeviation")]; actorNet = layerGraph(commonPath); actorNet = addLayers(actorNet,meanPath); actorNet = addLayers(actorNet,stdPath); actorNet = connectLayers(actorNet,"CommonOut","MeanIn/in"); actorNet = connectLayers(actorNet,"CommonOut","StdIn/in"); % Convert to dlnetwork and display the number of weights. actorNet = dlnetwork(actorNet); summary(actorNet)
Initialized: true Number of learnables: 20.2k Inputs: 1 'obsIn' Sequence input with 2 dimensions
Create the actor using actorNetwork
.
actor = rlContinuousGaussianActor(actorNet, obsInfo, actInfo, ... ActionMeanOutputNames="Mean",... ActionStandardDeviationOutputNames="StandardDeviation",... ObservationInputNames="obsIn");
Check your actor with a random input observation.
getAction(actor,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[-0.3476]}
Specify training options for the critics.
criticOptions = rlOptimizerOptions( ... Optimizer = "adam", LearnRate = 1e-3,... GradientThreshold = 1, L2RegularizationFactor = 2e-4);
Specify training options for the actor.
actorOptions = rlOptimizerOptions( ... Optimizer = "adam", LearnRate = 1e-3,... GradientThreshold = 1, L2RegularizationFactor = 1e-5);
Specify agent options. To use a recurrent neural network, you must specify a SequenceLength
greater than 1.
agentOptions = rlSACAgentOptions; agentOptions.SampleTime = env.Ts; agentOptions.DiscountFactor = 0.99; agentOptions.TargetSmoothFactor = 1e-3; agentOptions.ExperienceBufferLength = 1e6; agentOptions.SequenceLength = 32; agentOptions.MiniBatchSize = 32;
Create SAC agent using actor, critics, and options.
agent = rlSACAgent(actor,[critic1 critic2],agentOptions);
To check your agent, use getAction
to return the action from a random observation.
getAction(agent,{rand(obsInfo.Dimension)})
ans = 1x1 cell array
{[0.7990]}
You can now test and train the agent within the environment.
Version History
Introduced in R2020b
MATLAB 명령
다음 MATLAB 명령에 해당하는 링크를 클릭했습니다.
명령을 실행하려면 MATLAB 명령 창에 입력하십시오. 웹 브라우저는 MATLAB 명령을 지원하지 않습니다.
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)