rlDQNAgent
R2026bDeep Q-network (DQN) reinforcement learning agent
Description
The deep Q-network (DQN) algorithm is an off-policy reinforcement learning method for environments with a discrete action space. A DQN agent trains a Q-value function critic to estimate the value of the optimal policy, while following an epsilon-greedy policy based on the value estimated by the critic. DQN is a variant of Q-learning that features a target critic and an experience buffer. The DQN agent supports offline training (training from saved data, without an environment).
For more information, Deep Q-Network (DQN) Agent. For more information on the different types of reinforcement learning agents, see Reinforcement Learning Agents.
Creation
Syntax
Description
Create Default Agent from Observation and Action Specifications
creates a DQN agent for an environment with the given observation and action
specifications, using default initialization options. The critic in the agent uses a
default vector (that is, multi-output) Q-value deep neural network built from the
specifications.agent = rlDQNAgent(observationInfo,actionInfo)
creates a DQN agent for an environment with the given observation and action
specifications. The agent uses a default network configured using options specified in
the agent = rlDQNAgent(observationInfo,actionInfo,initOpts)initOpts object. For more information on the initialization
options, see rlAgentInitializationOptions.
Create Agent from Critic
creates a DQN agent with the specified critic network using a default option set for a
DQN agent.agent = rlDQNAgent(critic)
Specify Agent Options
creates a DQN agent with the specified critic network and sets the agent = rlDQNAgent(critic,agentOptions)AgentOptions
property to the agentOptions input argument. Use this syntax after
any of the input arguments in the previous syntaxes..
Input Arguments
Observation specifications, specified as an rlFiniteSetSpec
or rlNumericSpec
object or an array containing any combination of such objects. Each element in the array defines
the properties of an environment observation channel, such as its dimensions, data
type, and name.
This argument sets the ObservationInfo property.
Example: observationInfo=[rlNumericSpec([2 1]) rlFiniteSetSpec([-1
1])]
Action specification, specified as an rlFiniteSetSpec
object. This object defines the properties of the environment action channel, such as
its dimensions, data type, and name.
This argument sets the ActionInfo property.
Example: actionInfo=rlFiniteSetSpec([-1 0 1])
Agent initialization options, specified as an rlAgentInitializationOptions object.
Example: rlAgentInitializationOptions(NumHiddenUnit=128)
Critic, specified as an rlQValueFunction or as the generally more efficient rlVectorQValueFunction object. For more information on creating critics,
see Create Actors, Critics, and Policy Objects.
Your critic can use a recurrent neural network as its function approximator.
However, only rlVectorQValueFunction supports recurrent neural
networks. For an example, see Create DQN Agent with Custom Recurrent Neural Network.
Agent options, specified as an rlDQNAgentOptions object.
This argument sets the AgentOptions property.
Example: rlDQNAgentOptions(ExperienceBufferLength=20000)
Properties
This property is read-only.
Observation specifications, returned as an rlFiniteSetSpec
or rlNumericSpec
object or an array containing any combination of such objects. Each element in the array defines
the properties of an environment observation channel, such as its dimensions, data type,
and name.
If you create the agent by specifying an actor or critic, the value of
ObservationInfo matches the value specified in the actor and
critic objects. If you create a default agent, the agent constructor function sets the
ObservationInfo property to the input argument
observationInfo.
You can extract observationInfo from an existing environment,
function approximator, or agent using getObservationInfo. You can also construct the specifications manually
using rlFiniteSetSpec
or rlNumericSpec.
This property is read-only.
Action specifications, specified as an rlFiniteSetSpec
object. This object defines the properties of the environment action channel, such as
its dimensions, data type, and name.
Note
For this agent, only one action channel is allowed.
If you create the agent by specifying a critic object, the value of
ActionInfo matches the value specified in
critic. If you create a default agent, the agent constructor
function sets the ActionInfo property to the input argument
ActionInfo.
You can extract actionInfo from an existing environment, function
approximator, or agent using getActionInfo. You can also construct the specification manually using
rlFiniteSetSpec.
Agent options, specified as an rlDQNAgentOptions
object.
If you create a DQN agent with a default critic that uses a recurrent neural
network, the default value of AgentOptions.SequenceLength is
32.
Example: myagent.AgentOptions =
rlDQNAgentOptions(ExperienceBufferLenght=20000)
Experience buffer, specified as one of the following replay memory objects.
Note
Agents with recursive neural networks only support rlReplayMemory and rlHindsightReplayMemory buffers.
During training the agent stores each of its experiences (S,A,R,S',D) in the 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.
The agent then samples mini-batches of experiences from the buffer and uses these mini-batches to update its actor and critic function approximators.
Example: myagent.ExperienceBuffer = rlReplayMemory(rlNumericSpec([3
1]),rlFiniteSetSpec([-1 0 1]))
Option to use an exploration policy when selecting actions during simulation or after deployment, specified as a logical value.
true— Specify this value to use the base agent exploration policy when you use the agent with thesimandgeneratePolicyFunctionfunctions. Specifically, in this case, the agent uses therlEpsilonGreedyPolicyobject. The action selection has a random component, so the agent explores its action and observation spaces.false— Specify this value to force the agent to use the base agent greedy policy (the action with maximum likelihood) when you use the agent with thesimandgeneratePolicyFunctionfunctions. Specifically, in this case, the agent uses therlMaxQPolicypolicy. The action selection is greedy, so the policy behaves deterministically and the agent does not explore its action and observation spaces.
Note
This option affects only simulation and deployment and does not affect training.
When you train an agent using the train
function, the agent always uses its exploration policy independently of the value of
this property. Specifically, the training algorithm temporarily sets
UseExplorationPolicy to true for the
duration of the training,and then reverts it to the original value when the training
is completed.
Example: myagent.UseExplorationPolicy = true
Sample time of the agent, specified as a positive scalar or as -1.
Within a MATLAB® environment, the agent is executed every time the environment advances,
so, SampleTime does not affect the timing of the agent execution.
If SampleTime is set to -1, in MATLAB environments, the time interval between consecutive elements in the
returned output experience is considered equal to 1.
Within a Simulink® environment, the RL Agent block
that uses the agent object executes every SampleTime seconds of
simulation time. If SampleTime is set to -1 the
block inherits the sample time from its input signals. Set
SampleTime to -1 when the block is a child
of an event-driven subsystem.
Set SampleTime to a positive scalar when the block is not a child
of an event-driven subsystem. Doing so ensures that the block executes at appropriate
intervals when input signal sample times change due to model variations. If
SampleTime is a positive scalar, this value is also the time
interval between consecutive elements in the output experience returned by sim or
train,
regardless of the type of environment.
If SampleTime is set to -1, in Simulink environments, the time interval between consecutive elements in the
returned output experience reflects the timing of the events that trigger the RL Agent block
execution.
This property is shared between the agent and the agent options object within the agent. If you change this property in the agent options object, it also changes in the agent, and vice versa.
Example: myagent.SampleTime = -1 sets the sample time of the agent
object myagent to -1.
Option to use GPU for learning, specified as "off",
"on", or "auto".
Setting this option to "on" configures agent learnables, targets,
and optimizers for GPU usage during training. Specifically, this option lazily sets the
agent approximators UseDevice property. This setting will result in
an error if no GPU is available.
Setting this option to "auto" configures the agent learnables,
targets, and optimizers to use a GPU during training if one is available.
Setting this option to "off" configures the agent learnables,
targets, and optimizers to use the CPU during training.
The "gpu" option requires both Parallel Computing Toolbox™ software and a CUDA® enabled NVIDIA® GPU. For more information on supported GPUs see GPU Computing Requirements (Parallel Computing Toolbox).
You can use gpuDevice (Parallel Computing Toolbox) to query or select a local GPU device to be
used with MATLAB.
Note
Training or simulating an agent on a GPU involves device-specific numerical round-off errors. Because of these errors, you can get different results on a GPU and on a CPU for the same operation.
To speed up training by using parallel processing over multiple cores, you do not need
to use this property. Instead, set the UseParallel training option
to "on" or "auto". For more information about
training using multicore processors and GPUs for training, see Train Agents Using Parallel Computing and GPUs.
Example: myagent.UseGPUForLearning = "off"
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 |
getCritic | Extract critic from reinforcement learning agent |
setCritic | Set critic of reinforcement learning agent |
generatePolicyFunction | Generate MATLAB function that evaluates policy of an agent or policy object |
Examples
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 DQN Agent Using Deep Network Designer and Train Using Image Observations. This environment has two observation channels: one carrying a 50-by-50 grayscale image and the other carrying 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.
rng(0,"twister")Create a deep Q-network agent from the environment observation and action specifications.
agent = rlDQNAgent(obsInfo,actInfo);
To check your agent, use the getAction function to return the action from a batch of 10 random observations.
robs1 = rand([obsInfo(1).Dimension 10]);
robs2 = rand([obsInfo(2).Dimension 10]);
act = getAction(agent,{robs1,robs2});Display the seventh element in the batch.
act{1}(7)ans = -2
You can now test and train the agent within the environment.
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 DQN Agent Using Deep Network Designer and Train Using Image Observations. This environment has two observation channels: one carrying a 50-by-50 grayscale image and the other carrying 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);
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. To reproduce the results of this section, specify the seed and algorithm used for random number generation.
rng(0,"twister")Create a default deep Q-network agent from the environment observation and action specifications. Pass the initialization options object as the third argument.
agent = rlDQNAgent(obsInfo,actInfo,initOpts);
Extract the deep neural network from both the critic.
criticNet = getModel(getCritic(agent));
To verify that each hidden fully connected layer has 128 neurons, you can display the layers on the MATLAB® command window,
criticNet.Layers
or visualize the structure interactively using analyzeNetwork.
analyzeNetwork(criticNet)
Plot the critic network.
plot(criticNet)

To check your agent, use the getAction function to return the actions from a batch of 10 random observations.
obs1 = rand([obsInfo(1).Dimension 10]);
obs2 = rand([obsInfo(2).Dimension 10]);
act = getAction(agent,{obs1,obs2});Display the seventh element in the batch.
act{1}(7)ans = -1
You can now test and train the agent within the environment.
Create an environment object and obtain its observation and action specifications. For this example load the predefined environment used for the Train Default DQN Agent to Balance Discrete Cart-Pole example. 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.
Create the predefined environment.
env = rlPredefinedEnv("CartPole-Discrete");Get the observation and action specification objects.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
A DQN agent approximates the long-term reward, given observations and actions, using a parameterized Q-value function critic.
Because DQN agents have a discrete action space, you have the option to create a vector (that is, a multi-output) Q-value function critic, which is generally more efficient than a comparable single-output critic. A vector Q-value function is a mapping from an environment observation to a vector in which each element represents the expected discounted cumulative long-term reward when an agent starts from the state corresponding to the given observation and executes the action corresponding to the element number (and follows a given policy afterward).
To model the Q-value function within the critic, use a deep neural network. The network must have one input layer (which receives the content of the observation channel, as specified by obsInfo) and one output layer (which returns the vector of values for all the possible actions).
Define the network as an array of layer objects, and get the dimensions of the observation space (that is, prod(obsInfo.Dimension)) and the number of possible actions (that is, numel(actInfo.Elements)) directly from the environment specification objects.
dnn = [
featureInputLayer(prod(obsInfo.Dimension))
fullyConnectedLayer(24)
reluLayer
fullyConnectedLayer(24)
reluLayer
fullyConnectedLayer(numel(actInfo.Elements))
];Convert the network to a dlnetwork object ad display the number of weights.
dnn = dlnetwork(dnn); summary(dnn)
Initialized: true
Number of learnables: 770
Inputs:
1 'input' 4 features
Create the critic using rlVectorQValueFunction, the network dnn as well as the observation and action specifications.
critic = rlVectorQValueFunction(dnn,obsInfo,actInfo);
Check that the critic works with a random observation input.
getValue(critic,{rand(obsInfo.Dimension)})ans = 2×1 single column vector
-0.0361
0.0913
Create the DQN agent using the critic.
agent = rlDQNAgent(critic)
agent =
rlDQNAgent with properties:
ExperienceBuffer: [1×1 rl.replay.rlReplayMemory]
AgentOptions: [1×1 rl.option.rlDQNAgentOptions]
UseExplorationPolicy: 0
ObservationInfo: [1×1 rl.util.rlNumericSpec]
ActionInfo: [1×1 rl.util.rlFiniteSetSpec]
SampleTime: 1
UseGPUForLearning: "off"
IntrinsicReward: []
Specify agent options, including training options for the critic.
agent.AgentOptions.UseDoubleDQN=false;
agent.AgentOptions.TargetUpdateMethod="periodic";
agent.AgentOptions.TargetUpdateFrequency=4;
agent.AgentOptions.ExperienceBufferLength=100000;
agent.AgentOptions.DiscountFactor=0.99;
agent.AgentOptions.MiniBatchSize=256;
agent.AgentOptions.CriticOptimizerOptions.LearnRate=1e-2;
agent.AgentOptions.CriticOptimizerOptions.GradientThreshold=1;To check your agent, use the getAction function 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.
Create an environment object and obtain its observation and action specifications. For this example load the predefined environment used for the Train Default DQN Agent to Balance Discrete Cart-Pole example. 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, -10 N or 10 N.
Create the predefined environment.
env = rlPredefinedEnv("CartPole-Discrete");Get the observation and action specification objects.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
For DQN agents, you can use multi-output Q-value function critics, which are generally more efficient than comparable single-output critics. However, for this example, create a single-output Q-value function critic instead.
A Q-value function critic takes the current observation and an action as inputs and returns a single scalar as output (the estimated discounted cumulative long-term reward for taking the action from the state corresponding to the current observation, and following the policy thereafter).
To model the parameterized Q-value function within the critic, use a neural network with two input layers (one for the observation channel, as specified by obsInfo, and the other for the action channel, as specified by actInfo) and one output layer (which returns the scalar value).
Note that prod(obsInfo.Dimension) and prod(actInfo.Dimension) return the number of dimensions of the observation and action spaces, respectively, regardless of whether they are arranged as row vectors, column vectors, or matrices.
Define each network path as an array of layer objects, and assign names to the input and output layers of each path, so you can connect the paths.
% Observation path obsPath = [ featureInputLayer(prod(obsInfo.Dimension),Name="netOin") fullyConnectedLayer(24) reluLayer fullyConnectedLayer(24,Name="fcObsPath") ]; % Action path actPath = [ featureInputLayer(prod(actInfo.Dimension),Name="netAin") fullyConnectedLayer(24,Name="fcActPath") ]; % Common path (concatenate inputs along dim #1) commonPath = [ concatenationLayer(1,2,Name="cat") reluLayer fullyConnectedLayer(1,Name="out") ];
Assemble dlnetwork object.
net = dlnetwork; net = addLayers(net,obsPath); net = addLayers(net,actPath); net = addLayers(net,commonPath);
Connect layers.
net = connectLayers(net,"fcObsPath","cat/in1"); net = connectLayers(net,"fcActPath","cat/in2");
Plot network.
plot(net)

Initialize network and display the number of weights.
net = initialize(net); summary(net)
Initialized: true
Number of learnables: 817
Inputs:
1 'netOin' 4 features
2 'netAin' 1 features
Create the critic approximator object using net, the environment observation and action specifications, and the names of the network input layers to be connected with the environment observation and action channels. For more information, see rlQValueFunction.
critic = rlQValueFunction(net, ... obsInfo, ... actInfo, ... ObservationInputNames="netOin", ... ActionInputNames="netAin");
Check the critic with a random observation and action input.
getValue(critic,{rand(obsInfo.Dimension)},{rand(actInfo.Dimension)})ans = single
-0.0232
Create the DQN agent using the critic.
agent = rlDQNAgent(critic)
agent =
rlDQNAgent with properties:
ExperienceBuffer: [1×1 rl.replay.rlReplayMemory]
AgentOptions: [1×1 rl.option.rlDQNAgentOptions]
UseExplorationPolicy: 0
ObservationInfo: [1×1 rl.util.rlNumericSpec]
ActionInfo: [1×1 rl.util.rlFiniteSetSpec]
SampleTime: 1
UseGPUForLearning: "off"
IntrinsicReward: []
Specify agent options, including training options for the critic.
agent.AgentOptions.UseDoubleDQN=false;
agent.AgentOptions.TargetUpdateMethod="periodic";
agent.AgentOptions.TargetUpdateFrequency=4;
agent.AgentOptions.ExperienceBufferLength=100000;
agent.AgentOptions.DiscountFactor=0.99;
agent.AgentOptions.MiniBatchSize=256;
agent.AgentOptions.CriticOptimizerOptions.LearnRate=1e-2;
agent.AgentOptions.CriticOptimizerOptions.GradientThreshold=1;To check your agent, use the getAction function 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.
For this example load the predefined environment used for the Train Default DQN Agent to Balance Discrete Cart-Pole example. 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.
env = rlPredefinedEnv("CartPole-Discrete");Get the observation and action specification objects.
obsInfo = getObservationInfo(env); actInfo = getActionInfo(env);
For DQN agents, only the vector function approximator, rlVectorQValueFunction, supports recurrent neural networks models. The network must have one input layer (taking the content of the observation channel) and one output layer (returning the vector of values for all the possible actions).
Define the network as an array of layer objects. To create a recurrent neural network, use a sequenceInputLayer as the input layer and include at least one lstmLayer.
net = [
sequenceInputLayer(prod(obsInfo.Dimension))
fullyConnectedLayer(50)
reluLayer
lstmLayer(20,OutputMode="sequence");
fullyConnectedLayer(20)
reluLayer
fullyConnectedLayer(numel(actInfo.Elements))
];Convert to a dlnetwork object and display the number of weights.
net = dlnetwork(net); summary(net);
Initialized: true
Number of learnables: 6.4k
Inputs:
1 'sequenceinput' Sequence input with 4 channels
Create the critic approximator object using net and the environment specifications.
critic = rlVectorQValueFunction(net,obsInfo,actInfo);
Check your critic with a random input observation.
getValue(critic,{rand(obsInfo.Dimension)})ans = 2×1 single column vector
0.0136
0.0067
Define some training options for the critic.
criticOptions = rlOptimizerOptions( ... LearnRate=1e-3, ... GradientThreshold=1);
Specify options for creating the DQN agent. To use a recurrent neural network, you must specify a SequenceLength greater than 1.
agentOptions = rlDQNAgentOptions( ... UseDoubleDQN=false, ... TargetSmoothFactor=5e-3, ... ExperienceBufferLength=1e6, ... SequenceLength=32, ... CriticOptimizerOptions=criticOptions); agentOptions.EpsilonGreedyExploration.EpsilonDecay = 1e-4;
Create the agent. The actor and critic networks are initialized randomly.
agent = rlDQNAgent(critic,agentOptions)
agent =
rlDQNAgent with properties:
ExperienceBuffer: [1×1 rl.replay.rlReplayMemory]
AgentOptions: [1×1 rl.option.rlDQNAgentOptions]
UseExplorationPolicy: 0
ObservationInfo: [1×1 rl.util.rlNumericSpec]
ActionInfo: [1×1 rl.util.rlFiniteSetSpec]
SampleTime: 1
UseGPUForLearning: "off"
IntrinsicReward: []
Check your agent using getAction to return the action from a random observation.
getAction(agent,rand(obsInfo.Dimension))
ans = 1×1 cell array
{[-10]}
To evaluate the agent using sequential observations, use the sequence length (time) dimension. For example, obtain actions for a sequence of 9 observations. Note that batch processing is not supported for recurrent neural networks, so the size of the third dimension must be one.
[action,state] = getAction(agent, ...
{rand([obsInfo.Dimension 1 9])});Display the action corresponding to the seventh element of the observation.
action = action{1};
action(1,1,1,7)ans = -10
You can now test and train the agent within the environment.
Extended Capabilities
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Version History
Introduced in R2019a
See Also
Apps
Functions
getAction|getActor|getCritic|getModel|generatePolicyFunction|generatePolicyBlock|getActionInfo|getObservationInfo
Objects
rlDQNAgentOptions|rlAgentInitializationOptions|rlVectorQValueFunction|rlQValueFunction|rlQAgent|rlLSPIAgent|rlSARSAAgent
Blocks
Topics
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.
Web サイトの選択
Web サイトを選択すると、翻訳されたコンテンツにアクセスし、地域のイベントやサービスを確認できます。現在の位置情報に基づき、次のサイトの選択を推奨します:
また、以下のリストから Web サイトを選択することもできます。
最適なサイトパフォーマンスの取得方法
中国のサイト (中国語または英語) を選択することで、最適なサイトパフォーマンスが得られます。その他の国の MathWorks のサイトは、お客様の地域からのアクセスが最適化されていません。
南北アメリカ
- América Latina (Español)
- Canada (English)
- United States (English)
ヨーロッパ
- 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)