train dqn agent for lane keeping assist -凯发k8网页登录
this example shows how to train a deep q-learning network (dqn) agent for lane keeping assist (lka) in simulink®. for more information on dqn agents, see .
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 in (model predictive control toolbox). the ego car dynamics is specified by the following parameters.
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 tf
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 limitations 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 , the 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. to do so, first create the observation and action specifications.
observationinfo = rlnumericspec([6 1], ... lowerlimit=-inf*ones(6,1), ... upperlimit=inf*ones(6,1)); observationinfo.name = "observations"; observationinfo.description = "lateral deviation and relative yaw angle"; actioninfo = rlfinitesetspec((-15:15)*pi/180); actioninfo.name = "steering";
then, create the environment interface.
env = rlsimulinkenv(mdl,agentblk,observationinfo,actioninfo);
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 lateral deviation and relative yaw angle, specify an environment reset function using an anonymous function handle. this reset function randomizes the initial values for the lateral deviation and relative yaw angle.
env.resetfcn = @(in)localresetfcn(in);
fix the random generator seed for reproducibility.
rng(0)
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 deep 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).
% define number of inputs, neurons, and outputs ni = observationinfo.dimension(1); % number of inputs (6) nl = 24; % number of neurons no = numel(actioninfo.elements); % number of outputs (31) % define network as array of layer objects dnn = [ featureinputlayer(ni) fullyconnectedlayer(nl) relulayer fullyconnectedlayer(nl) relulayer fullyconnectedlayer(no) ]; % convert to dlnetwork object dnn = dlnetwork(dnn);
display the number of parameters and view the network configuration.
summary(dnn)
initialized: true number of learnables: 1.5k inputs: 1 'input' 6 features
plot(dnn)
create the critic using dnn
and the observation and action specifications. for more information, see rlqvaluefunction
.
critic = rlvectorqvaluefunction(dnn,observationinfo,actioninfo);
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 training options for the critic.
agentoptions = rldqnagentoptions(... sampletime=ts,... usedoubledqn=true,... criticoptimizeroptions=criticoptions,... experiencebufferlength=1e6,... minibatchsize=64);
then, create the dqn agent using the specified critic representation and agent options. for more information, see .
agent = rldqnagent(critic,agentoptions);
train agent
to train the agent, first specify the training options. for this example, use the following options:
run each training episode for at most 5000 episodes, with each episode lasting at most
ceil(t/ts)
time steps.display the training progress in the episode manager dialog box (set the
plots
option totraining-progress
) and disable the command line display (set theverbose
option tofalse
).stop training when the episode reward reaches
–1
.save a copy of the agent for each episode where the cumulative reward is greater than
–2.5
.
for more information, see rltrainingoptions
.
maxepisodes = 5000; maxsteps = ceil(t/ts); trainingopts = rltrainingoptions(... maxepisodes=maxepisodes,... maxstepsperepisode=maxsteps,... verbose=false,... plots="training-progress",... stoptrainingcriteria="episodereward",... stoptrainingvalue=-1,... saveagentcriteria="episodereward",... saveagentvalue=-2.5);
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,trainingopts); else % load the pretrained agent for the example. load("simulinklkadqnmulti.mat","agent") end
simulate dqn 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 on deterministic initial conditions, simulate the model in simulink.
e1_initial = -0.4; e2_initial = 0.2; sim(mdl)
as the plots show, the lateral error (top plot) and relative yaw angle (middle plot) are both driven close to zero. the vehicle starts from off the centerline (–0.4 m) and with a nonzero yaw angle error (0.2 rad). the lane keeping assist makes the ego car travel along the centerline after about 2.5 seconds. the steering angle (bottom plot) shows that the controller reaches steady state after about 2 seconds.
close the simulink model.
if ~dotraining �close(mdl) end
reset function
function in = localresetfcn(in) % reset 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 using parallel computing
- (model predictive control toolbox)