main content

train ddpg agent to control sliding robot -凯发k8网页登录

this example shows how to train a deep deterministic policy gradient (ddpg) agent to generate trajectories for a robot sliding without friction over a @d plane, modeled in simulink®. for more information on ddpg agents, see .

flying robot model

the reinforcement learning environment for this example is a sliding robot with its initial condition randomized around a ring having a radius of 15 m. the orientation of the robot is also randomized. the robot has two thrusters mounted on the side of the body that are used to propel and steer the robot. the training goal is to drive the robot from its initial condition to the origin facing east.

open the model.

mdl = "rlflyingrobotenv";
open_system(mdl)

set the initial model state variables.

theta0 = 0;
x0 = -15;
y0 = 0;

define the sample time ts and the simulation duration tf.

ts = 0.4;
tf = 30;

for this model:

  • the goal orientation is 0 rad (robot facing east).

  • the thrust from each actuator is bounded from -1 to 1 n

  • the observations from the environment are the position, orientation (sine and cosine of orientation), velocity, and angular velocity of the robot.

  • the reward rt provided at every time step is

r1=10((xt2 yt2 θt2)<0.5)

r2=-100(|xt|20|||yt|20)

r3=-(0.2(rt-1 lt-1)2 0.3(rt-1-lt-1)2 0.03xt2 0.03yt2 0.02θt2)

rt=r1 r2 r3

where:

  • xt is the position of the robot along the x-axis.

  • yt is the position of the robot along the y-axis.

  • θt is the orientation of the robot.

  • lt-1 is the control effort from the left thruster.

  • rt-1 is the control effort from the right thruster.

  • r1 is the reward when the robot is close to the goal.

  • r2 is the penalty when the robot drives beyond 20 m in either the x or y direction. the simulation is terminated when r2<0.

  • r3 is a qr penalty that penalizes distance from the goal and control effort.

create integrated model

to train an agent for the flyingrobotenv model, use the createintegratedenv function to automatically generate a simulink model containing an rl agent block that is ready for training.

integratedmdl = "integratedflyingrobot";
[~,agentblk,obsinfo,actinfo] = ...
    createintegratedenv(mdl,integratedmdl);

actions and observations

before creating the environment object, specify names for the observation and action specifications, and bound the thrust actions between -1 and 1.

the observation vector for this environment is [xyx˙y˙sin(θ)cos(θ)θ˙]t. assign a name to the environment observation channel.

obsinfo.name = "observations";

the action vector for this environment is [trtl]t. assign a name, as well as upper and lower limits, to the environment action channel.

actinfo.name = "thrusts";
actinfo.lowerlimit = -ones(prod(actinfo.dimension),1);
actinfo.upperlimit =  ones(prod(actinfo.dimension),1);

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.

create environment object

create an environment object using the integrated simulink model.

env = rlsimulinkenv( ...
    integratedmdl, ...
    agentblk, ...
    obsinfo, ...
    actinfo);

reset function

create a custom reset function that randomizes the initial position of the robot along a ring of radius 15 m and the initial orientation. for details on the reset function, see flyingrobotresetfcn.

env.resetfcn = @(in) flyingrobotresetfcn(in);

fix the random generator seed for reproducibility.

rng(0)

create ddpg agent

ddpg agents use a parametrized q-value function approximator to estimate the value of the policy. 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 given the action from the state corresponding to the current observation, and following the policy thereafter).

to model the parametrized 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).

define each network path as an array of layer objects. assign names to the input and output layers of each path. these names allow you to connect the paths and then later explicitly associate the network input and output layers with the appropriate environment channel.

% specify the number of outputs for the hidden layers.
hiddenlayersize = 100; 
% define observation path layers
observationpath = [
    featureinputlayer( ...
        prod(obsinfo.dimension),name="obsinlyr")
    fullyconnectedlayer(hiddenlayersize)
    relulayer
    fullyconnectedlayer(hiddenlayersize)
    additionlayer(2,name="add")
    relulayer
    fullyconnectedlayer(hiddenlayersize)
    relulayer
    fullyconnectedlayer(1,name="fc4")
    ];
% define action path layers
actionpath = [
    featureinputlayer( ...
        prod(actinfo.dimension), ...
        name="actinlyr")
    fullyconnectedlayer(hiddenlayersize,name="fc5")
    ];
% create the layer graph.
criticnetwork = layergraph(observationpath);
criticnetwork = addlayers(criticnetwork,actionpath);
% connect actionpath to observationpath.
criticnetwork = connectlayers(criticnetwork,"fc5","add/in2");
% create dlnetwork from layer graph
criticnetwork = dlnetwork(criticnetwork);
% display the number of parameters
summary(criticnetwork)
   initialized: true
   number of learnables: 21.4k
   inputs:
      1   'obsinlyr'   7 features
      2   'actinlyr'   2 features

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

critic = rlqvaluefunction(criticnetwork,obsinfo,actinfo,...
    observationinputnames="obsinlyr",actioninputnames="actinlyr");

ddpg agents use a parametrized deterministic policy over continuous action spaces, which is learned by a continuous deterministic actor. this actor takes the current observation as input and returns as output an action that is a deterministic function of the observation.

to model the parametrized policy within the actor, use a neural network with one input layer (which receives the content of the environment observation channel, as specified by obsinfo) and one output layer (which returns the action to the environment action channel, as specified by actinfo).

define the network as an array of layer objects.

actornetwork = [
    featureinputlayer(prod(obsinfo.dimension))
    fullyconnectedlayer(hiddenlayersize)
    relulayer
    fullyconnectedlayer(hiddenlayersize)
    relulayer
    fullyconnectedlayer(hiddenlayersize)
    relulayer
    fullyconnectedlayer(prod(actinfo.dimension))
    tanhlayer
    ];

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

actornetwork = dlnetwork(actornetwork);
summary(actornetwork)
   initialized: true
   number of learnables: 21.2k
   inputs:
      1   'input'   7 features

define the actor using actornetwork, and the specifications for the action and observation channels. for more information, see rlcontinuousdeterministicactor.

actor = rlcontinuousdeterministicactor(actornetwork,obsinfo,actinfo);

specify options for the critic and the actor using rloptimizeroptions.

criticoptions = rloptimizeroptions(learnrate=1e-03,gradientthreshold=1);
actoroptions = rloptimizeroptions(learnrate=1e-04,gradientthreshold=1);

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

agentoptions = rlddpgagentoptions(...
    sampletime=ts,...
    actoroptimizeroptions=actoroptions,...
    criticoptimizeroptions=criticoptions,...
    experiencebufferlength=1e6 ,...
    minibatchsize=256);
agentoptions.noiseoptions.variance = 1e-1;
agentoptions.noiseoptions.variancedecayrate = 1e-6;

then, create the agent using the actor, the critic and the agent options. for more information, see .

agent = rlddpgagent(actor,critic,agentoptions);

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

train agent

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

  • run each training for at most 20000 episodes, with each episode lasting at most ceil(tf/ts) 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 415 over 10 consecutive episodes. at this point, the agent can drive the sliding robot to the goal position.

  • save a copy of the agent for each episode where the cumulative reward is greater than 415.

for more information, see rltrainingoptions.

maxepisodes = 20000;
maxsteps = ceil(tf/ts);
trainingoptions = rltrainingoptions(...
    maxepisodes=maxepisodes,...
    maxstepsperepisode=maxsteps,...
    stoponerror="on",...
    verbose=false,...
    plots="training-progress",...
    stoptrainingcriteria="averagereward",...
    stoptrainingvalue=415,...
    scoreaveragingwindowlength=10,...
    saveagentcriteria="episodereward",...
    saveagentvalue=415); 

train the agent using the train function. training 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,trainingoptions);
else
    % load the pretrained agent for the example.
    load("flyingrobotddpg.mat","agent")
end

simulate ddpg agent

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

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

figure flying robot visualizer contains an axes object. the axes object contains 3 objects of type quiver, patch, line.

see also

functions

objects

blocks

related examples

more about

网站地图