<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Simon Deleersnijder on Medium]]></title>
        <description><![CDATA[Stories by Simon Deleersnijder on Medium]]></description>
        <link>https://medium.com/@sdeleers?source=rss-1083a050fde4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*W5HEegZoQrl8TiGw8LHAFQ.jpeg</url>
            <title>Stories by Simon Deleersnijder on Medium</title>
            <link>https://medium.com/@sdeleers?source=rss-1083a050fde4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 19:01:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sdeleers/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Autonomous car with Reinforcement Learning — part 1: obstacle avoidance]]></title>
            <link>https://medium.com/@sdeleers/autonomous-car-with-reinforcement-learning-part-1-obstacle-avoidance-7c73a2567b7b?source=rss-1083a050fde4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c73a2567b7b</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Simon Deleersnijder]]></dc:creator>
            <pubDate>Sat, 04 Nov 2017 12:42:56 GMT</pubDate>
            <atom:updated>2017-11-04T12:52:26.974Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Recently I’ve become very interested in machine learning, and reinforcement learning in particular. Since I’m also quite passionate about autonomous driving I want to build a car that learns to drive itself using reinforcement learning. In simulation, that is.</em></p><p><em>In this first post the car will learn how to avoid obstacles using only distance sensors as input. In the </em><a href="https://medium.com/@sdeleers/autonomous-car-with-reinforcement-learning-part-2-track-following-4ffbf7aa33d1"><em>next post</em></a><em> I will tackle the more challenging problem of driving around a track as fast as possible using only a camera input mounted on the front of the car.</em></p><h4>The simulation environment</h4><p>The simulation will be carried out in Pygame, which is a Python library that allows you to write your own games. I made a simple game in which a car (or circle, depending on your level of imagination) can be driven around in a 2D environment. The speed of the car is fixed and you can use the keyboard to make it go left or right. If you don’t press any key the car will continue to move in a straight line at the same speed. The environment contains obstacles and the goal is to drive around as long as possible without crashing. Every time the car crashes it starts over in a new randomly generated obstacle maze. In order for the car to autonomously drive itself it needs sensors. In the <a href="http://www.peacytea.com/machine-learning/autonomous-car-rl-2/">next post</a> we will use a camera mounted on the front of the car but let’s start simple with just 3 radar sensors. These tell us the distance to the nearest object in 3 directions (straight ahead, 45 degrees to the left, 45 degrees to the right).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6vO-AqAZQIT0-Smu6-uhiw.png" /><figcaption>The ball-shaped car moving towards the left in the environment with the randomly placed square obstacles shown in white. The radar sensors are visualized with yellow lines. The state vector here is [178, 248, 69], meaning that the left sensor detects an object 178 units away, 248 for the front, and 69 for the right. Note that the environment walls are also detected as obstacles.</figcaption></figure><p>The only feedback the reinforcement learning algorithm gets from the environment is these sensor values and a reward at every time step. Without these rewards it would not know that crashing is bad, and that not crashing for a long time is good. In our simulation a negative reward of -100 is given every time the car crashes into something, a reward of +1 for every time step it doesn’t crash, and a negative reward of -0.1 every time the car turns left or right. The first two rewards are intuitively clear to disfavor crashes. The idea behind the -0.1 reward is to smoothen the policy and make it less jittery. Given that there are no obstacles we prefer to keep going in a straight line instead of randomly turning left or right. The values for these rewards are quite arbitrary and different values might lead to different learnt policies. I did not really experiment with them too much.</p><h4>Reinforcement learning overview</h4><p>In reinforcement learning today there are broadly speaking two different approaches being used: Q-learning, and Policy Gradient methods. In both of these the idea is to train a neural network to learn the optimal policy, i.e. the optimal action to take in every state. The policy is learnt by trial and error — but in a smart way. We start out by driving the car around the environment with a random policy (since we don’t know any better yet). Every time step we record the state (the 3 sensor distances) and the reward we got in that state. The policy is then periodically updated using the state/reward information after which we use this new and hopefully slightly better policy to drive the car around. Then it’s a case of rinse and repeat until we converge or until we are happy with the policy’s performance.</p><p>Q-learning and Policy Gradients are both algorithms for finding an optimal policy but they work a little differently. In Q-learning a function <em>Q(s,a)</em> is learnt that maps every state <em>s</em> of the system and action <em>a</em> to a value that is an estimate for the sum of future rewards, given that we start from this state <em>s</em> and take action <em>a</em>. As an example consider the case when all our distance sensor readings return a high value. This means all objects are far away and we are not likely to crash anytime soon; this will therefore correspond to a high Q value. Once the Q function has been learnt the optimal action to take in a new state can be found by taking the maximum of the Q function over all actions in this state, i.e. <em>a_optimal=argmax Q(s,a)</em>. We simply take the action corresponding to the highest Q value at every time step. The Q function therefore implicitly defines our policy.</p><p>Since we won’t be using Q-learning I will not go deeper into this. In fact most people prefer to use Policy Gradients which has been shown to work better than Q-Learning when tuned well (<a href="http://karpathy.github.io/2016/05/31/rl/">quote taken from Andrej Karpathy’s blog</a>).</p><h4>Policy Gradients</h4><p>The policy gradient approach is more direct than the implicit policy in Q-learning. Here a policy network is trained that maps every state to a probability distribution on the actions, without resorting to the Q function first. Since the car senses the environment with 3 distance sensors this means that our policy network will map a 3-dimensional input (distance left, distance front, distance right) to a 3-dimensional output (turn left, turn right, go straight). For each of the 3 actions it will assign a probability of how likely it is to take this action given the input state. A well-trained policy example might for example output [0.02, 0.95, 0.03] if the state was [5, 8, 100]. This means that it is 95% confident that turning right is the best action to take when the left and front sensors indicate that there is an object nearby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*PpPOKteD8H0UOrk1V53LsQ.png" /><figcaption>The policy network takes as input the sensor values and returns the probability distribution on the action the car should take. It’s a neural network with two fully connected hidden layers of 64 nodes.</figcaption></figure><p>But how are we going to train the network if we don’t know what the correct actions are? The key to this is the rewards we collect at every time step. The rewards in reinforcement learning can be thought of in the same way as the correct labels in supervised learning. I’d like to give an intuitive explanation of how this works by highlighting this close connection between Policy Gradients and supervised learning.</p><p>In supervised learning we would have a training set of labels telling us what the correct action to take is for every input in the training set which we could then use to train a classifier. The problem is that there are no correct actions in reinforcement learning; the system has to learn these for itself. But let’s suppose for a moment that we do have a training set with correct actions, and that our car has only two possible actions (e.g. left and right) to choose from instead of three (left, right, straight). This means that for every state ss we have a label that is either 1 or 0 depending on whether action 1 or action 2 is correct. This is simply a supervised learning problem and we could <a href="http://cs229.stanford.edu/notes/cs229-notes1.pdf">train a logistic regression classifier</a> by maximizing the log-likelihood of the parameters of our policy network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*fkgXJPMgSTxe_a1-hVMOBQ.png" /></figure><p>where π_1 is the probability the policy network predicts for taking action 1, and y^(i) is the supervised label that is 1 if action 1 is the correct action in state s^(i) and 0 for action 2. T is the size of our training set (i.e. the number of time steps we drove the car with the policy) and θ is the parameter vector of the policy network. We can rewrite this as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*VJG5RUJVsZ_VQ4zikHKzDQ.png" /></figure><p>where I used the notation π_correct to denote the probability the policy network predicts for taking the action that corresponds with the supervised “correct” label. In order to maximize this function we compute the gradient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*4Xox1RpDUNQqJbI5Xkpyzg.png" /></figure><p>using backpropagation and do gradient descent. This will give us a policy that is more likely to predict the correct labels from our training set.</p><p>Now let’s link this to Policy Gradient methods. The difference here is that we want to make the actions that led to high rewards more likely. If in the expression above we therefore use whatever actions the policy chose at each time step (instead of the correct actions which we don’t know) and then weigh them by the discounted sum of rewards R we get the following expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*mC-1urQW5LZxJDrVvuBxww.png" /></figure><p>This is the formula for the gradient that is used in vanilla Policy Gradient. Following this gradient will cause trajectories that led to high rewards to become more likely, while trajectories that led to negative rewards will become less likely. That’s exactly what we want! Well, almost. We can still do a little bit better. The problem is that every trajectory that has a positive reward will cause the policy that led to it to become more likely, even if the reward was small and the policy therefore wasn’t such a good one. What we really want is only for “better than average” policies to become more likely. That’s why in practice we subtract a baseline from the reward at every time step. The value function <em>V(s)</em> can be shown to be a near-optimal choice for this baseline.</p><p>Another problem is that it is hard to find a suitable gradient descent step size that works for the whole optimization, since the distribution of the data changes every time we update our policy network. This is because taking different actions leads us to different states. This is very different to supervised learning problems where the training set is fixed and changing the parameters of our network does not change it. That’s why in practice you probably want to use a slightly different form of Policy Gradients called <a href="https://arxiv.org/abs/1502.05477">Trust Region Policy Optimization (TRPO)</a>. TRPO linearly approximates the performance of the policy in the region around the current policy parameters. It then has a measure of how changing the policy parameters will affect the performance, albeit only locally valid. Using a clever line search on this linear approximation it then can find a step size in the direction of the policy gradient that can be proven to monotonically improve the policy. More details on Policy Gradients and TRPO can be found in <a href="https://www.youtube.com/watch?v=gb5Q2XL5c8A&amp;t=1627s">John Schulman’s lectures</a>.</p><h4>Learning to drive</h4><p>Let’s start this section with a video to regain your attention, after that somewhat dull explanation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsNI-Wtf-KBg%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsNI-Wtf-KBg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsNI-Wtf-KBg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba26278ae8eadee7659660b5003d1210/href">https://medium.com/media/ba26278ae8eadee7659660b5003d1210/href</a></iframe><p>In the video the learnt policy is shown after one day of training on an AWS C4.large instance (comparable in performance to a laptop). It still crashes sometimes but clearly has learnt how to avoid obstacles. I trained two different policy networks, one with vanilla Policy Gradient and one with <a href="https://github.com/joschu/modular_rl">John Schulman’s implementation of TRPO</a>. The vanilla PG algorithm simply does gradient descent on the policy gradient, and uses RMSProp to adaptively change the learning rate in every iteration. The TRPO algorithm uses the policy gradient too but does more fancy stuff with it as explained above. And it pays off, as can be seen in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*Qwrc93xSxM9H5Co6MllNcg.png" /><figcaption>Moving average of mean episode rewards for TRPO and Vanilla PG.</figcaption></figure><p>The graph shows the mean episode reward as the simulation progresses. It’s a moving average over 10 iterations to reduce the noise. Every iteration consists of 20.000 time steps, with a maximum episode length of 4000. This means that the environment is reset after 4000 time steps, or before that if the car if the car crashes. After each iteration the policy network is updated. The episode reward is roughly equal to the number of time steps the car did not crash. The maximum achievable reward is 4000 (actually a bit lower since there are penalties for turning left and right).</p><p>The TRPO’s performance improves quickly and then levels out at a mean reward that fluctuates around 2250. This noise is due to the random obstacle locations (within a grid). The car’s initial position is also random, although there is a safety margin so that it does not crash immediately. Because of the random nature of the obstacle locations there are sometimes gaps between obstacles that are too small for the car to go through. This is very difficult to detect with only 3 sensors. Adding more sensors would certainly help. The red graph shows the performance when using 2 extra sensors at +90 and -90 degrees, i.e perpendicular to the driving direction. For the same reason the car can sometimes get stuck in a cavity in which it is certain to crash because it can only turn so sharply. Again increasing the number of sensors to detect these cavities before entering them or decreasing the car’s turning circle might further increase the performance.</p><p>It’s clear that the improvement per iteration is a lot lower for the vanilla PG algorithm than for TRPO. Since running the policy in PyGame to generate data is the bottleneck for both algorithms, the computation time per iteration is also very similar. Within 30 minutes the TRPO reaches the same performance it took the vanilla PG algorithm a whole day to achieve. I think the Vanilla PG is still improving and should eventually reach the same performance as the TRPO algorithm.</p><p>Both TRPO and our vanilla PG algorithm use the value function V(s)V(s) as a baseline to subtract from the rewards so that only policies that achieve better than average rewards (as measured by the value function). The value function is a neural network with exactly the same architecture as our policy network: it has two fully connected hidden layers of 64 nodes. This means that every iteration we need to update not only the policy network but the value function as well. It’s interesting to see what the value function looks like for our learnt policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*v9hJ_dsdjLYS2PzbC0aDSg.png" /><figcaption>Value function as a function of left and front sensor distance.</figcaption></figure><p>Remember that the value function maps our 3D state vector of distances to a single value that measures how good this state is. More specifically it tells us what the expected discounted sum of rewards will be if we start out in this state. In the graph above the value function as a function of the left and front sensor distances, keeping the right distance sensor fixed at 100 (since sadly we can’t visualize 4D). It can be seen that a small distance for the front sensor corresponds to a negative value. This makes sense: if the distance is too small our car cannot turn sharp enough to avoid the obstacle and will crash. Large values of the distance sensors correspond to high rewards.</p><h4>Looking ahead</h4><p>Our learnt policy performs OK but doesn’t reach the maximally attainable reward. Like explained above, adding more distance sensors around the car will solve this problem. Distance sensors however only allow the car to detect obstacles. Since the car should also be able to follow a track I will follow a different approach and use a camera mounted on the front of the car as input to the policy network. This will allow the car to both detect obstacles (other cars) and follow the track. This is quite challenging since the input to our network goes from 3 dimensional to having 4096 dimensions (for a 64 by 64 image). You can read about it in <a href="https://medium.com/@sdeleers/autonomous-car-with-reinforcement-learning-part-2-track-following-4ffbf7aa33d1">part 2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c73a2567b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autonomous car with Reinforcement Learning — part 2: track following]]></title>
            <link>https://medium.com/@sdeleers/autonomous-car-with-reinforcement-learning-part-2-track-following-4ffbf7aa33d1?source=rss-1083a050fde4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ffbf7aa33d1</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Simon Deleersnijder]]></dc:creator>
            <pubDate>Sat, 04 Nov 2017 12:18:14 GMT</pubDate>
            <atom:updated>2017-11-04T12:52:54.678Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In the </em><a href="https://medium.com/@sdeleers/autonomous-car-with-reinforcement-learning-part-1-obstacle-avoidance-7c73a2567b7b"><em>last post</em></a><em> I trained a ball-shaped car to avoid obstacles using distance sensors. While it illustrates the concept of reinforcement learning it can hardly be called an autonomous car. In this post I will make the car model more realistic and use a camera to sense the environment rather than distance sensors. The car will then be trained to lap a race track as fast as possible while avoiding other agents driving around the same track.</em></p><h4>The car model</h4><p>The dynamics of the car will be simulated using a bicycle model. It is modeled as having two wheels of which only the front can turn. To make the cornering more realistic the maximum turning angle of the front wheel depends quadratically on the speed of the car: if the car goes very fast it can’t turn as sharply as when it is driving very slowly. This is because in real life the centripetal force generated by the friction between the tyres and the road also depends quadratically on the speed. Turning sharper than this maximum angle would cause the car to spin since the tyres cannot generate enough friction.</p><p>Unlike in the previous post the car will always start from a standstill. It therefore also needs to be able to accelerate, and decelerate. Accelerating and decelerating increases/decreases the car’s velocity with a fixed amount, regardless of the car’s velocity.</p><h4>The simulation environment</h4><p>I made a simple car game in Pygame with the physics model I described above. The race tracks are made by parsing SVG files of existing Formula One circuits and using the svg.path library to turn them into coordinates. The rendering is done with OpenGL which is a rendering engine that allows you to create a 3D scene and then look at it from different viewpoints. This means we can easily look at the race track from the top and also from the car’s perspective. The image rendered from the car’s perspective will be used as input to our neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*86iT3wZcSUbvFyxPVX5ZMw.png" /><figcaption>Top view of the environment with the car shown in green (left) and the view from the car (right).</figcaption></figure><p>The up arrow makes the car accelerate, the down arrow makes the car decelerate. The left and right arrows set the front wheel’s angle to the maximum allowed turning angle (this depends on the speed as explained above). Pressing the “s” key sets the front wheel back in the straight position.</p><p>But why would I push the buttons myself if I can let a neural network do it?</p><h4>The policy network</h4><p>I will use reinforcement learning (and more specifically policy gradients) to train a policy network that takes an image from the car’s perspective and outputs for each of the 5 actions (accelerate, decelerate, go straight, turn left, turn right) a probability of it being the “right choice”. In the last post I used a policy network with 2 fully connected hidden layers. This was ok since the inputs were the 3 distance sensors which are scalar values.</p><p>Now the policy network’s input is the red channel of a 64x64 RGB image. I can get away with only using the red channel because I made the color scheme so that the 3 channels have the same value for all objects in the scene. The cars are white (255, 255, 255), the road is brown (123, 123, 123) and the off-track area is black (0, 0, 0).</p><p>When using a neural network with images as inputs convolutional layers are very useful. They make the assumption that the features in the image (edges, corners, cars, etc.) are location independent and can appear anywhere in the image. In doing so they drastically reduce the number of parameters of the network. Since the size of our input layer has increased from 33 to 64∗64=4096 this is quite helpful.</p><p>I chose the architecture for the policy network to be the same as the one used in the <a href="https://arxiv.org/abs/1312.5602">paper by Mnih et al.</a> in which a neural network is trained to play Atari games. The network consists of 3 convolutional layers followed by a fully connected hidden layer, and then a fully connected output layer. The only difference is that I’m also adding the car’s speed as an input to the first fully connected layer. Without the speed input the car wouldn’t know at what speed it was approaching a corner. This is crucial since it needs to slow down if it’s going too fast; otherwise the car can’t turn sharply enough to round the corner. Another way of providing the car with speed information would be to provide the network not only with the current camera state but also with the camera state from previous time steps. If the car is standing still the 4 images would be exactly the same, if it was going at full speed they would be quite different.</p><p>It is not easy to visualize a convolutional neural network’s architecture but the Keras code explains it well enough:</p><pre>input_img = Input(shape=(64, 64, 1)) <br>conv1 = Convolution2D(32, 8, 8, subsample=(4, 4), border_mode=&#39;valid&#39;, activation=&#39;tanh&#39;, input_shape=img_shape)(input_img) <br>conv2 = Convolution2D(64, 4, 4, subsample=(2, 2), border_mode=&#39;valid&#39;, activation=&#39;tanh&#39;)(conv1) <br>conv3 = Convolution2D(64, 3, 3, border_mode=&#39;valid&#39;, activation=&#39;tanh&#39;)(conv2) input_fc = Input(shape=(1,))<br>concatenated = merge([Flatten()(conv3), input_fc], mode=&#39;concat&#39;) fc1 = Dense(512, activation=&#39;tanh&#39;)(concatenated) <br>fc2 = Dense(5, activation=&quot;softmax&quot;)(fc1) net = Model(input=[input_img, input_fc], output=fc2)</pre><h4>Reward function</h4><p>In reinforcement learning the policy is learnt via trial and error (kind of). The car starts driving around the environment with a randomly initialized policy. You can hardly call it driving at this point though since it is randomly applying the brakes, the throttle and the steering wheel. In order for the policy to improve the car needs to be told what actions it took were good and which ones weren’t.</p><p>But what is good and what is bad? This is defined by the reward function. Since the policy network will try to maximize the rewards, it implicitly defines how our policy will behave. I found the following reward function to work quite well:</p><ul><li>The race track is divided into segments and for every segment the car crosses it gets a +10 reward.</li><li>The car gets a -15 penalty for every time step it is off track. If the car is off track for more than 50 time steps the environment is reset.</li><li>If the car crosses a road segment in the wrong direction it gets a -10 penalty.</li></ul><p>The environment is also reset when the car crosses more than 5 road segments in the opposite direction. This is to avoid giving a penalty to a policy that correctly follows the track in the wrong direction. Since the policy to follow the track in the opposite direction is likely very similar to the one to follow it in the correct direction this would slow down the learning.</p><h4>Training the network</h4><p>After the car has driven around for 5000 timesteps we give the learning algorithm the sum of future rewards at every one of the 5000 time steps. This sum is discounted so that rewards far in the future have a smaller contribution. The sum of discounted rewards at time step 100 for instance would be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*5eM2-76l8UZK2kssstIwrQ.png" /></figure><p>γ is the discount factor and r_t is the reward at time step t. We calculate this sum R_t for every of the 5000 time steps and give it to the learning algorithm. Now imagine that the car arrives at a left hand corner at time step 100. If the car chose to turn the wheel to the left the sum of future rewards would most likely be higher than if it turned the wheel to the right since then it would go off track. But since the sum of future rewards also depends on the future actions at time steps 101, 102, etc. this is not guaranteed to be the case. Indeed, the car might turn left after having turned right in time step 100, or turn right after having turned left in time step 100. In statistical terms we could say that the experimental sums of rewards are a high-variance but unbiased estimator for the expected value of the sum of rewards. Since our learning algorithm tries to maximize the expected value of the sum of rewards this means that we might need a lot of iterations before the car learns how to drive properly.</p><p>I will again be using <a href="https://github.com/joschu/modular_rl">John Schulman’s TRPO library</a> to train the policy. TRPO is similar to a vanilla Policy Gradient algorithm in that it calculates the policy gradient (this is the estimator for the gradient of the expected value of the sum of rewards). But TRPO then does some more clever stuff with it to improve the convergence. It therefore learns more quickly than a vanilla Policy Gradient algorithm would.</p><p>The results of training the car with TRPO on an AWS p2.xlarge instance can be seen in the video below. I used a p2.xlarge instance since it has a GPU and this speeds up the forward and backward passes of the convolutional neural network significantly. The learning algorithm trained for less than a day.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FS6nH3NwCZDM%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DS6nH3NwCZDM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FS6nH3NwCZDM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fc6bd06f31912a37221393286359af2/href">https://medium.com/media/2fc6bd06f31912a37221393286359af2/href</a></iframe><p>The top view of the race track is shown on the left, and the inputs to the neural network (camera image and speed) are shown on the right. The car has learnt to accelerate from a standstill and slow down for corners. On the straights it accelerates again and although I’d hoped it would corner a bit more agressively (it’s not always hitting the apex) I think it does quite well.</p><p>When I the put the car on another track, or on the same track in the other direction it performs reasonable but not nearly as well as on the track it trained on. It ends up off the track too many times. A next step would therefore be to train the car on a large number of tracks and then test its performance on a validation set of tracks that it has never seen before. But computation time on the AWS p2x.large instances isn’t free and coming from my own money :) So instead let’s only use this track in the direction we trained on and add some other cars!</p><h4>Adding multiple agents</h4><p>To help the car realize that crashing into other cars is bad we will change the reward function. This can again be done in more than one way but I found the following to work well:</p><ul><li>If the car crashes into another car it gets a penalty of -500 and the environment is reset.</li><li>If the car overtakes another car it gets a reward of +500.</li></ul><p>I chose to reset the environment after a car crash. Another option would be to simulate the car crash in Pygame. Since a car crash will decrease the car’s velocity and therefore the number of track segments it will cross per time this will result in an implicit penalty. Therefore we might not need the -500 penalty in that case.</p><p>The policy network needs to be changed as well. The problem with the network’s current inputs is that it cannot detect movement of other cars: it only gets a single static image. In order for the car to detect movement it needs extra sensors. A solution would be to provide the car not only with the current camera state but also with the camera state from the 3 previous time steps. This way the car gets information about how the environment in front of it is changing over time.</p><p>I instead chose to use distance sensors from 4 points in time (current and 3 previous readings). This not only allows the car to detect movement but also helps the network to detect the cars. Sure, it can already detect the cars from the camera image but adding distance sensors will only make it better. Note that the distance sensors sense in a plane parallel to the ground and can therefore only detect other cars. They cannot sense the road.</p><p>I trained the network once again with TRPO on an AWS p2.xlarge instance. The network weights were initialized with the weights that were learnt in the previous simulation without other cars. The weights corresponding to the new distance sensors were set to zero and therefore the initial policy network exactly matched the previous one at iteration 0. This process of gradually increasing the difficulty of the task and using the network learnt in the previous task is called curriculum learning. It generally improves the speed of convergence, compared to trying to learn the more difficult task from scratch.</p><p>The car was trained for roughly 12 hours on an environment with 2 other cars that were driven with the old policy (zero weights for distance sensor nodes). Every time our agent overtakes a car, the car that was overtaken gets reset some distance in front of our car. This way there is a continuous stream of cars to overtake while keeping the number of agents manageable.</p><p>After training I put the car on track with 11 other agents. I limited the top speed of some of the cars to increase the number of overtake manoeuvres. There are 4 fast cars and 8 slow cars. The fast cars use the new policy and the slower cars use the old policy with zero weights for the distance sensor nodes. This was the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FCPeUW1vXqR0%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DCPeUW1vXqR0&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FCPeUW1vXqR0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/17467b094182962872473ab5599f41c2/href">https://medium.com/media/17467b094182962872473ab5599f41c2/href</a></iframe><p>I think it does quite well. When I put the learnt agent on another track however it does significantly worse, meaning that the neural network has overfit the training data. This can be solved by training on a variety of tracks. Also when I use another policy for the other cars our red car will crash a lot more. This is because the network has only learnt to overtake cars that were driven around with one specific policy (the one with zero weights for the distance sensor nodes). Again, this is a problem of overfitting. It would therefore be a good idea to randomly select a policy for the other agents during training, for instance one of the policies learnt in previous iterations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ffbf7aa33d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>