In this project, an agent is designed to fly a quadcopter, and then trained using a reinforcement learning algorithm to take off. Here is the code for this project which was a part of Udacity’sDeep Learning Nanodegree.
Instructions
Take a look at the files in the directory to better understand the structure of the project.
task.py: Define your task (environment) in this file.
policy_search.py: A sample agent has been provided here.
agent.py: Develop your agent here.
physics_sim.py: This file contains the simulator for the quadcopter. DO NOT MODIFY THIS FILE.
For this project, you will define your own task in task.py. Although we have provided a example task to get you started, you are encouraged to change it. Later in this notebook, you will learn more about how to amend this file.
You will also design a reinforcement learning agent in agent.py to complete your chosen task.
You are welcome to create any additional files to help you to organize your code. For instance, you may find it useful to define a model.py file defining any needed neural network architectures.
Controlling the Quadcopter
We provide a sample agent in the code cell below to show you how to use the sim to control the quadcopter. This agent is even simpler than the sample agent that you’ll examine (in agents/policy_search.py) later in this notebook!
The agent controls the quadcopter by setting the revolutions per second on each of its four rotors. The provided agent in the Basic_Agent class below always selects a random action for each of the four rotors. These four speeds are returned by the act method as a list of four floating-point numbers.
For this project, the agent that you will implement in agents/agent.py will have a far more intelligent method for selecting actions!
Run the code cell below to have the agent select actions to control the quadcopter.
Feel free to change the provided values of runtime, init_pose, init_velocities, and init_angle_velocities below to change the starting conditions of the quadcopter.
The labels list below annotates statistics that are saved while running the simulation. All of this information is saved in a text file data.txt and stored in the dictionary results.
Run the code cell below to visualize how the position of the quadcopter evolved during the simulation.
The next code cell visualizes the velocity of the quadcopter.
Next, you can plot the Euler angles (the rotation of the quadcopter over the $x$-, $y$-, and $z$-axes),
before plotting the velocities (in radians per second) corresponding to each of the Euler angles.
Finally, you can use the code cell below to print the agent’s choice of actions.
When specifying a task, you will derive the environment state from the simulator. Run the code cell below to print the values of the following variables at the end of the simulation:
task.sim.pose (the position of the quadcopter in ($x,y,z$) dimensions and the Euler angles),
task.sim.v (the velocity of the quadcopter in ($x,y,z$) dimensions), and
task.sim.angular_v (radians/second for each of the three Euler angles).
In the sample task in task.py, we use the 6-dimensional pose of the quadcopter to construct the state of the environment at each timestep. However, when amending the task for your purposes, you are welcome to expand the size of the state vector by including the velocity information. You can use any combination of the pose, velocity, and angular velocity - feel free to tinker here, and construct the state to suit your task.
The Task
A sample task has been provided for you in task.py. Open this file in a new window now.
The __init__() method is used to initialize several variables that are needed to specify the task.
The simulator is initialized as an instance of the PhysicsSim class (from physics_sim.py).
Inspired by the methodology in the original DDPG paper, we make use of action repeats. For each timestep of the agent, we step the simulation action_repeats timesteps. If you are not familiar with action repeats, please read the Results section in the DDPG paper.
We set the number of elements in the state vector. For the sample task, we only work with the 6-dimensional pose information. To set the size of the state (state_size), we must take action repeats into account.
The environment will always have a 4-dimensional action space, with one entry for each rotor (action_size=4). You can set the minimum (action_low) and maximum (action_high) values of each entry here.
The sample task in this provided file is for the agent to reach a target position. We specify that target position as a variable.
The reset() method resets the simulator. The agent should call this method every time the episode ends. You can see an example of this in the code cell below.
The step() method is perhaps the most important. It accepts the agent’s choice of action rotor_speeds, which is used to prepare the next state to pass on to the agent. Then, the reward is computed from get_reward(). The episode is considered done if the time limit has been exceeded, or the quadcopter has travelled outside of the bounds of the simulation.
In the next section, you will learn how to test the performance of an agent on this task.
The Agent
The sample agent given in agents/policy_search.py uses a very simplistic linear policy to directly compute the action vector as a dot product of the state vector and a matrix of weights. Then, it randomly perturbs the parameters by adding some Gaussian noise, to produce a different policy. Based on the average reward obtained in each episode (score), it keeps track of the best set of parameters found so far, how the score is changing, and accordingly tweaks a scaling factor to widen or tighten the noise.
Run the code cell below to see how the agent performs on the sample task.
This agent should perform very poorly on this task. And that’s where you come in!
Testing with Open AI Gym - MountainCarContinous v0
Since I was having trouble teaching the quadcopter to take off/hover, I tried this Open AI gym environment and was able to achieve a reward > 90 and thus solve this environment.
Define the Task, Design the Agent, and Train Your Agent!
Amend task.py to specify a task of your choosing. If you’re unsure what kind of task to specify, you may like to teach your quadcopter to takeoff, hover in place, land softly, or reach a target pose.
After specifying your task, use the sample agent in agents/policy_search.py as a template to define your own agent in agents/agent.py. You can borrow whatever you need from the sample agent, including ideas on how you might modularize your code (using helper methods like act(), learn(), reset_episode(), etc.).
Note that it is highly unlikely that the first agent and task that you specify will learn well. You will likely have to tweak various hyperparameters and the reward function for your task until you arrive at reasonably good behavior.
As you develop your agent, it’s important to keep an eye on how it’s performing. Use the code above as inspiration to build in a mechanism to log/save the total rewards obtained in each episode to file. If the episode rewards are gradually increasing, this is an indication that your agent is learning.
Plot the Rewards
Once you are satisfied with your performance, plot the episode rewards, either from a single run, or averaged over multiple runs.
Run the code cell below to visualize how the position of the quadcopter evolved during the simulation.
The next code cell visualizes the velocity of the quadcopter.
Next, you can plot the Euler angles (the rotation of the quadcopter over the $x$-, $y$-, and $z$-axes),
before plotting the velocities (in radians per second) corresponding to each of the Euler angles.
Finally, you can use the code cell below to print the agent’s choice of actions.
Reflections
Tasks
I tried two different tasks but wasn’t able to train the quadcopter successfully.
Hover (commented out)
I tried to make the quadcopter hover near the inital position by using this reward function.
Whenever the quadcopter was within 3 units of the target position, a reward of 10 applied.
When it was beyond this distance, there was some punishment in the range (-1, 0) (using tanh) and proportional to the distance away from the target position.
In addition to the above, I tried to discourage rotation using punishments in the same range as before as can be seen in the code snippet below.
Take off
For the take off task, I tried to punish any movements along x and y with values in the range (-1, 0) just like before.
For the z axis, I gave some extra weight to the reward/punishment as I felt this was the most important thing for the quadcopter to learn. I used the difference between the current position along the z axis and the initial position - this would be positive if the quadcopter is moving up and negative otherwise.
I tried to discourage rotation by adding a value between (-1, 0) for any rotation along each of the axes.
The agent
I chose the recommended Deep Deterministic Policy Gradient (DDPG) algorithm. After trying many permutations of hyperparemeters, I chose the ones specified in 7 Experiment Details section of the linked paper:
I tweaked the recommended architecture with these changes based on the above paper.
Learning rates of Adam optimizer
Actor - 0.0001
Critic - 0.001
Final layer weights were initialized from a uniform distribution in the below ranges
Actor - [-0.003, 0.003]
Critic - [-0.0003, 0.0003]
Summaries of the architecture of the actor and critic with the layers, sizes and activation functions are printed below. The only addition to each from the recommended architecure is a batch normalization layer in between.
Performance
Based on the plot of the rewards over episodes above, it doesn’t look like the quadcopter was able to learn how to take off. After the amount of tweaking I did with no success, this was a very hard task for me to teach the quadcopter.
The quadcopter seemed to learn a lot suddenly around episode 45 but couldn’t retain this. There was some gradual learning after this but not enough.
The performance was not as good as the best performance.
The best reward for an episode was around -3 but towards the end this was around -18.
Final thoughts
The hardest part was setting up a suitable reward function for the agent to start learning the task. Though tweaking the parameters changed the performance, this wasn’t much as I was using parameters very close to the ones specified in the DDPG paper.
At one point during my experimentation, the quadcopter seemed to land smoothly even though I had set up the task for the agent to learn take off. This did make sense because of the way I was calculating the reward. I then started rewarding the height of the quadcopter a little bit more to avoid this.
Most times, though the rewards seemed to go up over a number of episodes, the trained model failed to perform the necessary task during the simulation.
After a long time tweaking the parameters and reward function with not much success, I validated the architecture with Open AI gym’s mountain car environment and was able to solve it.
I did some more tweaking after that but still don’t have a quadcopter that can hover or take off.
However, there was a lot of great material and my understanding of deep reinforcement learning grew because of the time I spent on this project. I hope to apply this knowledge to different environments in the Open AI gym and other applications in the future.