Main Content

rlQValueFunction

Q-Value function approximator object for reinforcement learning agents

Description

This object implements a Q-value function approximator that you can use as a critic for a reinforcement learning agent. A Q-value function maps an environment state-action pair to a scalar value representing the predicted discounted cumulative long-term reward when the agent starts from the given state and executes the given action. A Q-value function critic therefore needs both the environment state and an action as inputs. After you create an rlQValueFunction critic, use it to create an agent such as rlQAgent, rlDQNAgent, rlSARSAAgent, rlDDPGAgent, or rlTD3Agent. For more information on creating representations, see Create Policies and Value Functions.

Creation

Description

example

critic = rlQValueFunction(net,observationInfo,actionInfo) creates the Q-value function object critic. Here, net is the deep neural network used as an approximator, and it must have both observation and action as inputs and a single scalar output. The network input layers are automatically associated with the environment observation and action channels according to the dimension specifications in observationInfo and actionInfo. This function sets the ObservationInfo and ActionInfo properties of critic to the observationInfo and actionInfo input arguments, respectively.

example

critic = rlQValueFunction(tab,observationInfo,actionInfo) creates the Q-value function object critic with discrete action and observation spaces from the Q-value table tab. tab is a rlTable object containing a table with as many rows as the number of possible observations and as many columns as the number of possible actions. The function sets the ObservationInfo and ActionInfo properties of critic respectively to the observationInfo and actionInfo input arguments, which in this case must be scalar rlFiniteSetSpec objects.

example

critic = rlQValueFunction({basisFcn,W0},observationInfo,actionInfo) creates a Q-value function object critic using a custom basis function as underlying approximator. The first input argument is a two-element cell array whose first element is the handle basisFcn to a custom basis function and whose second element is the initial weight vector W0. Here the basis function must have both observation and action as inputs and W0 must be a column vector. The function sets the ObservationInfo and ActionInfo properties of critic to the observationInfo and actionInfo input arguments, respectively.

example

critic = rlQValueFunction(___,Name=Value) specifies one or more name-value arguments. You can specify the input and output layer names (to mandate their association with the environment observation and action channels) for deep neural network approximators. For all types of approximators, you can specify the computation device, for example UseDevice="gpu".

Input Arguments

expand all

Deep neural network used as the underlying approximator within the critic, specified as one of the following:

The network must have both the environment observation and action as inputs and a single scalar as output.

Note

Among the different network representation options, dlnetwork is preferred, since it has built-in validation checks and supports automatic differentiation. If you pass another network object as an input argument, it is internally converted to a dlnetwork object. However, best practice is to convert other representations to dlnetwork explicitly before using it to create a critic or an actor for a reinforcement learning agent. You can do so using dlnet=dlnetwork(net), where net is any Deep Learning Toolbox™ neural network object. The resulting dlnet is the dlnetwork object that you use for your critic or actor. This practice allows a greater level of insight and control for cases in which the conversion is not straightforward and might require additional specifications.

rlQValueFunction objects support recurrent deep neural networks.

The learnable parameters of the critic are the weights of the deep neural network. For a list of deep neural network layers, see List of Deep Learning Layers. For more information on creating deep neural networks for reinforcement learning, see Create Policies and Value Functions.

Q-value table, specified as an rlTable object containing an array with as many rows as the possible observations and as many columns as the possible actions. The element (s,a) is the expected cumulative long-term reward for taking action a from observed state s. The elements of this array are the learnable parameters of the critic.

Custom basis function, specified as a function handle to a user-defined MATLAB function. The user defined function can either be an anonymous function or a function on the MATLAB path. The output of the critic is the scalar c = W'*B, where W is a weight vector containing the learnable parameters, and B is the column vector returned by the custom basis function.

Your basis function must have the following signature.

B = myBasisFunction(obs1,obs2,...,obsN,act)

Here, obs1 to obsN are inputs in the same order and with the same data type and dimensions as the environment observation channels defined in observationInfo and act is an input with the same data type and dimension as the environment action channel defined in actionInfo.

For an example on how to use a basis function to create a Q-value function critic with a mixed continuous and discrete observation space, see Create Mixed Observation Space Q-Value Function Critic from Custom Basis Function.

Example: @(obs1,obs2,act) [act(2)*obs1(1)^2; abs(obs2(5)+act(1))]

Initial value of the basis function weights W, specified as a column vector having the same length as the vector returned by the basis function.

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Example: UseDevice="gpu"

Network input layers name corresponding to the environment action channel, specified as a string array or a cell array of character vectors. The function assigns the environment action channel specified in actionInfo to the specified network input layer. Therefore, the specified network input layer must have the same data type and dimensions as defined in actionInfo.

Note

The function does not use the name or the description (if any) of the action channel specified in actionInfo.

This name-value argument is supported only when the approximation model is a deep neural network.

Example: ActionInputNames="myNetOutput_Force"

Network input layers names corresponding to the environment observation channels, specified as a string array or a cell array of character vectors. The function assigns, in sequential order, each environment observation channel specified in observationInfo to each specified network input layer. Therefore, the specified network input layers, ordered as indicated in this argument, must have the same data type and dimensions as the observation specifications, as ordered in observationInfo.

Note

Of the information specified in observationInfo, the function uses only the data type and dimension of each channel, but not its (optional) name or description.

This name-value argument is supported only when the approximation model is a deep neural network.

Example: ObservationInputNames={"NetInput1_airspeed","NetInput2_altitude"}

Properties

expand all

Observation specifications, specified as an rlFiniteSetSpec or rlNumericSpec object or an array containing a mix of such objects. Each element in the array defines the properties of an environment observation channel, such as its dimensions, data type, and name. Note that only the data type and dimension of a channel are used by the software to create actors or critics, but not its (optional) name.

rlQValueFucntion sets the ObservationInfo property of critic to the input argument observationInfo.

You can extract ObservationInfo from an existing environment or agent using getObservationInfo. You can also construct the specifications manually.

Action specifications, specified as an rlFiniteSetSpec or rlNumericSpec object. This object defines the properties of the environment action channel, such as its dimensions, data type, and name. Note that the function does not use the name of the action channel specified in actionInfo.

Note

Only one action channel is allowed.

rlQValueRepresentation sets the ActionInfo property of critic to the input actionInfo.

You can extract ActionInfo from an existing environment or agent using getActionInfo. You can also construct the specifications manually.

Computation device used to perform operations such as gradient computation, parameter update and prediction during training and simulation, specified as either "cpu" or "gpu".

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. These errors can produce different results compared to performing the same operations a CPU.

To speed up training by using parallel processing over multiple cores, you do not need to use this argument. Instead, when training your agent, use an rlTrainingOptions object in which the UseParallel option is set to true. For more information about training using multicore processors and GPUs for training, see Train Agents Using Parallel Computing and GPUs.

Example: "gpu"

Object Functions

rlDDPGAgentDeep deterministic policy gradient (DDPG) reinforcement learning agent
rlTD3AgentTwin-delayed deep deterministic policy gradient reinforcement learning agent
rlDQNAgentDeep Q-network (DQN) reinforcement learning agent
rlQAgentQ-learning reinforcement learning agent
rlSARSAAgentSARSA reinforcement learning agent
rlSACAgentSoft actor-critic reinforcement learning agent
getValueObtain estimated value from a critic given environment observations and actions
getMaxQValueObtain maximum estimated value over all possible actions from a Q-value function critic with discrete action space, given environment observations
evaluateEvaluate function approximator object given observation (or observation-action) input data
gradientEvaluate gradient of function approximator object given observation and action input data
accelerateOption to accelerate computation of gradient for approximator object based on neural network
getLearnableParametersObtain learnable parameter values from agent, function approximator, or policy object
setLearnableParametersSet learnable parameter values of agent, function approximator, or policy object
setModelSet function approximation model for actor or critic
getModelGet function approximator model from actor or critic

Examples

collapse all

Create an observation specification object (or alternatively use getObservationInfo to extract the specification object from an environment). For this example, define the observation space as a continuous four-dimensional space, so that a single observation is a column vector containing four doubles.

obsInfo = rlNumericSpec([4 1]);

Create an action specification object (or alternatively use getActionInfo to extract the specification object from an environment). For this example, define the action space as a continuous two-dimensional space, so that a single action is a column vector containing two doubles.

actInfo = rlNumericSpec([2 1]);

To approximate the Q-value function within the critic, use a deep neural network.

The network must have two inputs, one for the observation and one for the action. The observation input must accept a four-element vector (the observation vector defined by obsInfo). The action input must accept a two-element vector (the action vector defined by actInfo). The output of the network must be a scalar, representing the expected cumulative long-term reward when the agent starts from the given observation and takes the given action.

You can also obtain the number of observations from the obsInfo specification (regardless of whether the observation space is a column vector, row vector, or matrix, prod(obsInfo.Dimension) is its total number of dimensions, in this case four, similarly, prod(actInfo.Dimension) is the number of dimension of the action space, in the case two).

Create the network as an array of layer objects.

% Observation path layers
obsPath = [featureInputLayer(prod(obsInfo.Dimension))
           fullyConnectedLayer(5)
           reluLayer
           fullyConnectedLayer(5,Name="obsout")];

% Action path layers
actPath = [featureInputLayer(prod(actInfo.Dimension))
           fullyConnectedLayer(5)
           reluLayer
           fullyConnectedLayer(5,Name="actout")];

% Common path to output layers
% Concatenate two layers along dimension one
comPath = [concatenationLayer(1,2,Name="cct")
           fullyConnectedLayer(5)
           reluLayer    
           fullyConnectedLayer(1, Name="output")];

% Add layers to network object
net = addLayers(layerGraph(obsPath),actPath); 
net = addLayers(net,comPath);

% Connect layers
net = connectLayers(net,"obsout","cct/in1");
net = connectLayers(net,"actout","cct/in2");

% Plot network
plot(net)

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

% Convert the network to a dlnetwork object
net = dlnetwork(net);

% Summarize properties
summary(net)
   Initialized: true

   Number of learnables: 161

   Inputs:
      1   'input'     4 features
      2   'input_1'   2 features

Create the critic with rlQValueFunction, using the network as well as the observations and action specification objects. When using this syntax, the network input layers are automatically associated with the components of the observation and action signals according to the dimension specifications in obsInfo and actInfo.

critic = rlQValueFunction(net,obsInfo,actInfo)
critic = 
  rlQValueFunction with properties:

    ObservationInfo: [1x1 rl.util.rlNumericSpec]
         ActionInfo: [1x1 rl.util.rlNumericSpec]
          UseDevice: "cpu"

To check your critic, use the getValue function to return the value of a random observation and action, given the current network weights.

v = getValue(critic, ...
    {rand(obsInfo.Dimension)}, ...
    {rand(actInfo.Dimension)})
v = single
    -1.1006

You can now use the critic (along with an with an actor) to create an agent relying on a Q-value function critic (such as rlQAgent, rlDQNAgent, rlSARSAAgent, or rlDDPGAgent).

Create an observation specification object (or alternatively use getObservationInfo to extract the specification object from an environment). For this example, define the observation space as a continuous four-dimensional space, so that a single observation is a column vector containing four doubles.

obsInfo = rlNumericSpec([4 1]);

Create an action specification object (or alternatively use getActionInfo to extract the specification object from an environment). For this example, define the action space as a continuous two-dimensional space, so that a single action is a column vector containing two doubles.

actInfo = rlNumericSpec([2 1]);

To approximate the Q-value function within the critic, use a deep neural network .

The network must have two inputs, one for the observation and one for the action. The observation input (here called netObsInput) must accept a four-element vector (the observation vector defined by obsInfo). The action input (here called netActInput) must accept a two-element vector (the action vector defined by actInfo). The output of the network must be a scalar, representing the expected cumulative long-term reward when the agent starts from the given observation and takes the given action.

You can also obtain the number of observations from the obsInfo specification object (regardless of whether the observation space is a column vector, row vector, or matrix, prod(obsInfo.Dimension) is its number of dimensions, in this case four, similarly, prod(actInfo.Dimension) is the number of dimension of the action space, in the case two).

To create the neural network paths, use vectors of layer objects. Name the network input layers for the observation and action netObsInput and netActInput, respectively.

% Observation path layers
obsPath = [featureInputLayer( ...
                prod(obsInfo.Dimension), ...
                Name="netObsInput") 
           fullyConnectedLayer(5)
           reluLayer
           fullyConnectedLayer(5,Name="obsout")];

% Action path layers
actPath = [featureInputLayer( ...
                prod(actInfo.Dimension), ...
                Name="netActInput") 
           fullyConnectedLayer(5)
           reluLayer
           fullyConnectedLayer(5,Name="actout")];

% Common path to output layers 
% Concatenate two layers along dimension one
comPath = [concatenationLayer(1,2,Name="cct")
           fullyConnectedLayer(5)
           reluLayer
           fullyConnectedLayer(1, Name="output")];

% Add layers to network object
net = addLayers(layerGraph(obsPath),actPath); 
net = addLayers(net,comPath);

% Connect layers
net = connectLayers(net,"obsout","cct/in1");
net = connectLayers(net,"actout","cct/in2");

% Plot network
plot(net)

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

% Convert to dlnetwork object
net = dlnetwork(net);

% Summarize properties
summary(net);
   Initialized: true

   Number of learnables: 161

   Inputs:
      1   'netObsInput'   4 features
      2   'netActInput'   2 features

Create the critic with rlQValueFunction, using the network, the observations and action specification objects, and the names of the network input layers to be associated with the observation and action from the environment.

critic = rlQValueFunction(net,...
             obsInfo,actInfo, ...
             ObservationInputNames="netObsInput",...
             ActionInputNames="netActInput")
critic = 
  rlQValueFunction with properties:

    ObservationInfo: [1x1 rl.util.rlNumericSpec]
         ActionInfo: [1x1 rl.util.rlNumericSpec]
          UseDevice: "cpu"

To check your critic, use the getValue function to return the value of a random observation and action, given the current network weights.

v = getValue(critic, ...
    {rand(obsInfo.Dimension)}, ...
    {rand(actInfo.Dimension)})
v = single
    -1.1006

You can now use the critic (along with an with an actor) to create an agent relying on a Q-value function critic (such as rlQAgent, rlDQNAgent, rlSARSAAgent, or rlDDPGAgent).

Create a finite set observation specification object (or alternatively use getObservationInfo to extract the specification object from an environment with a discrete observation space). For this example define the observation space as a finite set with of four possible values.

obsInfo = rlFiniteSetSpec([7 5 3 1]);

Create a finite set action specification object (or alternatively use getActionInfo to extract the specification object from an environment with a discrete action space). For this example define the action space as a finite set with 2 possible values.

actInfo = rlFiniteSetSpec([4 8]);

Create a table to approximate the value function within the critic. rlTable creates a value table object from the observation and action specifications objects.

qTable = rlTable(obsInfo,actInfo);

The table stores a value (representing the expected cumulative long term reward) for each possible observation-action pair. Each row corresponds to an observation and each column corresponds to an action. You can access the table using the Table property of the vTable object. The initial value of each element is zero.

qTable.Table
ans = 4×2

     0     0
     0     0
     0     0
     0     0

You can initialize the table to any value, in this case an array containing the integer from 1 through 8.

qTable.Table=reshape(1:8,4,2)
qTable = 
  rlTable with properties:

    Table: [4x2 double]

Create the critic using the table as well as the observations and action specification objects.

critic = rlQValueFunction(qTable,obsInfo,actInfo)
critic = 
  rlQValueFunction with properties:

    ObservationInfo: [1x1 rl.util.rlFiniteSetSpec]
         ActionInfo: [1x1 rl.util.rlFiniteSetSpec]
          UseDevice: "cpu"

To check your critic, use the getValue function to return the value of a given observation and action, using the current table entries.

v = getValue(critic,{5},{8})
v = 6

You can now use the critic (along with an with an actor) to create a discrete action space agent relying on a Q-value function critic (such as rlQAgent, rlDQNAgent, or rlSARSAAgent).

Create an observation specification object (or alternatively use getObservationInfo to extract the specification object from an environment). For this example, define the observation space as a continuous three-dimensional space, so that a single observation is a column vector containing three doubles.

obsInfo = rlNumericSpec([3 1]);

Create an action specification object (or alternatively use getActionInfo to extract the specification object from an environment). For this example, define the action space as a continuous two-dimensional space, so that a single action is a column vector containing two doubles.

actInfo = rlNumericSpec([2 1]);

Create a custom basis function to approximate the value function within the critic. The custom basis function must return a column vector. Each vector element must be a function of the observations and actions respectively defined by obsInfo and actInfo.

myBasisFcn = @(myobs,myact) [ ...
    myobs(2)^2; ...
    myobs(1)+exp(myact(1)); ...
    abs(myact(2)); ...
    myobs(3) ]
myBasisFcn = function_handle with value:
    @(myobs,myact)[myobs(2)^2;myobs(1)+exp(myact(1));abs(myact(2));myobs(3)]

The output of the critic is the scalar W'*myBasisFcn(myobs,myact), where W is a weight column vector which must have the same size of the custom basis function output. This output is the expected cumulative long term reward when the agent starts from the given observation and takes the best possible action. The elements of W are the learnable parameters.

Define an initial parameter vector.

W0 = [1;4;4;2];

Create the critic. The first argument is a two-element cell containing both the handle to the custom function and the initial weight vector. The second and third arguments are, respectively, the observation and action specification objects.

critic = rlQValueFunction({myBasisFcn,W0}, ...
    obsInfo,actInfo)
critic = 
  rlQValueFunction with properties:

    ObservationInfo: [1x1 rl.util.rlNumericSpec]
         ActionInfo: [1x1 rl.util.rlNumericSpec]
          UseDevice: "cpu"

To check your critic, use getValue to return the value of a given observation-action pair, using the current parameter vector.

v = getValue(critic,{[1 2 3]'},{[4 5]'})
v = 252.3926

You can now use the critic (along with an with an actor) to create an agent relying on a Q-value function critic (such as rlQAgent, rlDQNAgent, rlSARSAAgent, or rlDDPGAgent).

Create an observation specification object (or alternatively use getObservationInfo to extract the specification object from an environment). For this example, define the observation space as consisting of two channels, the first is a vector over a continuous two-dimensional space and the second is a vector over a three-dimensional space that can assume only four values.

obsInfo = [rlNumericSpec([1 2]) 
           rlFiniteSetSpec({[1 0 -1], ...
                            [-1 2 1], ...
                            [0.1 0.2 0.3], ...
                            [0 0 0]})];

Create an action specification object (or alternatively use getActionInfo to extract the specification object from an environment). For this example, define the action space as discrete set consisting of three possible actions, 1, 2, and 3.

actInfo = rlFiniteSetSpec({1,2,3});

Create a custom basis function to approximate the value function within the critic. The custom basis function must return a column vector. Each vector element must be a function of the observations and the action respectively defined by obsInfo and actInfo. Note that the selected action, as defined, has only one element, while each observation channel has two elements.

myBasisFcn = @(obsA,obsB,act) [obsA(1)+obsB(2)+obsB(3)+act(1);
                               obsA(2)+obsB(1)+obsB(2)-act(1);
                               obsA(1)+obsB(2)+obsB(3)+act(1)^2;
                               obsA(1)+obsB(1)+obsB(2)-act(1)^2];

The output of the critic is the scalar W'*myBasisFcn(obsA,obsB,act), where W is a weight column vector that must have the same size of the custom basis function output. This output is the expected cumulative long term reward when the agent starts from the given observation and takes the action specified as last input. The elements of W are the learnable parameters.

Define an initial parameter vector.

W0 = ones(4,1);

Create the critic. The first argument is a two-element cell containing both the handle to the custom function and the initial weight vector. The second and third arguments are, respectively, the observation and action specification objects.

critic = rlQValueFunction({myBasisFcn,W0},obsInfo,actInfo)
critic = 
  rlQValueFunction with properties:

    ObservationInfo: [2x1 rl.util.RLDataSpec]
         ActionInfo: [1x1 rl.util.rlFiniteSetSpec]
          UseDevice: "cpu"

To check your critic, use the getValue function to return the value of a given observation-action pair, using the current parameter vector.

v = getValue(critic,{[-0.5 0.6],[1 0 -1]},{3})
v = -0.9000

Note that the critic does not enforce the set constraint for the discrete set elements.

v = getValue(critic,{[-0.5 0.6],[10 -10 -0.05]},{33})
v = -21.0000

You can now use the critic (along with an with an actor) to create an agent with a discrete action space relying on a Q-value function critic (such as rlQAgent, rlDQNAgent, or rlSARSAAgent).

Version History

Introduced in R2022a