train multiple agents for area coverage -凯发k8网页登录
this example demonstrates a multi-agent collaborative-competitive task in which you train three proximal policy optimization (ppo) agents to explore all areas within a grid-world environment.
multi-agent training is supported for simulink® environments only. as shown in this example, if you define your environment behavior using a matlab® system object, you can incorporate it into a simulink environment using a (simulink) block.
create environment
the environment in this example is a 12x12 grid world containing obstacles, with unexplored cells marked in white and obstacles marked in black. there are three robots in the environment represented by the red, green, and blue circles. three proximal policy optimization agents with discrete action spaces control the robots. to learn more about ppo agents, see .
the agents provide one of five possible movement actions (wait, up, down, left, or right) to their respective robots. the robots decide whether an action is legal or illegal. for example, an action of moving left when the robot is located next to the left boundary of the environment is deemed illegal. similarly, actions for colliding against obstacles and other agents in the environment are illegal actions and draw penalties. the environment dynamics are deterministic, which means the robots execute legal and illegal actions with 100% and 0% probabilities, respectively. the overall goal is to explore all cells as quickly as possible.
at each time step, an agent observes the state of the environment through a set of four images that identify the cells with obstacles, current position of the robot that is being controlled, position of other robots, and cells that have been explored during the episode. these images are combined to create a 4-channel 12x12 image observation set. the following figure shows an example of what the agent controlling the green robot observes for a given time step.
for the grid world environment:
the search area is a 12x12 grid with obstacles.
the observation for each agent is a 12x12x4 image.
the discrete action set is a set of five actions (wait=0, up=1, down=2, left=3, right=4).
the simulation terminates when the grid is fully explored or the maximum number of steps is reached.
at each time step, agents receive the following rewards and penalties.
1 for moving to a previously unexplored cell (white).
-0.5 for an illegal action (attempt to move outside the boundary or collide against other robots and obstacles)
-0.05 for an action that results in movement (movement cost).
-0.1 for an action that results in no motion (lazy penalty).
if the grid is fully explored, 200 times the coverage contribution for that robot during the episode (ratio of cells explored to total cells)
define the locations of obstacles within the grid using a matrix of indices. the first column contains the row indices, and the second column contains the column indices.
obsmat = [4 3; 5 3; 6 3; 7 3; 8 3; 9 3; 5 11; 6 11; 7 11; 8 11; 5 12; 6 12; 7 12; 8 12];
initialize the robot positions.
sa0 = [2 2]; sb0 = [11 4]; sc0 = [3 12]; s0 = [sa0; sb0; sc0];
specify the sample time, simulation time, and maximum number of steps per episode.
ts = 0.1; tf = 100; maxsteps = ceil(tf/ts);
open the simulink model.
mdl = "rlareacoverage";
open_system(mdl)
the gridworld
block is a matlab system block representing the training environment. the system object for this environment is defined in gridworld.m
.
in this example, the agents are homogeneous and have the same observation and action specifications. create the observation and action specifications for the environment. for more information, see rlnumericspec
and rlfinitesetspec
.
% define observation specifications. obssize = [12 12 4]; oinfo = rlnumericspec(obssize); oinfo.name = "observations"; % define action specifications. numact = 5; actionspace = {0,1,2,3,4}; ainfo = rlfinitesetspec(actionspace); ainfo.name = "actions";
specify the block paths for the agents.
blks = mdl ["/agent a (red)","/agent b (green)","/agent c (blue)"];
create the environment interface, specifying the same observation and action specifications for all three agents.
env = rlsimulinkenv(mdl,blks,{oinfo,oinfo,oinfo},{ainfo,ainfo,ainfo});
specify a reset function for the environment. the reset function resetmap
ensures that the robots start from random initial positions at the beginning of each episode. the random initialization makes the agents robust to different starting positions and improves training convergence.
env.resetfcn = @(in) resetmap(in, obsmat);
create agents
the ppo agents in this example operate on a discrete action space and rely on actor and critic functions to learn the optimal policies. the agents maintain deep neural network-based function approximators for the actors and critics with similar network structures (a combination of convolution and fully connected layers). the critic outputs a scalar value representing the state value . the actor outputs the probabilities of taking each of the five actions wait, up, down, left, or right.
set the random seed for reproducibility.
rng(0)
create the actor and critic functions using the following steps.
create the actor and critic deep neural networks.
create the actor function objects using the
rldiscretecategoricalactor
command.create the critic function objects using the
rlvaluefunction
command.
use the same network structure and representation options for all three agents.
for idx = 1:3 % create actor deep neural network. actornetwork = [ imageinputlayer(obssize,normalization="none") convolution2dlayer(8,16, ... stride=1,padding=1,weightsinitializer="he") relulayer convolution2dlayer(4,8, ... stride=1,padding="same",weightsinitializer="he") relulayer fullyconnectedlayer(256,weightsinitializer="he") relulayer fullyconnectedlayer(128,weightsinitializer="he") relulayer fullyconnectedlayer(64,weightsinitializer="he") relulayer fullyconnectedlayer(numact) softmaxlayer ]; actornetwork = dlnetwork(actornetwork); % create critic deep neural network. criticnetwork = [ imageinputlayer(obssize,normalization="none") convolution2dlayer(8,16, ... stride=1,padding=1,weightsinitializer="he") relulayer convolution2dlayer(4,8, ... stride=1,padding="same",weightsinitializer="he") relulayer fullyconnectedlayer(256,weightsinitializer="he") relulayer fullyconnectedlayer(128,weightsinitializer="he") relulayer fullyconnectedlayer(64,weightsinitializer="he") relulayer fullyconnectedlayer(1) ]; criticnetwork = dlnetwork(criticnetwork); % create actor and critic actor(idx) = rldiscretecategoricalactor(actornetwork,oinfo,ainfo); critic(idx) = rlvaluefunction(criticnetwork,oinfo); end
specify training options for the critic and the actor using rloptimizeroptions
.
actoropts = rloptimizeroptions(learnrate=1e-4,gradientthreshold=1); criticopts = rloptimizeroptions(learnrate=1e-4,gradientthreshold=1);
specify the agent options using , include the training options for the actor and critic. use the same options for all three agents. during training, agents collect experiences until they reach the experience horizon of 128 steps and then train from mini-batches of 64 experiences. an objective function clip factor of 0.2 improves training stability, and a discount factor value of 0.995 encourages long-term rewards.
opt = rlppoagentoptions(... actoroptimizeroptions=actoropts,... criticoptimizeroptions=criticopts,... experiencehorizon=128,... clipfactor=0.2,... entropylossweight=0.01,... minibatchsize=64,... numepoch=3,... advantageestimatemethod="gae",... gaefactor=0.95,... sampletime=ts,... discountfactor=0.995);
create the agents using the defined actors, critics, and options.
agenta = rlppoagent(actor(1),critic(1),opt); agentb = rlppoagent(actor(2),critic(2),opt); agentc = rlppoagent(actor(3),critic(3),opt);
alternatively, you can create the agents first, and then access their option object to modify the options using dot notation.
train agents
in this example, the agents are trained independently in decentralized manner. specify the following options for training the agents.
automatically assign agent groups using the
agentgroups=auto
option. this allocates each agent in a separate group.specify the
"decentralized"
learning strategy.run the training for at most 1000 episodes, with each episode lasting at most 5000 time steps.
stop the training of an agent when its average reward over 100 consecutive episodes is 80 or more.
trainopts = rlmultiagenttrainingoptions(... "agentgroups","auto",... "learningstrategy","decentralized",... maxepisodes=1000,... maxstepsperepisode=maxsteps,... plots="training-progress",... scoreaveragingwindowlength=100,... stoptrainingcriteria="averagereward",... stoptrainingvalue=80);
for more information on multi-agent training, type help rlmultiagenttrainingoptions
in matlab.
to train the agents, specify an array of agents to the train
function. the order of the agents in the array must match the order of agent block paths specified during environment creation. doing so ensures that the agent objects are linked to the appropriate action and observation specifications in the environment.
training is a computationally intensive process that takes several minutes to complete. to save time while running this example, load pretrained agent parameters by setting dotraining
to false
. to train the agent yourself, set dotraining
to true
.
dotraining = false; if dotraining result = train([agenta,agentb,agentc],env,trainopts); else load("rlareacoverageagents.mat"); end
the following figure shows a snapshot of the training progress. you can expect different results due to randomness in the training process.
simulate agents
simulate the trained agents within the environment. for more information on agent simulation, see rlsimulationoptions
and sim
.
rng(0) % reset the random seed
simopts = rlsimulationoptions(maxsteps=maxsteps);
experience = sim(env,[agenta,agentb,agentc],simopts);
the agents successfully cover the entire grid world.