main content

option to accelerate computation of gradient for approximator object based on neural network -凯发k8网页登录

option to accelerate computation of gradient for approximator object based on neural network

since r2022a

description

example

newappx = accelerate(oldappx,useacceleration) returns the new neural-network-based function approximator object newappx, which has the same configuration as the original object, oldappx, and the option to accelerate the gradient computation set to the logical value useacceleration.

examples

create observation and action specification objects (or alternatively use getobservationinfo and getactioninfo to extract the specification objects from an environment). for this example, define an observation space with two channels. the first channel carries an observation from a continuous four-dimensional space. the second carries a discrete scalar observation that can be either zero or one. finally, the action space is a three-dimensional vector in a continuous action space.

obsinfo = [rlnumericspec([4 1]) 
           rlfinitesetspec([0 1])];
actinfo =  rlnumericspec([3 1]);

to approximate the q-value function within the critic, create a recurrent deep neural network. the output layer must be a scalar expressing the value of executing the action given the observation.

define each network path as an array of layer objects. get the dimensions of the observation and action spaces from the environment specification objects, and specify a name for the input layers, so you can later explicitly associate them with the appropriate environment channel. since the network is recurrent, use sequenceinputlayer as the input layer and include an lstmlayer as one of the other network layers.

% define paths
inpath1 = [ sequenceinputlayer( ...
                prod(obsinfo(1).dimension), ...
                name="netobsin1")
            fullyconnectedlayer(5,name="infc1") ];
inpath2 = [ sequenceinputlayer( ...
                prod(obsinfo(2).dimension), ...
                name="netobsin2")
            fullyconnectedlayer(5,name="infc2") ];
inpath3 = [ sequenceinputlayer( ...
                prod(actinfo(1).dimension), ...
                name="netactin")
            fullyconnectedlayer(5,name="infc3") ];
% concatenate 3 previous layer outputs along dim 1
jointpath = [ concatenationlayer(1,3,name="cct")
              tanhlayer
              lstmlayer(8,"outputmode","sequence")
              fullyconnectedlayer(1,name="jntfc") ];
% add layers to network object
net = layergraph;
net = addlayers(net,inpath1);
net = addlayers(net,inpath2);
net = addlayers(net,inpath3);
net = addlayers(net,jointpath);
% connect layers
net = connectlayers(net,"infc1","cct/in1");
net = connectlayers(net,"infc2","cct/in2");
net = connectlayers(net,"infc3","cct/in3");
% plot network
plot(net)

figure contains an axes object. the axes object contains an object of type graphplot.

% convert to dlnetwork and display number of weights
net = dlnetwork(net);
summary(net)
   initialized: true
   number of learnables: 832
   inputs:
      1   'netobsin1'   sequence input with 4 dimensions
      2   'netobsin2'   sequence input with 1 dimensions
      3   'netactin'    sequence input with 3 dimensions

create the critic with rlqvaluefunction, using the network, and the observation and action specification objects.

critic = rlqvaluefunction(net, ...
            obsinfo, ...
            actinfo, ...
            observationinputnames=["netobsin1","netobsin2"], ...
            actioninputnames="netactin");

to return the value of the actions as a function of the current observation, use getvalue or evaluate.

val = evaluate(critic, ...
                { rand(obsinfo(1).dimension), ...
                  rand(obsinfo(2).dimension), ...
                  rand(actinfo(1).dimension) })
val = 1x1 cell array
    {[0.1360]}

when you use evaluate, the result is a single-element cell array containing the value of the action in the input, given the observation.

val{1}
ans = single
    0.1360

calculate the gradients of the sum of the three outputs with respect to the inputs, given a random observation.

gro = gradient(critic,"output-input", ...
                { rand(obsinfo(1).dimension) , ...
                  rand(obsinfo(2).dimension) , ...
                  rand(actinfo(1).dimension) } )
gro=3×1 cell array
    {4x1 single}
    {[  0.0243]}
    {3x1 single}

the result is a cell array with as many elements as the number of input channels. each element contains the derivatives of the sum of the outputs with respect to each component of the input channel. display the gradient with respect to the element of the second channel.

gro{2}
ans = single
    0.0243

obtain the gradient with respect of five independent sequences, each one made of nine sequential observations.

gro_batch = gradient(critic,"output-input", ...
                { rand([obsinfo(1).dimension 5 9]) , ...
                  rand([obsinfo(2).dimension 5 9]) , ...
                  rand([actinfo(1).dimension 5 9]) } )
gro_batch=3×1 cell array
    {4x5x9 single}
    {1x5x9 single}
    {3x5x9 single}

display the derivative of the sum of the outputs with respect to the third observation element of the first input channel, after the seventh sequential observation in the fourth independent batch.

gro_batch{1}(3,4,7)
ans = single
    0.0108

set the option to accelerate the gradient computations.

critic = accelerate(critic,true);

calculate the gradients of the sum of the outputs with respect to the parameters, given a random observation.

grp = gradient(critic,"output-parameters", ...
                { rand(obsinfo(1).dimension) , ...
                  rand(obsinfo(2).dimension) , ...
                  rand(actinfo(1).dimension) } )
grp=11×1 cell array
    { 5x4  single                                                }
    { 5x1  single                                                }
    { 5x1  single                                                }
    { 5x1  single                                                }
    { 5x3  single                                                }
    { 5x1  single                                                }
    {32x15 single                                                }
    {32x8  single                                                }
    {32x1  single                                                }
    {[0.0444 0.1280 -0.1560 0.0193 0.0262 0.0453 -0.0186 -0.0651]}
    {[                                                         1]}

each array within a cell contains the gradient of the sum of the outputs with respect to a group of parameters.

grp_batch = gradient(critic,"output-parameters", ...
                { rand([obsinfo(1).dimension 5 9]) , ...
                  rand([obsinfo(2).dimension 5 9]) , ...
                  rand([actinfo(1).dimension 5 9]) } )
grp_batch=11×1 cell array
    { 5x4  single                                                 }
    { 5x1  single                                                 }
    { 5x1  single                                                 }
    { 5x1  single                                                 }
    { 5x3  single                                                 }
    { 5x1  single                                                 }
    {32x15 single                                                 }
    {32x8  single                                                 }
    {32x1  single                                                 }
    {[2.6325 10.1821 -14.0886 0.4162 2.0677 5.3991 0.3904 -8.9048]}
    {[                                                         45]}

if you use a batch of inputs, gradient uses the whole input sequence (in this case nine steps), and all the gradients with respect to the independent batch dimensions (in this case five) are added together. therefore, the returned gradient always has the same size as the output from .

create observation and action specification objects (or alternatively use getobservationinfo and getactioninfo to extract the specification objects from an environment). for this example, define an observation space with two channels. the first channel carries an observation from a continuous four-dimensional space. the second carries a discrete scalar observation that can be either zero or one. finally, the action space consist of a scalar that can be -1, 0, or 1.

obsinfo = [rlnumericspec([4 1]) 
           rlfinitesetspec([0 1])];
actinfo =  rlfinitesetspec([-1 0 1]);

create a deep neural network to be used as approximation model within the actor. the output layer must have three elements, each one expressing the value of executing the corresponding action, given the observation. to create a recurrent neural network, use sequenceinputlayer as the input layer and include an lstmlayer as one of the other network layers.

% define paths
inpath1 = [ sequenceinputlayer(prod(obsinfo(1).dimension))
            fullyconnectedlayer(prod(actinfo.dimension),name="fc1") ];
inpath2 = [ sequenceinputlayer(prod(obsinfo(2).dimension))
            fullyconnectedlayer(prod(actinfo.dimension),name="fc2") ];
% concatenate previous paths outputs along first dimension
jointpath = [ concatenationlayer(1,2,name="cct")
              tanhlayer;
              lstmlayer(8,outputmode="sequence");
              fullyconnectedlayer( ...
                prod(numel(actinfo.elements)), ...
                name="jntfc"); ];
% add layers to network object
net = layergraph;
net = addlayers(net,inpath1);
net = addlayers(net,inpath2);
net = addlayers(net,jointpath);
% connect layers
net = connectlayers(net,"fc1","cct/in1");
net = connectlayers(net,"fc2","cct/in2");
% plot network
plot(net)

figure contains an axes object. the axes object contains an object of type graphplot.

% convert to dlnetwork and display the number of weights
net = dlnetwork(net);
summary(net)
   initialized: true
   number of learnables: 386
   inputs:
      1   'sequenceinput'     sequence input with 4 dimensions
      2   'sequenceinput_1'   sequence input with 1 dimensions

since each element of the output layer must represent the probability of executing one of the possible actions the software automatically adds a softmaxlayer as a final output layer if you do not specify it explicitly.

create the actor with rldiscretecategoricalactor, using the network and the observations and action specification objects. when the network has multiple input layers, they are automatically associated with the environment observation channels according to the dimension specifications in obsinfo.

actor = rldiscretecategoricalactor(net, obsinfo, actinfo);

to return a vector of probabilities for each possible action, use evaluate.

[prob,state] = evaluate(actor, ...
                { rand(obsinfo(1).dimension) , ...
                  rand(obsinfo(2).dimension) });
prob{1}
ans = 3x1 single column vector
    0.3403
    0.3114
    0.3483

to return an action sampled from the distribution, use getaction.

act = getaction(actor, ...
                { rand(obsinfo(1).dimension) , ...
                  rand(obsinfo(2).dimension) });
act{1}
ans = 1

set the option to accelerate the gradient computations.

actor = accelerate(actor,true);

each array within a cell contains the gradient of the sum of the outputs with respect to a group of parameters.

grp_batch = gradient(actor,"output-parameters", ...
                        { rand([obsinfo(1).dimension 5 9]) , ...
                          rand([obsinfo(2).dimension 5 9])} )
grp_batch=9×1 cell array
    {[-3.1996e-09 -4.5687e-09 -4.4820e-09 -4.6439e-09]}
    {[                                    -1.1544e-08]}
    {[                                    -1.1321e-08]}
    {[                                    -2.8436e-08]}
    {32x2 single                                      }
    {32x8 single                                      }
    {32x1 single                                      }
    { 3x8 single                                      }
    { 3x1 single                                      }

if you use a batch of inputs, the gradient uses the whole input sequence (in this case nine steps), and all the gradients with respect to the independent batch dimensions (in this case five) are added together. therefore, the returned gradient always has the same size as the output from .

input arguments

function approximator object, specified as one of the following:

option to use acceleration for gradient computations, specified as a logical value. when useacceleration is true, the gradient computations are accelerated by optimizing and caching some inputs needed by the automatic-differentiation computation graph. for more information, see .

output arguments

new actor or critic, returned as an approximator object with the same type as oldappx but with the gradient acceleration option set to useacceleration.

version history

introduced in r2022a

网站地图