train ac agent to balance cart-凯发k8网页登录
this example shows how to train an actor-critic (ac) agent to balance a cart-pole system modeled in matlab® by using asynchronous parallel training. for an example that shows how to train the agent without using parallel training, see train ac agent to balance cart-pole system.
actor-critic agent parallel training
ac agents use gradient-based parallelization, in which both environment simulation and gradient computation is done by the workers and the gradient averaging is done by the client. specifically, each worker generates new experiences from its copy of agent and environment, calculates the gradient, and sends it back to the client. the client updates its parameters as follows.
for asynchronous training (for ac agents this option is also referred to as a3c), the client agent averages the gradients and updates its agent parameters, without waiting to receive experiences from all the workers. the client then sends the updated parameters back to the worker that provided the gradient. then, the worker updates its copy of the agent and continues to generate experiences (and gradients) 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 until it has received gradients from all of the workers. it then averages the gradients, updates its 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 and calculate new gradients. synchronous, gradient-based parallelization allows you to achieve, in principle, a speed improvement which is nearly linear in the number of workers. however, since each worker must pause execution until all workers are finished, synchronous training only advances as fast as the slowest worker allows. 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 gradient-based parallelization, see train agents using parallel computing and gpus.
create cart-pole matlab environment interface
create a predefined environment interface for the cart-pole system. for more information on this environment, see load predefined control system environments.
env = rlpredefinedenv("cartpole-discrete");
env.penaltyforfalling = -10;
obtain the observation and action information from the environment interface.
obsinfo = getobservationinfo(env); numobservations = obsinfo.dimension(1); actinfo = getactioninfo(env);
fix the random generator seed for reproducibility.
rng(0)
create ac agent
actor-critic agents use a parametrized value function approximator to estimate the value of the policy. a value-function critic takes the current observation as input and returns a single scalar as output (the estimated discounted cumulative long-term reward for following the policy from the state corresponding to the current observation).
to model the parametrized value function within the critic, use a neural network with one input layer (which receives the content of the observation channel, as specified by obsinfo
) and one output layer (which returns the scalar value). note that prod(obsinfo.dimension)
returns the total number of dimensions of the observation space regardless of whether the observation space is a column vector, row vector, or matrix.
define the network as an array of layer objects.
criticnetwork = [ featureinputlayer(prod(obsinfo.dimension)) fullyconnectedlayer(32) relulayer fullyconnectedlayer(1) ];
create the value function approximator object using criticnetwork
and the environment action and observation specifications.
critic = rlvaluefunction(criticnetwork,obsinfo);
actor-critic agents use a parametrized stochastic policy, which for discrete action spaces is implemented by a discrete categorical actor. this actor takes an observation as input and returns as output a random action sampled (among the finite number of possible actions) from a categorical probability distribution.
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. the output layer must return a vector of probabilities for each possible action, as specified by actinfo
. note that numel(actinfo.dimension)
returns the number of elements of the discrete action space.
define the network as an array of layer objects.
actornetwork = [ featureinputlayer(prod(obsinfo.dimension)) fullyconnectedlayer(32) relulayer fullyconnectedlayer(numel(actinfo.dimension))];
create the actor approximator object using actornetwork
and the environment action and observation specifications.
actor = rldiscretecategoricalactor(actornetwork,obsinfo,actinfo);
for more information on creating approximator objects such as actors and critics, see create policies and value functions.
specify options for the critic and actor using rloptimizeroptions
.
criticopts = rloptimizeroptions(learnrate=1e-2,gradientthreshold=1); actoropts = rloptimizeroptions(learnrate=1e-2,gradientthreshold=1);
specify the ac agent options using rlacagentoptions
, include the training options for the actor and critic.
agentopts = rlacagentoptions(... actoroptimizeroptions=actoropts,... criticoptimizeroptions=criticopts,... entropylossweight=0.01);
create the agent using the specified actor representation and agent options. for more information, see rlacagent
.
agent = rlacagent(actor,critic,agentopts);
parallel training options
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 most500
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).stop training when the agent receives an average cumulative reward greater than
500
over10
consecutive episodes. at this point, the agent can balance the pendulum in the upright position.
trainopts = rltrainingoptions(... maxepisodes=1000,... maxstepsperepisode=500,... verbose=false,... plots="training-progress",... stoptrainingcriteria="averagereward",... stoptrainingvalue=500,... scoreaveragingwindowlength=10);
you can visualize the cart-pole system can during training or simulation using the plot
function.
plot(env)
to train the agent using parallel computing, specify the following training options.
set the
useparallel
option totrue
.train the 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 in the asynchronous parallel training, you can expect different training results from the following training plot. the plot shows the result of training with six workers.
dotraining = false; if dotraining % train the agent. trainingstats = train(agent,env,trainopts); else % load the pretrained agent for the example. load("matlabcartpoleparac.mat","agent"); end
simulate ac agent
you can visualize the cart-pole system with the plot function during simulation.
plot(env)
to validate the performance of the trained agent, simulate it within the cart-pole environment. for more information on agent simulation, see rlsimulationoptions
and sim
.
simoptions = rlsimulationoptions(maxsteps=500); experience = sim(env,agent,simoptions);
totalreward = sum(experience.reward)
totalreward = 500
references
[1] mnih, volodymyr, adrià puigdomènech badia, mehdi mirza, alex graves, timothy p. lillicrap, tim harley, david silver, and koray kavukcuoglu. ‘asynchronous methods for deep reinforcement learning’. arxiv:1602.01783 [cs], 16 june 2016. .
see also
apps
functions
objects
related examples
- configure options for a3c training
- train ac agent to balance cart-pole system
- train dqn agent for lane keeping assist using parallel computing
- train biped robot to walk using reinforcement learning agents