main content

train biped robot to walk using reinforcement learning agents -凯发k8网页登录

this example shows how to train a biped robot to walk using either a deep deterministic policy gradient (ddpg) agent or a twin-delayed deep deterministic policy gradient (td3) agent. in the example, you also compare the performance of these trained agents. the robot in this example is modeled in simscape™ multibody™. for more information on these agents, see and twin-delayed deep deterministic (td3) policy gradient agents.

for the purpose of comparison in this example, this example trains both agents on the biped robot environment with the same model parameters. the example also configures the agents to have the following settings in common.

  • initial condition strategy of the biped robot

  • network structure of actor and critic, inspired by [1]

  • options for actor and critic representations

  • training options (sample time, discount factor, mini-batch size, experience buffer length, exploration noise)

biped robot model

the reinforcement learning environment for this example is a biped robot. the training goal is to make the robot walk in a straight line using minimal control effort.

load the parameters of the model into the matlab® workspace.

robotparametersrl

open the simulink® model.

mdl = "rlwalkingbipedrobot";
open_system(mdl)

the robot is modeled using simscape multibody.

for this model:

  • in the neutral 0 rad position, both of the legs are straight and the ankles are flat.

  • the foot contact is modeled using the (simscape multibody) block.

  • the agent can control 3 individual joints (ankle, knee, and hip) on both legs of the robot by applying torque signals from -3 to 3 n·m. the actual computed action signals are normalized between -1 and 1.

the environment provides the following 29 observations to the agent.

  • y (lateral) and z (vertical) translations of the torso center of mass. the translation in the z direction is normalized to a similar range as the other observations.

  • x (forward), y (lateral), and z (vertical) translation velocities.

  • yaw, pitch, and roll angles of the torso.

  • yaw, pitch, and roll angular velocities of the torso.

  • angular positions and velocities of the three joints (ankle, knee, hip) on both legs.

  • action values from the previous time step.

the episode terminates if either of the following conditions occur.

  • the robot torso center of mass is less than 0.1 m in the z direction (the robot falls) or more than 1 m in the either y direction (the robot moves too far to the side).

  • the absolute value of either the roll, pitch, or yaw is greater than 0.7854 rad.

the following reward function rt, which is provided at every time step is inspired by [2].

rt=vx-3y2-50zˆ2 25tstf-0.02iut-1i2

here:

  • vx is the translation velocity in the x direction (forward toward goal) of the robot.

  • y is the lateral translation displacement of the robot from the target straight line trajectory.

  • zˆ is the normalized vertical translation displacement of the robot center of mass.

  • ut-1i is the torque from joint i from the previous time step.

  • ts is the sample time of the environment.

  • tfis the final simulation time of the environment.

this reward function encourages the agent to move forward by providing a positive reward for positive forward velocity. it also encourages the agent to avoid episode termination by providing a constant reward (25tstf) at every time step. the other terms in the reward function are penalties for substantial changes in lateral and vertical translations, and for the use of excess control effort.

create environment interface

create the observation specification.

numobs = 29;
obsinfo = rlnumericspec([numobs 1]);
obsinfo.name = "observations";

create the action specification.

numact = 6;
actinfo = rlnumericspec([numact 1],lowerlimit=-1,upperlimit=1);
actinfo.name = "foot_torque";

create the environment interface for the walking robot model.

blk = mdl   "/rl agent";
env = rlsimulinkenv(mdl,blk,obsinfo,actinfo);
env.resetfcn = @(in) walkerresetfcn(in, ...
    upper_leg_length/100, ...
    lower_leg_length/100, ...
    h/100);

select and create agent for training

this example provides the option to train the robot either using either a ddpg or td3 agent. to simulate the robot with the agent of your choice, set the agentselection flag accordingly.

agentselection = "ddpg";
switch agentselection
    case "ddpg"
        agent = createddpgagent(numobs,obsinfo,numact,actinfo,ts);
    case "td3"
        agent = createtd3agent(numobs,obsinfo,numact,actinfo,ts);
    otherwise
        disp("assign agentselection to ddpg or td3")
end

the createddpgagent and createtd3agent helper functions perform the following actions.

  • create actor and critic networks.

  • specify options for actors and critics.

  • create actors and critics using the networks and options previously created.

  • configure agent specific options.

  • create the agent.

ddpg agent

ddpg agents use a parametrized deterministic policy over continuous action spaces, which is learned by a continuous deterministic actor, and a parametrized q-value function approximator to estimate the value of the policy. use neural networks to model both the policy and the q-value function. the actor and critic networks for this example are inspired by [1].

for details on how the ddpg agent is created, see the createddpgagent helper function. for information on configuring ddpg agent options, see .

for more information on creating a deep neural network value function representation, see create policies and value functions. for an example that creates neural networks for ddpg agents, see compare ddpg agent to lqr controller.

td3 agent

the critic of a ddpg agent can overestimate the q value. since the agent uses the q value to update its policy (actor), the resultant policy can be suboptimal and can accumulate training errors that can lead to divergent behavior. the td3 algorithm is an extension of ddpg with improvements that make it more robust by preventing overestimation of q values [3].

  • two critic networks — td3 agents learn two critic networks independently and use the minimum value function estimate to update the actor (policy). doing so prevents accumulation of error in subsequent steps and overestimation of q values.

  • addition of target policy noise — adding clipped noise to value functions smooths out q function values over similar actions. doing so prevents learning an incorrect sharp peak of noisy value estimate.

  • delayed policy and target updates — for a td3 agent, delaying the actor network update allows more time for the q function to reduce error (get closer to the required target) before updating the policy. doing so prevents variance in value estimates and results in a higher quality policy update.

the structure of the actor and critic networks used for this agent are the same as the ones used for ddpg agent. for details on the creation of the td3 agent, see the createtd3agent helper function. for information on configuring td3 agent options, see rltd3agentoptions.

specify training options and train agent

for this example, the training options for the ddpg and td3 agents are the same.

  • run each training session for 2000 episodes with each episode lasting at most maxsteps time steps.

  • display the training progress in the episode manager dialog box (set the plots option) and disable the command line display (set the verbose option).

  • terminate the training only when it reaches the maximum number of episodes (maxepisodes). doing so allows the comparison of the learning curves for multiple agents over the entire training session.

for more information and additional options, see rltrainingoptions.

maxepisodes = 2000;
maxsteps = floor(tf/ts);
trainopts = rltrainingoptions(...
    maxepisodes=maxepisodes,...
    maxstepsperepisode=maxsteps,...
    scoreaveragingwindowlength=250,...
    verbose=false,...
    plots="training-progress",...
    stoptrainingcriteria="episodecount",...
    stoptrainingvalue=maxepisodes,...
    saveagentcriteria="episodecount",...
    saveagentvalue=maxepisodes);

to train the agent in parallel, specify the following training options. training in parallel requires parallel computing toolbox™. if you do not have parallel computing toolbox software installed, set useparallel to false.

  • set the useparallel option to true.

  • train the agent in parallel asynchronously.

  • after every 32 steps, have each worker send experiences to the parallel pool client (the matlab® process which starts the training). ddpg and td3 agents require workers to send experiences to the client.

trainopts.useparallel = true;
trainopts.parallelizationoptions.mode = "async";
trainopts.parallelizationoptions.stepsuntildataissent = 32;
trainopts.parallelizationoptions.datatosendfromworkers = "experiences";

train the agent using the train function. this process is computationally intensive and takes several hours to complete for each agent. 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 parallel training, you can expect different training results from the plots that follow. the pretrained agents were trained in parallel using four workers.

dotraining = false;
if dotraining    
    % train the agent.
    trainingstats = train(agent,env,trainopts);
else
    % load a pretrained agent for the selected agent type.
    if strcmp(agentselection,"ddpg")
       load("rlwalkingbipedrobotddpg.mat","agent")
    else
       load("rlwalkingbipedrobottd3.mat","agent")
    end  
end

for the preceding example training curves, the average time per training step for the ddpg and td3 agents are 0.11 and 0.12 seconds, respectively. the td3 agent takes more training time per step because it updates two critic networks compared to the single critic used for ddpg.

simulate trained agents

fix the random generator seed for reproducibility.

rng(0)

to validate the performance of the trained agent, simulate it within the biped robot environment. for more information on agent simulation, see rlsimulationoptions and sim.

simoptions = rlsimulationoptions(maxsteps=maxsteps);
experience = sim(env,agent,simoptions);

compare agent performance

for the following agent comparison, each agent was trained five times using a different random seed each time. due to the random exploration noise and the randomness in the parallel training, the learning curve for each run is different. since the training of agents for multiple runs takes several days to complete, this comparison uses pretrained agents.

for the ddpg and td3 agents, plot the average and standard deviation of the episode reward (top plot) and the episode q0 value (bottom plot). the episode q0 value is the critic estimate of the discounted long-term reward at the start of each episode given the initial observation of the environment. for a well-designed critic, the episode q0 value approaches the true discounted long-term reward.

compareperformance("ddpgagent","td3agent")

based on the learning curve comparison plot:

  • the ddpg agent appears to pick up learning faster (around episode number 600 on average) but hits a local minimum. td3 starts slower but eventually achieves higher rewards than ddpg as it avoids overestimation of q values.

  • the td3 agent shows a steady improvement in its learning curve, which suggests improved stability when compared to the ddpg agent.

based on the episode q0 comparison plot:

  • for the td3 agent, the critic estimate of the discounted long-term reward (for 2000 episodes) is lower compared to the ddpg agent. this difference is because the td3 algorithm takes a conservative approach in updating its targets by using a minimum of two q functions. this behavior is further enhanced because of delayed updates to the targets.

  • although the td3 estimate for these 2000 episodes is low, the td3 agent shows a steady increase in the episode q0 values, unlike the ddpg agent.

in this example, the training was stopped at 2000 episodes. for a larger training period, the td3 agent with its steady increase in estimates shows the potential to converge to the true discounted long-term reward.

for another example on how to train a humanoid robot to walk using a ddpg agent, see train humanoid walker (simscape multibody). for an example on how to train a quadruped robot to walk using a ddpg agent, see .

references

[1] lillicrap, timothy p., jonathan j. hunt, alexander pritzel, nicolas heess, tom erez, yuval tassa, david silver, and daan wierstra. "continuous control with deep reinforcement learning." preprint, submitted july 5, 2019. .

[2] heess, nicolas, dhruva tb, srinivasan sriram, jay lemmon, josh merel, greg wayne, yuval tassa, et al. "emergence of locomotion behaviours in rich environments." preprint, submitted july 10, 2017. .

[3] fujimoto, scott, herke van hoof, and david meger. "addressing function approximation error in actor-critic methods." preprint, submitted october 22, 2018. .

see also

functions

objects

blocks

related examples

more about

网站地图