train dqn agent for lane keeping assist using parallel computing -凯发k8网页登录
this example shows how to train a deep q-learning network (dqn) agent for lane keeping assist (lka) in simulink® using parallel training. for an example that shows how to train the agent without using parallel training, see train dqn agent for lane keeping assist.
for more information on dqn agents, see . for an example that trains a dqn agent in matlab®, see train dqn agent to balance cart-pole system.
dqn parallel training overview
dqn agents use experience-based parallelization, in which the environment simulation is done by the workers and the gradient computation is done by the client. specifically, each worker generates new experiences from its copy of agent and environment and sends experience data back to the client. the client agent updates its parameters as follows.
for asynchronous training, the client agent calculates gradients and updates agent parameters from the received experiences, without waiting to receive experiences from all the workers. the client then sends the updated parameters back to the worker that provided the experiences. then, the worker updates its copy of the agent and continues to generate experiences using its copy of the environment. to specify asynchronous training, the
mode
property of therltrainingoptions
object that you pass to the train function must be set toasync
.for synchronous training, the client agent waits to receive experiences from all of the workers and then calculates the gradients from all these experiences. the client updates the agent parameters, and sends the updated parameters to all the workers at the same time. then, all workers use a single updated agent copy, together with their copy of the environment, to generate experiences. to specify synchronous training, the
mode
property of therltrainingoptions
object that you pass to the train function must be set tosync
.
for more information on experience-based parallelization, see train agents using parallel computing and gpus.
simulink model for ego car
the reinforcement learning environment for this example is a simple bicycle model for the ego vehicle dynamics. the training goal is to keep the ego vehicle traveling along the centerline of the lanes by adjusting the front steering angle. this example uses the same vehicle model as train dqn agent for lane keeping assist.
m = 1575; % total vehicle mass (kg) iz = 2875; % yaw moment of inertia (mns^2) lf = 1.2; % longitudinal distance from center of gravity to front tires (m) lr = 1.6; % longitudinal distance from center of gravity to rear tires (m) cf = 19000; % cornering stiffness of front tires (n/rad) cr = 33000; % cornering stiffness of rear tires (n/rad) vx = 15; % longitudinal velocity (m/s)
define the sample time ts
and simulation duration t
in seconds.
ts = 0.1; t = 15;
the output of the lka system is the front steering angle of the ego car. to simulate the physical steering limits of the ego car, constrain the steering angle to the range [–0.5,0.5]
rad.
u_min = -0.5; u_max = 0.5;
the curvature of the road is defined by a constant 0.001 (). the initial value for the lateral deviation is 0.2
m and the initial value for the relative yaw angle is –0.1
rad.
rho = 0.001; e1_initial = 0.2; e2_initial = -0.1;
open the model.
mdl = "rllkamdl"; open_system(mdl) agentblk = mdl "/rl agent";
for this model:
the steering-angle action signal from the agent to the environment is from –15 degrees to 15 degrees.
the observations from the environment are the lateral deviation , relative yaw angle , their derivatives and , and their integrals and .
the simulation is terminated when the lateral deviation
the reward , provided at every time step , is
where is the control input from the previous time step .
create environment interface
create a reinforcement learning environment interface for the ego vehicle.
define the observation information.
obsinfo = rlnumericspec([6 1], ... lowerlimit=-inf*ones(6,1), ... upperlimit=inf*ones(6,1)); obsinfo.name = "observations"; obsinfo.description = "lateral deviation and relative yaw angle";
define the action information.
actinfo = rlfinitesetspec((-15:15)*pi/180);
actinfo.name = "steering";
create the environment interface.
env = rlsimulinkenv(mdl,agentblk,obsinfo,actinfo);
the interface has a discrete action space where the agent can apply one of 31 possible steering angles from –15 degrees to 15 degrees. the observation is the six-dimensional vector containing lateral deviation, relative yaw angle, as well as their derivatives and integrals with respect to time.
to define the initial condition for the lateral deviation and relative yaw angle, specify an environment reset function using an anonymous function handle. localresetfcn
, which is defined at the end of this example, randomizes the initial lateral deviation and relative yaw angle.
env.resetfcn = @(in)localresetfcn(in);
create dqn agent
dqn agents use a parametrized q-value function approximator to estimate the value of the policy. since dqn agents have a discrete action space, you have the option to create a vector (that is multi-output) q-value function critic, which is generally more efficient than a comparable single-output critic.
a vector q-value function takes only the observation as input and returns as output a single vector with as many elements as the number of possible actions. the value of each output 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 afterwards).
to model the parametrized q-value function within the critic, use a neural network with one input (the six-dimensional observed state) and one output vector with 31 elements (evenly spaced steering angles from -15 to 15 degrees). get the number of dimensions of the observation space and the number of elements of the discrete action space from the environment specifications.
ni = obsinfo.dimension(1); % number of inputs (6) nl = 120; % number of neurons no = numel(actinfo.elements); % number of outputs (31)
define the network as an array of layer objects.
dnn = [ featureinputlayer(ni) fullyconnectedlayer(nl) relulayer fullyconnectedlayer(nl) relulayer fullyconnectedlayer(no) ];
the critic network is initialized randomly. ensure reproducibility by fixing the seed of the random generator.
rng(0)
convert to a dlnetwork
object and display the number of parameters.
dnn = dlnetwork(dnn); summary(dnn)
initialized: true number of learnables: 19.1k inputs: 1 'input' 6 features
view the network configuration.
plot(dnn)
create the critic using dnn
and the environment specifications. for more information on vector q-value function approximators, see .
critic = rlvectorqvaluefunction(dnn,obsinfo,actinfo);
specify training options for the critic using rloptimizeroptions
.
criticoptions = rloptimizeroptions( ... learnrate=1e-4, ... gradientthreshold=1, ... l2regularizationfactor=1e-4);
specify the dqn agent options using , include the critic options object.
agentopts = rldqnagentoptions(... sampletime=ts,... usedoubledqn=true,... criticoptimizeroptions=criticoptions,... experiencebufferlength=1e6,... minibatchsize=256);
you can also set or modify the agent options using dot notation.
agentopts.epsilongreedyexploration.epsilondecay = 1e-4;
alternatively, you can create the agent first, and then access its option object and modify the options using dot notation.
create the dqn agent using the specified critic and the agent options. for more information, see .
agent = rldqnagent(critic,agentopts);
training options
to train the agent, first specify the training options. for this example, use the following options.
run each training for at most 10000 episodes, with each episode lasting at most
ceil(t/ts)
time steps.display the training progress in the episode manager dialog box only (set the
plots
andverbose
options accordingly).stop training when the episode reward reaches -1.
save a copy of the agent for each episode where the cumulative reward is greater than 100.
for more information, see rltrainingoptions
.
maxepisodes = 10000; maxsteps = ceil(t/ts); trainopts = rltrainingoptions(... maxepisodes=maxepisodes, ... maxstepsperepisode=maxsteps, ... verbose=false,... plots="training-progress",... stoptrainingcriteria="episodereward",... stoptrainingvalue= -1,... saveagentcriteria="episodereward",... saveagentvalue=100);
parallel training options
to train the agent in parallel, specify the following training options.
set the
useparallel
option totrue
.train agent in parallel asynchronously by setting the
parallelizationoptions.mode
option to"async"
.
trainopts.useparallel = true;
trainopts.parallelizationoptions.mode = "async";
for more information, see rltrainingoptions
.
train agent
train the agent using the train
function. training the agent is a computationally intensive process that takes several minutes 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
. due to randomness of the parallel training, you can expect different training results from the plot below. the plot shows the result of training with four workers.
dotraining = false; if dotraining % train the agent. trainingstats = train(agent,env,trainopts); else % load pretrained agent for the example. load("simulinklkadqnparallel.mat","agent") end
simulate the agent
to validate the performance of the trained agent, uncomment the following two lines and 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);
to demonstrate the trained agent using deterministic initial conditions, simulate the model in simulink.
e1_initial = -0.4; e2_initial = 0.2; sim(mdl)
as shown below, the lateral error (middle plot) and relative yaw angle (bottom plot) are both driven to zero. the vehicle starts from off centerline (–0.4 m) and nonzero yaw angle error (0.2 rad). the lka enables the ego car to travel along the centerline after 2.5 seconds. the steering angle (top plot) shows that the controller reaches steady state after 2 seconds.
local function
function in = localresetfcn(in) % set initial lateral deviation and relative yaw angle to random values in = setvariable(in,"e1_initial", 0.5*(-1 2*rand)); in = setvariable(in,"e2_initial", 0.1*(-1 2*rand)); end
see also
functions
train
|sim
|rlsimulinkenv
objects
blocks
related examples
- train dqn agent for lane keeping assist
- (model predictive control toolbox)
- (model predictive control toolbox)
- train ac agent to balance cart-pole system using parallel computing
- train biped robot to walk using reinforcement learning agents