main content

create dqn agent using deep network designer and train using image observations -凯发k8网页登录

this example shows how to create a deep q-learning network (dqn) agent that can swing up and balance a pendulum modeled in matlab®. in this example, you create the dqn agent using deep network designer. for more information on dqn agents, see .

pendulum swing-up with image matlab environment

the reinforcement learning environment for this example is a simple frictionless pendulum that initially hangs in a downward position. the training goal is to make the pendulum stand upright without falling over using minimal control effort.

for this environment:

  • the upward balanced pendulum position is 0 radians, and the downward hanging position is pi radians.

  • the torque action signal from the agent to the environment can take any of the five possible integer values from –2 to 2 n·m.

  • the observations from the environment are the simplified grayscale image of the pendulum and the pendulum angle derivative.

  • the reward rt, provided at every time step, is

rt=-(θt2 0.1θt˙2 0.001ut-12)

here:

  • θt is the angle of displacement from the upright position.

  • θt˙ is the derivative of the displacement angle.

  • ut-1 is the control effort from the previous time step.

for more information on the continuous action space version of this model, see train ddpg agent to swing up and balance pendulum with image observation.

create environment interface

create a predefined environment interface for the pendulum.

env = rlpredefinedenv("simplependulumwithimage-discrete");

the interface has two observations. the first observation, named "pendimage", is a 50-by-50 grayscale image.

obsinfo = getobservationinfo(env);
obsinfo(1)
ans = 
  rlnumericspec with properties:
     lowerlimit: 0
     upperlimit: 1
           name: "pendimage"
    description: [0x0 string]
      dimension: [50 50]
       datatype: "double"

the second observation, named "angularrate", is the angular velocity of the pendulum.

obsinfo(2)
ans = 
  rlnumericspec with properties:
     lowerlimit: -inf
     upperlimit: inf
           name: "angularrate"
    description: [0x0 string]
      dimension: [1 1]
       datatype: "double"

the interface has a discrete action space where the agent can apply one of five possible torque values to the pendulum: –2, –1, 0, 1, or 2 n·m.

actinfo = getactioninfo(env)
actinfo = 
  rlfinitesetspec with properties:
       elements: [-2 -1 0 1 2]
           name: "torque"
    description: [0x0 string]
      dimension: [1 1]
       datatype: "double"

fix the random generator seed for reproducibility.

rng(0)

construct critic network using deep network designer

dqn agents use a parametrized q-value function approximator to estimate the value of the policy. since a dqn agent has a discrete action space, you can use a vector (that is multi-output) q-value function critic, which is generally more efficient than a comparable single-output critic. however, for this example, use a standard single-output q-value function critic.

to model the parametrized q-value function within the critic, use a neural network with three input layers (two for the observation channels, as specified by obsinfo, and the other for the action channel, as specified by actinfo) and one output layer (which returns the scalar value). for more information on creating q-value function representations based on a deep neural network, see create policies and value functions.

construct the critic network interactively by using the deep network designer app. to do so, you first create separate input paths for each observation and action. these paths learn lower-level features from their respective inputs. you then create a common output path that combines the outputs from the input paths.

create image observation path

to create the image observation path, first drag an imageinputlayer from the layer library pane to the canvas. set the layer inputsize to 50,50,1 for the image observation, and set normalization to none.

second, drag a convolution2dlayer to the canvas and connect the input of this layer to the output of the imageinputlayer. create a convolution layer with 2 filters (numfilters property) that have a height and width of 10 (filtersize property), and use a stride of 5 in the horizontal and vertical directions (stride property).

finally, complete the image path network with two sets of relulayer and fullyconnectedlayer layers. the output sizes of the first and second fullyconnectedlayer layers are 400 and 300, respectively.

create all input paths and output path

construct the other input paths and the output path in a similar manner. for this example, use the following options.

angular velocity path (scalar input):

  • imageinputlayer — set inputsize to 1,1 and normalization to none.

  • fullyconnectedlayer — set outputsize to 400.

  • relulayer

  • fullyconnectedlayer — set outputsize to 300.

action path (scalar input):

  • imageinputlayer — set inputsize to 1,1 and normalization to none.

  • fullyconnectedlayer — set outputsize to 300.

output path:

  • additionlayer — connect the output of all input paths to the input of this layer.

  • relulayer

  • fullyconnectedlayer — set outputsize to 1 for the scalar value function.

export network from deep network designer

to export the network to the matlab workspace, in deep network designer, click export. deep network designer exports the network as a new variable containing the network layers. you can create the critic representation using this layer network variable.

alternatively, to generate equivalent matlab code for the network, click export > generate code.

the generated code is as follows.

lgraph = layergraph();
templayers = [
    imageinputlayer([1 1 1],"name","angularrate","normalization","none")
    fullyconnectedlayer(400,"name","dtheta_fc1")
    relulayer("name","dtheta_relu1")
    fullyconnectedlayer(300,"name","dtheta_fc2")];
lgraph = addlayers(lgraph,templayers);
templayers = [
    imageinputlayer([1 1 1],"name","torque","normalization","none")
    fullyconnectedlayer(300,"name","torque_fc1")];
lgraph = addlayers(lgraph,templayers);
templayers = [
    imageinputlayer([50 50 1],"name","pendimage","normalization","none")
    convolution2dlayer([10 10],2,"name","img_conv1","padding","same","stride",[5 5])
    relulayer("name","relu_1")
    fullyconnectedlayer(400,"name","critic_theta_fc1")
    relulayer("name","theta_relu1")
    fullyconnectedlayer(300,"name","critic_theta_fc2")];
lgraph = addlayers(lgraph,templayers);
templayers = [
    additionlayer(3,"name","addition")
    relulayer("name","relu_2")
    fullyconnectedlayer(1,"name","statevalue")];
lgraph = addlayers(lgraph,templayers);
lgraph = connectlayers(lgraph,"torque_fc1","addition/in3");
lgraph = connectlayers(lgraph,"critic_theta_fc2","addition/in1");
lgraph = connectlayers(lgraph,"dtheta_fc2","addition/in2");

view the critic network configuration.

figure
plot(lgraph)

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

convert to a dlnetwork object and display the number of parameters.

net = dlnetwork(lgraph);
summary(net)
   initialized: true
   number of learnables: 322.9k
   inputs:
      1   'angularrate'   1x1x1 images
      2   'torque'        1x1x1 images
      3   'pendimage'     50x50x1 images

create the critic using the neural network, the action and observation specifications, and the names of the input layers to be connected to the observations and action channels. for more information, see rlqvaluefunction.

critic = rlqvaluefunction(net,obsinfo,actinfo,...
    "observationinputnames",["pendimage","angularrate"], ...
    "actioninputnames","torque");

specify options for the critic using rloptimizeroptions.

criticopts = rloptimizeroptions(learnrate=1e-03,gradientthreshold=1);

specify the dqn agent options using . include the training options for the actor and critic.

agentopts = rldqnagentoptions(...
    usedoubledqn=false,...
    criticoptimizeroptions=criticopts,...
    experiencebufferlength=1e6,...
    sampletime=env.ts);

you can also set or modify agent options using dot notation.

agentopts.epsilongreedyexploration.epsilondecay = 1e-5;

alternatively, you can create the agent first, and then modify its options using dot notation.

create the dqn agent using the critic and the agent options object. for more information, see .

agent = rldqnagent(critic,agentopts);

train agent

to train the agent, first specify the training options. for this example, use the following options.

  • run each training for at most 5000 episodes, with each episode lasting at most 500 time steps.

  • display the training progress in the episode manager dialog box (set the plots option) and disable the command line display (set the verbose option to false).

  • stop training when the agent receives an average cumulative reward greater than –1000 over the default window length of five consecutive episodes. at this point, the agent can quickly balance the pendulum in the upright position using minimal control effort.

for more information, see rltrainingoptions.

trainopts = rltrainingoptions(...
    maxepisodes=5000,...
    maxstepsperepisode=500,...
    verbose=false,...
    plots="training-progress",...
    stoptrainingcriteria="averagereward",...
    stoptrainingvalue=-1000);

visualize the pendulum system during training or simulation using the plot function.

plot(env)

figure simple pendulum visualizer contains 2 axes objects. axes object 1 contains 2 objects of type line, rectangle. axes object 2 contains an object of type image.

train the agent using the train function. this is a computationally intensive process that takes several hours to complete. to save time while running this example, load a pretrained agent by setting dotraining to false. to train the agent yourself, set dotraining to true.

dotraining = false;
if dotraining
    % train the agent.
    trainingstats = train(agent,env,trainopts);
else
    % load pretrained agent for the example.
    load("matlabpendimagedqn.mat","agent");
end

simulate dqn agent

to validate the performance of the trained agent, simulate it within the pendulum environment. for more information on agent simulation, see rlsimulationoptions and sim.

simoptions = rlsimulationoptions(maxsteps=500);
experience = sim(env,agent,simoptions);

figure simple pendulum visualizer contains 2 axes objects. axes object 1 contains 2 objects of type line, rectangle. axes object 2 contains an object of type image.

totalreward = sum(experience.reward)
totalreward = -713.0336

see also

apps

functions

objects

related examples

more about

网站地图