reinforcement learning tutorial: soft actor-凯发k8网页登录
in this reinforcement learning tutorial, we will demonstrate how to use a soft actor-critic agent to solve control tasks for complex dynamic systems such as a redundant robot manipulator. the goal of the task is to design a model-free controller with a soft actor-critic agent that can balance a ping-pong ball on a flat surface attached to the end effector of the manipulator. model-based control techniques like model predictive control (mpc) or other methods can solve such tasks by creating mathematical models of the plant, but it may become difficult to design such controllers when the plant model becomes complex. model-free reinforcement learning is an alternative in such situations. we will go through how to use the reinforcement learning toolbox™ to create a soft actor-critic agent that can perform the ball balancing task while being robust to variabilities in the environment. at the end of the tutorial, you will have learned how to create environments, design neural network policies, create agents (e.g. soft actor-critic), and train agents to satisfactory performance.
in this hands on session, you will learn how to control a robot manipulator, to balance a ball on a plate using reinforcement learning. you will cover the process step by step starting from building the robot model in simulink to creating and training reinforcement learning agent. towards the end we will explore a few ways we can customize the rl agent by choosing different algorithms and training options.
first, let us take a look into the different components of our robot manipulator system. the robot in this example is kinova robot arm which is a 7 degree of freedom manipulator with a gripper. this diagram shows the modeling of the entire system. the design was created in simulink using simscape multi body blocks, which is specifically used to model and simulate high fidelity mechanical systems. major structural components of the system are the kinova robot, a flat surface or plate which is attached to the end effector of the robot, and a ping pong ball which can bounce or roll on the plate. motion of the ball is modeled using a six stop joint but the motion is also restricted by the plate whenever there is contact. the contact force between the ball and plate is modeled using a special contact force block, which basically behaves like a spring and mass temper system.
now we can look into each of the subsystems to understand them better. in the project folder, you can find a simulink model under the models folder here. you can open the model and once the model is open, you can navigate under these subsystems and look at them with more detail.
in the robot subsystem, we see the different parts of the robot arm but the links and joints are presented by some skip multi-body blocks. these components are created by importing the cad geometries or step files using the sm import command. we won't go through the import workflow in detail, but you will find more information on this towards the end of this tutorial.
the revolute joints-- the revel joint blocks are responsible for motion between the links, and the motion is computed after injecting torque signals into the revel joints. for this example, we make it simple by only actuating the last two joints, which is the r6 and r7 joints over here. the other joints remain static at some predefined joint angles. these angles are specified in an initialization script that you can find over here. can open the script to view the different parameters of the system, and feel free to change anything you like over here.
after getting familiarized with the model, let's take a look into the control problem. in this example, the task is to balance a ping pong ball on the plate. at the beginning of our simulation, the ball can start from any location within the plate, and the control algorithm should calculate the necessary top signals to drive the ball to the center and balance it over there.
this task can be solved using popular control algorithms like mpc or other optimal control methods. however because we need a mathematical model of the plant for such algorithms, designing controllers may become difficult when the system is complex for example, if you were to design an mpc controller for the entire system by actuating all joints, you would need to compute jacobians or write the transition function for the dynamics which could be a tedious process. this is where reinforcement learning can provide an alternate method for designing controllers.
here's a quick overview on some key concepts and reinforcement learning. we will focus on the section of reinforcement learning that is known as model free reinforcement learning. as the name suggests, the algorithm does not need the model of the plant, instead the desired behavior is learned by repeated interaction with the plant. this diagram shows the standard data flow in a reinforcement learning setup. the controller in the setup is the rl agent. and the remainder of the system including the robot plate, the ball, and their actuation and sensing components, is known as the environment.
the agent interacts with the environment by providing a set of action signals which is represented by a. the environment uses these signals to step into the next state s which is rendered down to the agent. the agent also receives another signal r from the environment called the reward, which is a feedback on how well the choice of action was suited for the control test.
the goal of the learning algorithm is to maximize this reward over time through repeated interaction of the agent and environment. in this tutorial, we will represent the agent using deep neural networks. you can find more information on designing neural networks in the matlab documentation. but for now, let us see how we can use the reinforcement learning tool box to solve the problem.
when you are back in the matlab window, open the live script from the project folder here. the script contains a standard command line workflow for reinforcement learning. we begin by running a startup script which adds the necessary files to the matlab file and creates the required variables in the base workspace. to run the script, you can click on the run section button here, and this also opens the simulink model.
at the top level of this model you will see the reinforcement learning setup that we discussed earlier with the agent exchanging data with environment. lets navigate into the environment and open the observation subsystem to view the signals. the observation is a set of 22 signals that represents the state of the system at any given time. that includes information on the position and velocities of actuated joints, position and velocity of the ball, of the plate quaternions and the derivatives, and the top inputs from the previous time steps, and then some physical parameters of the ball like mass and radius. the agent will use these observations to compute the actions at every time step. because these signals have different units, some of them are multiplied with these scale factors so that they remain in more or less the same range as others. it is important because these signals will be fed into a neural network and high magnitude signals may cause one section of the network to dominate and undermine the effect of other signals. the network will train better if you normalize or scale observations in some manner.
we also take the sine and cosine of the orientations instead of using them directly in order to avoid discontinuities of the angles plus or minus 5. this is because discontinuities in the observation space may cause the learning algorithm to converge poorly.
the other signals from the environment is a reward signal. let us take a few moments to understand the reward signals better. the reward at any time step is given by the relationship shown here. since we want the agent to move the ball to the center of the plate, we should provide a positive reward when the ball moves to the center. this reward could be the farthest value at any particular state, but we can improve the reward by providing a shape in the form of a non-linear function.
in this case, we use a gaussian function to reward the agent as the x and y distances of the ball goes to 0. after you have trained the agent a few times, you will find that a well-shaped reward helps in improving training convergence.
in addition to moving the ball to the center, we also want to avoid too much plate orientation, which would be counterintuitive to balancing the ball. for this reason, we provide a penalty for high plate orientation angles. we also provide another penalty to the agent when it uses too much control effort.
finally we sum the rewards and penalties to obtain the scalar reward at every time step. it is also important to note here that each terminated award function has been multiplied with a scaling factor to specify the relative importance on the overall reward.
the final set of signals from the environment is down signal and determines when the simulation should be terminated. termination could mean the system has reached a bad state and it does not make sense to simulate further. in this case, we terminate the simulation and the ball falls off the plate by comparing the xy coordinates against the plate boundaries.
let us go back to the live script to create a reinforcement learning environment from the simulink model. first you will need to create specifications for the inputs and outputs. since the observation and action spaces are continuous in our case, you can use that rl numeric spec function to create the specifications as shown here.
once you have the specifications created, you can create an environment object using the rl simulink env function as shown here. you will need to specify the simulink model name, the block path through the rl agent block, and the observation and action specifications that we created before.
one important aspect of training an rl agent is domain randomization. you can randomize the simulink environment at the beginning of each training episode by providing a function handled to reset the environment as done here. this randomization can help the agent learn a policy that is robust of variations within the environment.
scroll down to the end of the script to view the reset function. over here, there are some parameters that may be important for randomization such as the ball physical parameters and the initial joint angles and the initial torques. you can introduce randomness in these parameters as you like. but for now, let's focus on randomizing just the initial versions of the ball and then keep the other parameters constant.
after creating the environment, the next step is to create a reinforcement learning agent in matlab. there are many algorithms to choose from in the reinforcement learning tool box. these algorithms work on either discrete or continuous action spaces or both. for this tutorial, you will be using the soft actor-critic agent that supports continuous action space.
here is a high level explanation of the soft actor-critic algorithm. guidance in blue represent the major components of the agent. an experienced buffer is used to store experiences from the agent environment interactions and the agent learns by using sample data from this buffer. the learning algorithm for this agent follows the active critic approach with one actor and two critics, each of which are represented by neural networks.
the actor looks at the environment states and selects the actions based on a mean and variance output from the network as shown over here. this mean invariance defines the stochastic policy of the actor and is used to compute the agent's actions. during training, the weights of the actor network are updated by a trade off between the expected reward and the entropy of the policy.
the critics kind of sit behind the actor and criticize the actions whether they're good or bad. their rates are also updated periodically. the algorithm uses multiple critics to reduce overestimation of the q function. you can find more information on the soft actor-critic algorithm towards the end of this tutorial. but for now, all you need to do is to create this neural networks in matlab. everything else will be handled by the toolbox.
now we are back to the line script again. you can create the neural networks by running the code in this section. as shown here, the critic networks consist of a few fullyconnectedlayers with relulayers in between. the inputs to this network are the observations and actions of the agent. and the output is the q function value. you can use the same critic network to create the two critics.
the actor is also modeled in a similar way. it takes observations as inputs and outputs the mean and variance of the policy distribution. after creating the actor and critics, you can create the agent using the rlsacagent function as shown here. most of the type of parameters of the agent are kept to the default values as shown here. so you need not worry too much about changing them for this tutorial. for a full list of type of parameters, you can click on this link which will take you to the matlab documentation.
once the agent is created, the final step is to train the algorithm using the train command. you can specify a few training options such as how long the agent is going to train and what is a stock value for training. for example, you can set the maximum number of training episodes as shown here and then the maximum steps for training episode.
another important parameter is the stop training criteria. in this case, we stopped the training when the average reward over the last 100 episodes reaches the value of 675 or more. this value was obtained after analyzing the agent's performance for a few training iterations.
to start the training, you can set this blue training flag to true and execute the code in the section. software will take a few seconds to set up the training and we'll launch an episode manager figure to keep track of the training progress.
once the figure launches, you can view the training progress from the plot as well see the animation in the mechanics explorer window. you can see here that the agent is trying to balance the ball but failing most of the time. this is expected because it is towards the beginning of training and the agent has not learned much.
we'll also see from the plot that the agent does not receive too many rewards per episode. and the figure at the blue line represents the episode reward and the red line represents the average reward over a window of 100 episodes. yellow line represents the expected long term reward.
as the agent learns from experiences, you will see that the rewards will increase and converge to some value. at that point, you can stop the training and view the agent's performance. to stop the training, you can simply click on the stop training button over here. in the interest of time, let's stop the training and continue with the live script.
a snapshot of a completed training session is shown in the figure here. this will give you an idea of what we expect in the training process. for this particular training, the agent reached the average reward of 675 after about 3,300 episodes. it took about 20 hours to complete.
depending on your system specifications, the training may take less time or more. also, since there is randomness in the process, your actual results may be a little different from what is shown here. let's load a pre-trained agent now to view this performance. you can set the dotraining flag back to false to load an agent saved in a mat file. you can run the section again to load the file.
after loading the agent, scroll down to the simulation section. here, you can set the initial position of the ball to your liking and simulate the model this time with a trained agent. over here the initial x and y positions are set to some non-zero values. let's run the section. you can now see in the animation that the agent is able to center the ball successfully. you can try simulating a few different times with different initial conditions.
going back to the simulink model, you can view the trajectory of the ball and the control inputs through these code blocks. as seen here, the x and y trajectories are converged to zero or near-zero values. we can consider this as satisfactory for this tutorial. the actions, on the other hand, seem pretty noisy. and for practical purposes, we may need to consider whether the actuate can handle these signals. we can consider it as a future enhancement for analysis agent's performance. it's consistent with our reward function.
here are a few options for fine tuning the agent's performance. you can randomize other parameters in the environment like ball mass and initial velocities doing training. you can also change parameters and the reward function, or change the agent hyperparameters. another option is to use a different agent algorithm for this test. we won't be covering these in this video, but you can try them by yourself and discover more of about reinforcement learning.
that concludes this video. we covered a lot of concepts and hopefully this gave you an insight on rl and how to use the reinforcement learning tool box for solving control problems. finally, here are some resources that you can use for further reading.
related products
learn more
featured product
reinforcement learning toolbox
up next:
related videos:
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 mathworks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- (español)
- (english)
- (english)
欧洲
- (english)
- (english)
- (deutsch)
- (español)
- (english)
- (français)
- (english)
- (italiano)
- (english)
- (english)
- (english)
- (deutsch)
- (english)
- (english)
- switzerland
- (english)
亚太
- (english)
- (english)
- (english)
- 中国
- (日本語)
- (한국어)