train dqn agent to swing up and balance pendulum -凯发k8网页登录
this example shows how to train a deep q-learning network (dqn) agent to swing up and balance a pendulum modeled in simulink®.
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.
pendulum swing-up model
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.
open the model.
mdl = "rlsimplependulummodel";
open_system(mdl)
for this model:
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 is from –2 to 2 n·m.
the observations from the environment are the sine of the pendulum angle, the cosine of the pendulum angle, and the pendulum angle derivative.
the reward , provided at every timestep, is
here:
is the angle of displacement from the upright position.
is the derivative of the displacement angle.
is the control effort from the previous time step.
for more information on this model, see load predefined control system environments.
create environment interface
create a predefined environment interface for the pendulum.
env = rlpredefinedenv("simplependulummodel-discrete")
env = simulinkenvwithagent with properties: model : rlsimplependulummodel agentblock : rlsimplependulummodel/rl agent resetfcn : [] usefastrestart : on
the interface has a discrete action space where the agent can apply one of three possible torque values to the pendulum: –2, 0, or 2 n·m.
to define the initial condition of the pendulum as hanging downward, specify an environment reset function using an anonymous function handle. this reset function sets the model workspace variable theta0
to pi
.
env.resetfcn = @(in)setvariable(in,"theta0",pi,"workspace",mdl);
get the observation and action specification information from the environment.
obsinfo = getobservationinfo(env)
obsinfo = rlnumericspec with properties: lowerlimit: -inf upperlimit: inf name: "observations" description: [0x0 string] dimension: [3 1] datatype: "double"
actinfo = getactioninfo(env)
actinfo = rlfinitesetspec with properties: elements: [3x1 double] name: "torque" description: [0x0 string] dimension: [1 1] datatype: "double"
specify the simulation time tf
and the agent sample time ts
in seconds.
ts = 0.05; tf = 20;
fix the random generator seed for reproducibility.
rng(0)
create dqn agent
a dqn agent approximates the long-term reward, given observations and actions, using a parametrized q-value function critic.
since dqn agents have a discrete action space, you have the option to create a vector (that is a multi-output) q-value function critic, which is generally more efficient than a comparable single-output critic. a vector q-value function is a mapping from an environment observation to a vector in which each 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 q-value function within the critic, use a deep neural network. the network must have one input layer (which receives the content of the observation channel, as specified by obsinfo
) and one output layer (which returns the vector of values for all the possible actions). note that prod(obsinfo.dimension)
returns the number of dimensions of the observation space (regardless of whether they are arranged as a row vector, column vector, or matrix, while numel(actinfo.elements)
returns the number of elements of the discrete action space.
define the network as an array of layer objects.
criticnet = [ featureinputlayer(prod(obsinfo.dimension)) fullyconnectedlayer(24) relulayer fullyconnectedlayer(48) relulayer fullyconnectedlayer(numel(actinfo.elements)) ];
convert to dlnetwork
and display the number of weights.
criticnet = dlnetwork(criticnet); summary(criticnet)
initialized: true number of learnables: 1.4k inputs: 1 'input' 3 features
view the critic network configuration.
plot(criticnet)
for more information on creating value functions that use a deep neural network model, see create policies and value functions.
create the critic using criticnet
, as well as observation and action specifications. for more information, see .
critic = rlvectorqvaluefunction(criticnet,obsinfo,actinfo);
specify options for the critic optimizer using rloptimizeroptions
.
criticopts = rloptimizeroptions(learnrate=0.001,gradientthreshold=1);
to create the dqn agent, first specify the dqn agent options using .
agentoptions = rldqnagentoptions(... sampletime=ts,... criticoptimizeroptions=criticopts,... experiencebufferlength=3000,... usedoubledqn=false);
then, create the dqn agent using the specified critic 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 for at most 1000 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 theverbose
option tofalse
).stop training when the agent receives an average cumulative reward greater than –1100 over five consecutive episodes. at this point, the agent can quickly balance the pendulum in the upright position using minimal control effort.
save a copy of the agent for each episode where the cumulative reward is greater than –1100.
for more information, see rltrainingoptions
.
trainingoptions = rltrainingoptions(... maxepisodes=1000,... maxstepsperepisode=500,... scoreaveragingwindowlength=5,... verbose=false,... plots="training-progress",... stoptrainingcriteria="averagereward",... stoptrainingvalue=-1100,... saveagentcriteria="episodereward",... saveagentvalue=-1100);
train the agent using the train
function. training this 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
.
dotraining = false; if dotraining % train the agent. trainingstats = train(agent,env,trainingoptions); else % load the pretrained agent for the example. load("simulinkpendulumdqnmulti.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);