<?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 Drew Parmelee on Medium]]></title>
        <description><![CDATA[Stories by Drew Parmelee on Medium]]></description>
        <link>https://medium.com/@doingengineering21?source=rss-e7cec11c7aba------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Epjm8DBJqlhgTxhSAepTFA.jpeg</url>
            <title>Stories by Drew Parmelee on Medium</title>
            <link>https://medium.com/@doingengineering21?source=rss-e7cec11c7aba------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:13:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@doingengineering21/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[Getting an AI to play atari Pong, with deep reinforcement learning]]></title>
            <link>https://medium.com/data-science/getting-an-ai-to-play-atari-pong-with-deep-reinforcement-learning-47b0c56e78ae?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/47b0c56e78ae</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Tue, 26 Jan 2021 19:17:06 GMT</pubDate>
            <atom:updated>2021-01-26T20:40:38.819Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detailed instructional</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*hHXVW-Unl96OHJOZ1J_4ig.gif" /><figcaption>First we dominate pong, and next, the world…</figcaption></figure><p>Getting a computer program to learn how to play Atari games may seem like a very difficult task. Well, I’ll tell you what … it is. But believe me, if I can do it then so can you. This page assumed you have read through and somewhat slightly understand the theory of deep RL (link posted below). But beware, the theory is not enough to get an agent to learn Atari! With reinforcement learning, everything is in implementation and the devil is in the details! So, the rest of the post will be focused on implementing the code line by line to get our agent working.</p><p><a href="https://towardsdatascience.com/what-is-deep-reinforcement-learning-de5b7aa65778">What is Deep Reinforcement Learning?</a></p><h3>Implementation:</h3><p>For implementation, we will be using the Open AI Gym environment. For the agent&#39;s neural network, I will be building a CNN using Keras. We will first tackle Pong, then in a separate article, we will get the agent to play breakout (it takes a lot longer to train). Really take your time and read through my code to understand what is going on.</p><p>Also, I highly recommend you do this project on google colab if you don’t have a powerful computer. If you don’t know what google colab is, google it and check it out! They provide GPU and CPU&#39;s for you to run code on for free.</p><p>The strategy here is this; we receive the current game frame from openai gym. A tensor of the pixel values from the 4 most recent frames is our current state (more on this later). Based on the epsilon greedy strategy, we either take a random action or we input our current state into our CNN to get our action. Now we take our action, receive a reward, and are brought to a new state. We store our (S,A,R,S’) values in memory for training. After each action, we randomly sample data from our agent&#39;s memory and train our agent using the loss function we derived in the article on deep RL theory (linked above).</p><h4>A Quick Open AI Gym Tutorial</h4><p>Open AI Gym is a library full of atari games (amongst other games). This library easily lets us test our understanding without having to build the environments ourselves. After you import gym, there are only 4 functions we will be using from it. These functions are; gym.make(env), env.reset(), env.step(a), and env.render().</p><ul><li><strong>gym.make(env): </strong>This simply gets our environment from open ai gym. We will be calling env = gym.make(‘PongDeterministic-v4’), which is saying that our env is Pong.</li><li><strong>env.reset(): </strong>This resets the environment back to its first state</li><li><strong>env.step(a): </strong>This takes a step in the environment by performing action a. This returns the next frame, reward, a done flag, and info. If the done flag == True, then the game is over.</li><li><strong>env.render(): </strong>env.render() shows the agent playing the game. We are only going to use env.render() when checking the performance of our agent. I don’t think this works in google colab or any other notebook, though I may be wrong. Because of this, you may have to save the weights of the agent then load them on your local machine and render the game there.</li></ul><p>A code example of how to implement these functions is written below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab225333f1a500a12e128bc5873b4bcc/href">https://medium.com/media/ab225333f1a500a12e128bc5873b4bcc/href</a></iframe><h4>Preprocessing Frames</h4><p>Currently, the frames received from openai are much larger than we need, with a much higher resolution than we need. See below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*zCctvsYN-PPghvoBgadflw.png" /><figcaption>We don’t need any of the white space at the bottom, or any pixel above the white stripe at the top. Also, we don’t need this to be in color.</figcaption></figure><p>Firstly, we crop the image so that only the important area is displayed. Next, we convert the image to grayscale. Finally, we resize the frame using cv2 with nearest-neighbor interpolation, then convert the image datatype to np.uint8. See the code below for implementation…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aab1566f647543fd260b7c0aa06be8a9/href">https://medium.com/media/aab1566f647543fd260b7c0aa06be8a9/href</a></iframe><p>The resulting image looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*iA6hI4Cg0RQColmdMSM8HA.png" /></figure><h4>Supplying Directional Information</h4><p>Put yourself in the agent&#39;s shoes for a second and look at the frame below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*C3GwEVqNxMyNlhHWkThGGQ.png" /></figure><p>Now, which way is the ball is moving … well there&#39;s no way to know. We can only know the position since we only have one timestep. There is simply not enough information provided in one frame to know the direction. If given 2 timesteps we can know the velocity of the ball, and if given three then we can know the acceleration, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*kUia1piVQDPWUwjIO7jI-g.gif" /></figure><p>Recall that our frames are a matrix of pixel values. To add the directional information into our input, we can simply stack our frames together to form a tensor. Taking our frame&#39;s shape to be (84,84), the shape of our state will be (84,84, 4) if we stack the most recent 4 frames together. So at time t in-game, our current state is a stack of the frames at t, t-1, t-2, and t-3.</p><h4>Agent Memory</h4><p>Before I get into implementing agent memory, I want to explain what inspired researchers to use it in the first place.</p><p>When I first approached this project, I tried to train the agent using the data generated in real-time. So at timestep t, I would use the (S,A,R,S’) data from time (t-1) to train my agent.</p><p>The best way I can explain the problem with this is by going back to my early days in college. In my sophomore year, I had statics theory shoved down my throat for a year straight (I pursued mechanical engineering). Then in my junior year, I did nothing with statics and instead had machine design shoved down my throat. Come senior year, I’d forgotten everything there was to forget about statics.</p><p>In our environment, there might be 100 frames of the ball just moving to the left side of the screen. If we repeatedly train our agent on the same exact situation then eventually it will overfit to this situation and it won’t generalize the entire game, just like how I forgot about statics while studying machine design.</p><p>So, we store all our experiences in memory, then randomly sample from the whole list of memories. This way the agent learns from <em>all</em> his experiences while training, and not just his current situation (to beat this dead horse a little more, imagine if you couldn&#39;t learn from the past, and instead you could only learn from the exact present).</p><p>Alright now for implementation. For the memory, I make a separate class with 4 separate deques (a first in first out list of fixed size). The lists contain the frames, actions, rewards, and done flags (which tells us if this was a terminal state). I also add a function that allows us to add to these lists.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64b4bafa5a1d20902291f2b4f8e76d03/href">https://medium.com/media/64b4bafa5a1d20902291f2b4f8e76d03/href</a></iframe><h4>The environment</h4><p>Next, we get into implementing our environment. I do this by making 4 functions;</p><ul><li>Make_env()</li><li>Initialize_new_game()</li><li>take_step() … this is where all the magic happens</li><li>play_episode()</li></ul><p>I&#39;m going to show the code before I get into the specifics so you can follow along.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26a438666d81a8cd6438863844e6d633/href">https://medium.com/media/26a438666d81a8cd6438863844e6d633/href</a></iframe><p>The <strong>make_env()</strong> function is self-explanatory. It just calls the gym.make() function.</p><p>The <strong>initialize_new_game()</strong> function resets the environment, then gets the starting frame and declares a dummy action, reward, and done. Now, this data is added to our memory 3 times. Remember we need 4 frames for a complete state, 3 frames are added here and the last frame is added at the start of the take_step() function.</p><p>The <strong>take_step()</strong> function is a bit complicated. I’ll list the pseudocode below:</p><ol><li>Update agents total timesteps</li><li>Save weights every 50000 steps</li><li>Now, we call env.step using the last action in our agent&#39;s actions list. This returns the next frame, reward, done flag, and info</li><li>Resize the next frame and get the next state from the last 4 frames.</li><li>Get the next action using the next state. This is why we are able to use the last action in the agent&#39;s action list in step 3</li><li>If the game is over, then return the score and a terminal flag</li><li>Add the experience to memory</li><li>If debugging, render the game. We won’t be using this, but I found it useful when trying to get this to work.</li><li>If the agent&#39;s memory contains enough data, then have the agent learn from memory. More on this later.</li><li>Return the agents score and a false terminal flag</li></ol><p>As you can see, this function works with the agent class a lot. This class will be introduced shortly.</p><p>The <strong>play_episode </strong>function is pretty self-explanatory. This function just initializes a new game, calls the take_step function until a true terminal flag is returned. Then the episode score is returned.</p><h4>The Agent class</h4><p>This class has 5 functions, including the constructor. These functions are: __init__(), _build_model(), get_action(), _index_valid(), and learn().</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9a7cf8af4bb2c5c582e54142614f9fc/href">https://medium.com/media/e9a7cf8af4bb2c5c582e54142614f9fc/href</a></iframe><p>The <strong>build_model()</strong> function just constructs a CNN for the agent. Note that there are no max_pooling layers in the CNN, since pooling eliminates some needed spatial information. I use the Huber loss and Adam initializer.</p><p>The <strong>get_action()</strong> function is just an implementation of epsilon greedy. We generate a random number, and if it is less than our epsilon value, we take a random action. If not then we pass the current state into our CNN and return the max output.</p><p>The <strong>_index_valid()</strong> function is a helper to the learn function. It simply checks to see if there was a terminal frame within the past 4 frames of our memory, at the given index. We don&#39;t want to create a state that is in between 2 games.</p><p>Before I explain the learn function, you may have noticed the model_target attribute to the class. This is a method that is used to decrease training noise. Basically, we copy our CNN so we now have our model, and something called our model target. Now, recall that when training we input the next state into our CNN to help generate the target for the error function. Notice that after the weights are updated, the target within the error function will change since the CNN is being used to generate this target, and the CNN weights were just changed.</p><p>Below is a reminder of our loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*RxSQAuBRP2C6INFf0_nMkA.png" /><figcaption>V(t+2) is an output to our NN. So if we update our weights once, then V(t+2) will change a bit. This means our target is moving, which in practice has proven to be inefficient.</figcaption></figure><p>Someone at google had the idea that we could use the target model to generate the targets for our loss function, then every so often we just set the weights of the target model to the weights of our main model. So they gave that a go, and it increased performance and decreased training time (which is why I implemented it here).</p><p>So now onto the <strong>learn()</strong> function. We will be training our CNN with a minibatch size of 32.</p><ol><li>Our first step is to gather 32 states, next_states, actions, rewards, and done flags.</li><li>We pass our states through our model and our next states through our target model. The output we get from our model will be modified in the next step so it can be used as our Vtrue.</li><li>Now for each state in our minibatch, we first figure out which action was taken. Then we calculate the true value of taking this action and replace the outputted value with this true value. The <em>not next_done_flags[i] </em>code just ensures that if we are at a terminal state, the next reward is not taken into account. Also, gamma is called a discount factor. It just makes current rewards hold more weight than future rewards. Gamma can be taken out without fear of breaking the agent.</li><li>Now we fit our model using our states and the labels we created.</li><li>Now update epsilon and how many times the agent has learned</li><li>Copy the model weights to the target model every 10,000 steps</li></ol><p>And that&#39;s it for the agent. The learn function is where things went wrong for me when I first tried this project. So if you are having trouble check here first.</p><p><strong>main.py</strong></p><p>Now for our final file. I&#39;m not going to go into much detail here, the file is pretty self-explanatory. Just initialize your agent and environment, then call the play_episode() function in a loop. Every so often print out some useful metrics, every 100 episodes I print out a graph that shows a moving average of the scores. After training my agent, I realized it would be more useful to plot the scores against the steps taken instead of games played. If you are recreating this project I suggest plotting the scores every 10,000 or so steps.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b14e870b84e046d7dbd95bc1e5fb9124/href">https://medium.com/media/b14e870b84e046d7dbd95bc1e5fb9124/href</a></iframe><h4>Summary:</h4><p>You can find the complete, finished project <a href="https://github.com/Meredevs/DQN_Pong">here</a>. Training took about 24 hours. The final result is the agent on the right in the gif at the top of this post.</p><p>My first time doing this took weeks. It really is a difficult project. If you are having trouble, really take the time to understand the theory and read through my code.</p><p>This particular RL algorithm is called Deep Q Learning. Deep Q Learning is usually treated as an introduction to deep RL, but it is not the most effective algorithm out there. My favorite algorithm to use is A2C, which I will go over in a future post.</p><p>But before I do, let’s prove just how cool this algorithm is. I once showed this to a friend and he said, “Well couldn&#39;t you have just hardcoded the paddle to follow the ball”. Although he is right, the cool part about this project is not just that we got it to play pong. It is that the agent <em>learned</em> to play pong. This algorithm is a step towards general artificial intelligence. A way to prove that we have obtained some degree of general artificial intelligence is to see if this agent can learn multiple games. I will leave a link here to an instructional on how to get this agent to learn the game Breakout when finished.</p><p><em>*All images, gifs, and code snippets by the author!*</em></p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47b0c56e78ae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/getting-an-ai-to-play-atari-pong-with-deep-reinforcement-learning-47b0c56e78ae">Getting an AI to play atari Pong, with deep reinforcement learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Deep Reinforcement Learning?]]></title>
            <link>https://medium.com/data-science/what-is-deep-reinforcement-learning-de5b7aa65778?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/de5b7aa65778</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 21:35:31 GMT</pubDate>
            <atom:updated>2021-01-26T19:38:11.493Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detailed introduction</h4><p>Deep reinforcement learning has got to be one of the coolest tools I have used as an engineer. Once finished, all you have to do is tell the agent what it is you want to be accomplished, and watch as the AI figures out incredibly creative ways to accomplish this task.</p><p>Understanding neural networks (explained <a href="https://towardsdatascience.com/what-is-an-artificial-neural-network-b508c821ace8">here</a>) is a prerequisite for deep RL. Also, deep reinforcement learning can be more easily understood if you are comfortable with tabulated reinforcement learning, which I explain in-depth <a href="https://towardsdatascience.com/what-is-tabulated-reinforcement-learning-81eb8636f478">here</a>.</p><h4>Difference between Tabulated RL and Deep RL</h4><p>A quick summary of tabulated RL is this.</p><ol><li>The agent receives the state from the environment</li><li>Using the ε greedy strategy (or some other state exploration strategy), the agent either does a random action or the agent picks the action that will lead to the state with the highest value</li><li>At the end of the episode, the agent stores all the states that were visited in a table. Then the agent looks back at the states visited in that episode and updates the value of each state based on rewards received</li></ol><p>So, if we were given the true values of every state right from the get-go; this would be easy. We just make the agent always move to the state with the highest value. The main issue is finding these correct state values.</p><p>What deep RL does is; instead of keeping a table of all the values of each state we encounter, we approximate the value of all the next possible states in real-time using a neural network.</p><p>Let’s assume we already have a neural network that we can put our current state into as input and the output will be an array filled with the values of all the next states we can be in (if there is n number of possible actions then typically there are n number of next possible states we can be in). Say our environment is the atari game ‘breakout’, and our agent is in the beginning state (the first frame of the game). In breakout we can do 3 things; stay still, move left, or move right. Each of these actions will bring about a unique new state. We would input our current state into the NN and receive an array telling us the value of the state that will come from taking each action. We then take the action that leads to the highest value.</p><p>The diagram below is of a NN in an environment where there are only 2 available actions. The input is the current state, and the output is the next state values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*Vgkgx1UFK4mZSuh8gABn3g.png" /><figcaption><em>If there were N available actions, then there would be N outputs to the neural network </em><strong><em>*Image by author*</em></strong></figcaption></figure><h4>A quick note on Agent Memory</h4><p>Before we learn how to train our NN, it’s important to understand how we are storing the information received from playing the game. Most of the time, we are in a state S, we receive reward R, we take action A, we move to the next state S’. I say most of the time because if we are in a terminal state that ends the episode, we just receive a reward R (since there is no next state and action taken).</p><p>In practice, what we do is combine these values as a 4-tuple and store them in a list. So, it will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/0*YExa1dQYWHjXWuC-.PNG" /><figcaption><em>If the state is terminal, then A and S’ would be Nan</em></figcaption></figure><p>Now we have this information ready for when we want to train our agent.</p><h4>Training the Neural Network</h4><p>So, we know we want our output to be the values of the states that result from taking each action. In order to find all the weights in our NN that will make this possible, we need to identify the loss function we want to minimize. For starters,</p><blockquote><em>We want the difference between the output of our NN and the observed next state values to be 0</em>.</blockquote><p>If we use the mean squared error loss function, we obtain:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/0*3khCW7ZLT3ON04vC.PNG" /><figcaption><em>Don’t let the indexing trip you up, V^ai is the value of the state brought about from taking action ai. If having an index on an index freaks you out, it probably should, then just replace ai with i.</em></figcaption></figure><p>Now recall from tabulated RL that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*uEctqSMuhi-oQEad_CnIZA.png" /></figure><p>Or the value of the next state is just the reward received in that state + the value of the state after. Now to find V(t+2)true we could keep going and say,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*vXK0QqrUbhrCJcj1Vc3ujw.png" /></figure><p>Then find V(t+3)true the same way, then V(t+4)true all the way until we reach a terminal state. But this is impractical and frankly unnecessary.</p><p>In practice we can just say:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*tyYmRSY6-vishcbtPDxUbw.png" /></figure><p>Or, V(t+1)true = R(t+1) + the highest output we get from inputting the next state, S(t+1), into our NN.</p><p>This might seem kind of strange since with an untrained network V(t+2)predicted is going to be inaccurate nonsense. This is true, but over many weight updates the accurate information, R(t+1), is enough to eventually make the V(t+2)predicted values accurate. The way I think about it is this,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*Pk9jHHrvytsVTgtK72TO_Q.png" /></figure><p>But telling the NN R(t+1) lets it improve the accuracy of <em>V(t+</em><strong><em>1</em></strong><em>)predicted</em> ever so slightly so that over many iterations the Vpredicted values become accurate.</p><p>If what I just said doesn’t make sense, don’t worry about it. Really all you need to know is the loss function that we use is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*cVshTegZgaYfmQD7.PNG" /><figcaption><em>Vmax is the maximum predicted value. Or the maximum output of the NN. R^ai is the reward received for taking action ai. Note we only know the reward received for taking 1 of the actions. I call this training on partial information, which is the next topic. </em><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Training on partial information</h4><p>As a visual, imagine the NN below is in an environment with 2 actions. Now when our agent was in this state, he took action a1, and in the next state receives the reward R(a1,t+1). Now we have no idea what the value of the state that results from taking action a2 is since we took action a1. We need this for training!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/0*mp7ma4bmcyunGiTG.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>What we do is assume that the NN predicted the correct value for this action, so the difference becomes 0. Not very elegant but it works! So, we end up with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*UhDXkgzq_S63PfYG.png" /><figcaption><em>If you want to experiment, an idea I never explored is assuming the NN predicted dead wrong at first then over time slowly change the assumption to assuming it was accurate. If you try this let me know how it goes in the responses! </em><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Theoretical Section Summary</h4><p>The theory can be a bit complicated, depending on how far you want to go into the fine details. The way I learned was by sitting down with some paper and a pencil and manually drawing 3 or 4 of the agent&#39;s timesteps and seeing how I would train these timesteps. If you want a deep understanding of what is going on, I suggest you do the same. Start at state St, where you receive reward Rt. Now draw some made up output values to the NN, then pick an action and record the (S,A,R,S’) tuple in memory. Now do the same for 2 or 3 more timesteps and say you reach a terminal state. Now randomly pick one of these timesteps and try to write down what the loss function would be to train the NN on this timestep. An example of what I did to understand this is shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*B8IICr92EaTyOraz.png" /><figcaption><em>The actions I decided to take are circled in green. Not that the top action is 0 and the bottom action is 1. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>If all the theory is a bit fuzzy, don’t worry. I would think you were an alien if you understood all of this perfectly the first time ever seeing it. But now that we have been introduced to the theory, the only way to truly learn it is to apply it. Just a side note, my first deep RL project took me weeks to figure out. This project is what taught me how important it is for code to be beautiful and <strong><em>readable</em></strong>. So, don’t be discouraged if you don’t get it right away. If I can do it then so can you.</p><p>Below is a link to a post where we implement this to get an agent to play Atari Pong. Check it out!</p><p><a href="https://towardsdatascience.com/getting-an-ai-to-play-atari-pong-with-deep-reinforcement-learning-47b0c56e78ae">Getting an AI to play atari Pong, with deep reinforcement learning</a></p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could&#39;ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de5b7aa65778" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-deep-reinforcement-learning-de5b7aa65778">What is Deep Reinforcement Learning?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is Tabulated Reinforcement Learning?]]></title>
            <link>https://medium.com/data-science/what-is-tabulated-reinforcement-learning-81eb8636f478?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/81eb8636f478</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 01:31:23 GMT</pubDate>
            <atom:updated>2021-01-22T20:41:22.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>The first step in learning how to make your AI teach itself</h4><p>Tabulated reinforcement learning is the first algorithm in which you should learn if you want to master the art of getting your AI to teach itself in a developing, and constantly changing environment.</p><p>In general, the main idea behind reinforcement learning is that you have an Agent, Environment, State, Actions, and Rewards.</p><ul><li><strong>Agent:</strong> The agent is the thing that is living in the environment, taking in input, and performing certain actions.</li><li><strong>Environment:</strong> The environment is the world that the agent is in.</li><li><strong>State:</strong> A state is basically all the inputs that the agent is receiving at a particular moment.</li><li><strong>Actions:</strong> The actions are all the ways that the agent can interact with its environment.</li><li><strong>Rewards/Punishments:</strong> Rewards are given to the agent after performing an action. They are just numbers, so if the agent does something bad, we may give it a punishment of -1. If it does something good, we would give it a reward of +1.</li></ul><p>In the environment, we have an agent. This agent takes in some type of input from the environment, this input is the agent&#39;s state. Based on its state, the agent takes some action. This action brings the agent to a new state. Depending on if this new state is good or bad, the agent receives a reward/punishment. The diagram below helps to visualize this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*Puw3tHdcj4ljr3HB.png" /><figcaption><em>Note the order of events written in blue. The environment offers a state to the agent, the agent takes an action based on this state, this action changes the environment and offers a reward/punishment. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>To further drive the point home, if you think of yourself as an agent then the entire universe is your environment. You have 5 senses or 5 ways to receive input. At any particular time, your current state is what you are seeing, hearing, smelling, feeling, and tasting. You perform an action based on your current state. These actions eventually lead to either a reward (promotion at work maybe) or a punishment (getting fired). The idea is that you will learn from these punishments and rewards so that your future actions will lead to better rewards.</p><p>To get some more jargon out of the way, an <em>episode</em> is one full cycle of the agent interacting with the environment. For example, if the environment was a game of tic tac toe an episode would be one game of tic tac toe.</p><h4>Agent Memory/Value Table</h4><p>As the agent interacts with the environment, we can store all the states that the agent has been in and assign a value to each of these states. A state’s value is a measure of how many rewards the agent can expect to receive for the rest of the episode (for right now, understanding what this means quantitatively is not important). I will explain how to assign the correct values in a moment, but for now, just know that it is possible.</p><p>For example, say our agent is just starting its first game of tic tac toe. The environment is the game tic tac toe, and its current state would be the empty game board. The agent would store this unique state, say s0, in its memory. Say our agent then takes a random action, call it a0. Recall that taking an action brings a new state, let’s call it s1. Now say our agent continues to play with his opponent and ends up losing the game (it will receive some kind of punishment at this point).</p><p>Since the agent lost, we can say that every state the agent was in during this episode has a low value. Now say our agent starts his second game and is back in s0. Now, it can look in its memory and see what happens if the action a0 is taken. It will see that action a0 will lead to state s1, which has a low value since the last time it was in this state it ended up losing.</p><p>Since the agent is trying to win, it will only pick actions that will lead to states with high value. To start game 2 the agent avoids action a0, since it has low value, and picks another action at random, say a2. Again, the agent continues to play; but this time he ends up winning. Since the agent won, we can say that every state the agent was in during episode 2 has a high value. Hopefully, the figure below is helpful in visualizing this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/0*F5IBEEFRq9sKwm6f.png" /><figcaption><em>Note the values are actually numbers, we will get into finding the correct numerical value of each state next. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>You might see a problem with what we have so far. What if the action a0 really is the best action to take, and it was another action taken after a0 that caused us to lose that game? As of now, if our agent always avoids a0 it will never see that it is the best action to take. To solve this, we always make our agent have a chance to take a <em>random</em> action. If our agent takes a random action, it has a chance to take a0 and give that action another shot. We call this <em>exploring the state space</em>. We usually have the agent take completely random actions at first, then as time goes on we slowly reduce the chance that the agent takes a random action. An algorithm that does this is discussed in the tic tac toe project linked to at the bottom of this page.</p><p>The agent will continue this process until it knows the best action to take in every state it can possibly be in. To summarize, <em>we are literally just telling the agent to try everything</em>, recording everything that happens, and finding which actions lead to the best states (the states that lead to the largest reward).</p><h4>Finding the value of each state</h4><p>To find the correct value of each state, we start by setting the value of each state to 0.</p><blockquote><strong><em>A state&#39;s correct value is equal to the expected total future reward for that episode.</em></strong></blockquote><p>See the figure below to help let this soak in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*D1evu8bV6QJqpjG3.png" /></figure><p>It is best to start at the last state. In S5 we receive a reward of +1. Therefore, the value of S5 is 1. Now S4 does not get a reward, but it leads to S5 which gives a reward of +1. Therefore, S4 has a value of the reward it has received + the value of S5, or a value of 0+1=1. Similarly, V(S3) = R3 + V(S4) = -1+0+1 = 0. In general, we can say;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/0*7mJOvP1gonTSpfCk.PNG" /><figcaption><em>The Value of a state = The reward received in that state + the value of the next state</em></figcaption></figure><p>It is important to realize that we are sampling over many episodes, so instead of setting the value explicitly to Rt + V(St+1), we turn this into an iterative process and just take a small step in the direction of Rt + V(St+1). This brings us to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*4cI1bSntvr1Cp-4dt9WJ0w.png" /></figure><p>But we have a very subtle problem with the function above. Imagine we are updating state V(s1) with current value 0, with Rt = 0. Say V(s2) = 1. If we repeatedly apply the update function to V(s1) then it would blow up to infinity.</p><p>We can fix this problem by offsetting our update by the current value of the state(see below). This brings us to our <em>value update function:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*63dWPn_HyG1oySOI.PNG" /><figcaption><em>This should look a lot like gradient descent. If this function is repeatedly applied, it will make the state values converge to their correct values.</em></figcaption></figure><p>Another explanation of why we must use the difference in values is this; we must take a small step in the direction of the correct value <em>relative to the current value of the state</em>.</p><h4>Theoretical Section Summary</h4><p>In summary, the agent begins by playing several episodes. While it is playing these episodes, sometimes it takes a random action to explore the state space, and other times the agent takes whatever action leads to the state with the highest value. After each episode, we update the value of each state the agent was in during the episode using the value update function, starting from the last state and moving backward to the first state. Eventually, this will lead us to the correct value for each state. If then the agent only takes actions that will lead to the state with the highest reward it will have mastered the game (hopefully).</p><p>Alright, enough with the boring stuff. If all this theory is still a bit fuzzy to you, don’t worry; true learning happens when we apply this stuff. So, without further ado, let’s build an agent that kicks ass in <a href="https://doingengineering21.medium.com/how-to-create-an-ai-that-plays-tick-tac-toe-with-reinforcement-learning-d10e8fbbaa2c">tic tac toe!</a></p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81eb8636f478" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-tabulated-reinforcement-learning-81eb8636f478">What is Tabulated Reinforcement Learning?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create an AI that plays tick tac toe with reinforcement learning]]></title>
            <link>https://medium.com/data-science/how-to-create-an-ai-that-plays-tick-tac-toe-with-reinforcement-learning-d10e8fbbaa2c?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10e8fbbaa2c</guid>
            <category><![CDATA[tic-tac-toe]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Fri, 22 Jan 2021 01:27:28 GMT</pubDate>
            <atom:updated>2021-01-22T20:40:45.865Z</atom:updated>
            <content:encoded><![CDATA[<h4>The AI is unbeatable if it goes first</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*_Xz_OPF7hGa9lJEUwJKPVA.gif" /><figcaption><em>A short video of the AI kicking my ass in tic tac toe! The AI is X, I am O. See how he traps me? </em><strong><em>*Video by author*</em></strong></figcaption></figure><p>In this article, we will create two agents who play each other in tick tac toe until one has reached tic tac toe mastery.</p><p>Writing a program that learns to play tic tac toe is a first step in learning how reinforcement learning works. For this project, I assume you have already been introduced to the theory of tabulated reinforcement learning (which you can learn more about <a href="https://doingengineering21.medium.com/what-is-tabulated-reinforcement-learning-81eb8636f478">here</a>). This includes understanding what the value of a state is and how to find it. I will go in-depth into implementing this theory in code. After you learn how to do this project you are only one neural network away from getting the agent to learn to play video games (and maybe some more useful stuff too)!</p><h3>Implementation:</h3><p>First, we will need a tic tac toe game to be our environment. The implementation posted below should suffice.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0bd0b741f9fd17b84038be52ba93d8/href">https://medium.com/media/6f0bd0b741f9fd17b84038be52ba93d8/href</a></iframe><p>This is a classic implementation of tic tac toe where the spots on the board are represented as numbers in order from 0 to 8, going from top to bottom, left to right.</p><p>I will first show how to encode our states, with each state being a specific configuration of the game board. Then there are two functions that are in our way of tic tac toe autonomy, the get_action function, and the update_values function. Once you are done you should be able to build 2 agents and have them play each other until at least one has mastered the game of tic tac toe.</p><h4>Representing states as numbers</h4><p>As I said we need to store each state the agent encounters in its memory. For tic tac toe, we are defining the current configuration of the game board as the state. In my implementation, the game board is described by a list called ‘spot_placeholders’. The problem is if we store each state, which is a list, ever visited in another list, we will have a huge list full of lists. This is very inefficient. Instead of having a list full of lists, let&#39;s aim to have a list full of integers with each integer representing a unique state.</p><p>To figure out how to represent each state as a number, let’s start off by manually representing states and try to identify a pattern. Note that in the list ‘spot_placeholders’, a 1 means there is an X in that spot and 2 means there is an O in that spot.</p><ul><li><strong>State: [0,0,0,0,0,0,0,0,0]</strong> = 0</li><li><strong>State: [1,0,0,0,0,0,0,0,0]</strong> = 1</li><li><strong>State: [2,0,0,0,0,0,0,0,0]</strong> = 2</li><li><strong>State: [0,1,0,0,0,0,0,0,0]</strong> = 3</li><li><strong>State: [1,1,0,0,0,0,0,0,0]</strong> = 4</li><li><strong>State: [2,1,0,0,0,0,0,0,0]</strong> = 5</li><li><strong>State: [0,2,0,0,0,0,0,0,0]</strong> = 6</li><li><strong>State: [1,2,0,0,0,0,0,0,0]</strong> = 7</li><li><strong>State: [2,2,0,0,0,0,0,0,0]</strong> = 8</li></ul><p>One possible function we could use to enumerate these states is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/0*3Z26SwhJ2GwOwhef.PNG" /><figcaption>This should feel pretty natural if you&#39;re used to working with binary</figcaption></figure><p>Or in code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf263ca0173245da5c20cbd9b8cc8fe/href">https://medium.com/media/3bf263ca0173245da5c20cbd9b8cc8fe/href</a></iframe><p>If this function doesn’t make sense to you, don’t stress out about it. This is very specific to tic tac toe and probably won’t be used much in future projects. If you just copy and paste the code without a full understanding of how it works, not much harm is going to be done to your understanding of RL. Just know that you can improve efficiency by encoding states in some way.</p><h4>Epsilon Greedy</h4><p>The epsilon greedy algorithm is how we will decide which action our agent will take. We want the agent to take random actions at first, but once it starts getting the hang of things we want it to play to win. So what we do is set a variable ε that represents the agent&#39;s chance of taking a random action, and slowly decrease ε over time. The pseudocode is this:</p><ol><li>Initialize ε = 1</li><li>Generate a random number between 0 and 1</li><li>If this random number is &lt; ε, explore the state space (take a random action).</li><li>If this random number is &gt; ε, perform the action that leads to the state with the highest value.</li><li>Decrease ε by a small amount</li></ol><p>ε continues to fall until it reaches some pre-determined value. You can think of ε as the percent chance that the agent will take a random action.</p><h4>The Get Action Function</h4><p>Currently, our get_action function asks the user which spot they would like to go. Since we are making this completely autonomous you are free to clear the get_action function and start from scratch. What we want to do is find out all the possible next states the agent can be in, then find which one of those states has the highest value. We do this by looping through the game board (spot_placeholders) and if a spot is open, we record what the new state would be if the agent went in this free spot. We then look in the agent&#39;s state value table and find the value of this state. If this state has the highest value, we move to the spot that results in this state.</p><p>The pseudocode my implementation of this function is the following;</p><ol><li>Check whose turn it is</li><li>Find all the next possible states that the player can be in.</li><li>Perform ε greedy to either take a random action or be greedy(take the best action).</li><li>If greedy, loop through the next possible states and find the state with the highest value.</li><li>Try to perform this action, but if the agent doesn’t have any of these states in its table then do a random action.</li></ol><p>The code for my implementation of this function can be found below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/912382b5fbfead8fdf0ebebb7f4d863b/href">https://medium.com/media/912382b5fbfead8fdf0ebebb7f4d863b/href</a></iframe><p>Note that I also added the epsilon attribute to the player class for the ε greedy strategy.</p><h4>The Update Values Function</h4><p>Currently, we can make two agents play each other, but these two agents have no memory whatsoever. It’s like every game they play is their first-ever game of tic tac toe. So, let’s fix that.</p><p>What we do is keep a list of all the states visited in an episode. At the end of the episode, we need to call a function that applies the value update function to every state in this list for each agent. Notice that we only receive a reward at the last state of the episode. Therefore, we can just set the value of the last state to the reward. The pseudocode to my implementation is the following:</p><ol><li>Set the value of the last state equal to either 1 or -1 (reward if game won or punishment if game lost)</li><li>Append any new, previously undiscovered states to the player&#39;s memory</li><li>Apply the update function starting from the second to last state and moving towards the first state</li></ol><p>The code for my implementation is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5abb09e89ded0ca308b7af830342eaf/href">https://medium.com/media/c5abb09e89ded0ca308b7af830342eaf/href</a></iframe><p>I added a call to the update function in the play game function here too.</p><h4>Putting it all together</h4><p>We are now able to get two agents to play each other and become tic tac toe pros all on their own. You can find the code for my finished project below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39f2ad6633b84cd826d7aed32c44ca39/href">https://medium.com/media/39f2ad6633b84cd826d7aed32c44ca39/href</a></iframe><p>I added a test function so that you can play against the computer. You will find that if you go first the agent doesn’t play very well at all, this is due to the game of tic tac toe being very bias towards who goes first (which messes up training). Adjusting training time, the size of rewards, and other hyperparameters may help the agent play better when it goes second (you could try to reward the player who goes second for a cat-game, instead of punishing them).</p><h3>Project Summary</h3><p>In summary, we are making an agent play the game of tic tac toe thousands of times and recording what happens in every state of the game. We then assign a value to each state and correct this value using the value update function. When the agent is trying to win, he will always move to the state with the highest value. We call this tabulated RL since we keep all the states and their values in a table.</p><p>But what if this was a 4X4 or 5X5 or even a 10X10 game of tic tac toe? The number of total possible states grows exponentially as the game board grows. This means that our value table will eventually be way too large to be practical! If only there was a way to just approximate the value of each state.</p><blockquote>If only <em>there existed a function that</em> approximates the value of each possible action, given the current input…</blockquote><p>Well, there is such a function and we find it using a neural network. This is the topic of deep reinforcement learning, which I will write an article on soon and post the link here.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10e8fbbaa2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-create-an-ai-that-plays-tick-tac-toe-with-reinforcement-learning-d10e8fbbaa2c">How to create an AI that plays tick tac toe with reinforcement learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to classify handwritten digits in python]]></title>
            <link>https://medium.com/data-science/how-to-classify-handwritten-digits-in-python-7706b1ab93a3?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/7706b1ab93a3</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Wed, 20 Jan 2021 13:44:49 GMT</pubDate>
            <atom:updated>2021-01-22T20:40:13.098Z</atom:updated>
            <content:encoded><![CDATA[<h4>Without the help of any machine learning libraries</h4><p>If you have read the previous articles in this series (links at bottom of page), you should have built a DNN class completely from base principles. Let’s see if we can use this class to create a neural network that’s able to read handwritten digits.</p><p>This is a classic example of something that is easy for us humans to do, but it is incredibly difficult to write a program that accomplishes the same task. In the case of us humans classifying pictures, let’s think about what is happening. For a human looking at an image, the brain is receiving input in the form of photons and classifying the image based on this input.</p><p>Based on this we can say that there must be some relationship between the photons hitting our eye and the content of the picture. Obviously, right? Of course, what the picture looks like has something to do with what the picture is of. But, modeling this mathematically requires this proposition;</p><blockquote><em>There exists some mathematical function that can tell us what is in the picture, based on the input (photons) we receive from the picture.</em></blockquote><p>We will be finding this incredibly complicated function easily, using a neural network.</p><h4>Getting and cleaning our data</h4><p>In the spirit of advancing AI, the Modified National Institute of Standards and Technology (MNIST) has put together 10’s of thousands of pictures of handwritten digits, each with a label. This data can be downloaded <a href="https://www.kaggle.com/oddrationale/mnist-in-csv/data">here</a>. Below is an example of one of these digits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*kKxxK1YXSyWMEBtS.PNG" /><figcaption><em>This picture is labeled as a 3. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Now, in the case of us humans, we receive input as photons entering our eyes. Similarly (sort of), to a computer this picture is just a matrix of pixel values. These pixel values range from 0 to 255 (since the image is black and white), as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*UO6CE7ON9SWzlDDW.PNG" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>These pictures are 28X28, with 784-pixel values. Our goal is to map these 784-pixel values to the number that is written. So, let’s get started. Let’s first look at the data. You should have downloaded a zip folder from the Kaggle link I provided above. After you unzip the folder you will see a mnist_test and mnist_train CSV. For right now we will only be focused on the mnist_train CSV. Below I use pandas to open the file, then show the contents of the file.</p><pre><strong>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt</strong></pre><pre><strong>data = pd.read_csv(‘mnist_train.csv’)</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*KW9X00vr27JhJgkn.PNG" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>As you can see, the first column of this data is the labels (the number that the image represents), and the rest are the pixel values for the image (totaling 785 columns). Each row is an individual image. Using pandas iloc function we can separate the inputs from the labels. Also, we ensure that the input is normalized between 0 and 1.</p><pre><strong>labels = np.array(data.iloc[:,0])<br>x_train = np.array(data.iloc[:,1:])/255 <br># We divide by 255 so that all inputs are between 0 and 1</strong></pre><p>Our next step may seem odd, but it is essential. Right now each label is just one number or one dimensional. This means the neural network must output the correct number between 0 and 9. We can make the classification task easier for our neural network by increasing the dimensions of the output to 10 dimensions, one for each number. For example, we will change the label ‘0’ so that it is ‘[1,0,0,0,0,0,0,0,0,0], ‘1’ = ‘[0,1,0,0,0,0,0,0,0,0] and so on. This is called ‘one-hot-encoding’, and I do this for our labels below.</p><pre><strong>encoded_labels = []<br>for i in range(len(labels)):<br>  naked = [0,0,0,0,0,0,0,0,0,0]<br>  naked[labels[i]] = 1<br>  encoded_labels.append(naked)</strong></pre><p>Now we can use matplotlib to check out what these images actually look like.</p><pre><strong># Take a look at what the images look like<br>random_index = np.random.randint(0,40000)<br>img = x_train[random_index].reshape(28,28)<br>plt.imshow(img, cmap = “gray”)</strong></pre><p>As you can see, our neural network really has its work cut out for it with some of these pictures…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/0*vEoDxSjoBbo071C_.PNG" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Creating our Neural Network and training</h4><p>We will be using the DNN class we created in the article prior to this one (found <a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">here</a>). Each image has 784 inputs and 10 outputs, I will choose one hidden layer with 1250 neurons. Therefore, our layers would be [784,1250,10]. Inside a for loop, we simply generate a random index, then run the train function on the data and label that corresponds to this index. I also print some useful information every 1000 steps, see below:</p><pre><strong>model = DNN([784,1250,10])</strong></pre><pre><strong>from collections import deque<br>error = deque(maxlen = 1000) <br>&quot;&quot;&quot;A deque is just a list that stays at 1000 units long (last item gets deleted when a new item gets added when at length = 1000)&quot;&quot;&quot;</strong></pre><pre><strong>for n in range(30000):<br>  index = np.random.randint(0,59998)<br>  error.append(model.train(x_train[index], encoded_labels[index]))<br>  if n%1000 == 0:<br>    print(“\nStep: “,n)<br>    print(“Average Error: “, sum(error)/1000)<br>    plt.imshow(x_train[index].reshape(28,28), cmap = “gray”)<br>    plt.show()<br>    print(“Prediction: “, np.argmax(model.predict(x_train[index])))</strong></pre><h4>Results and testing</h4><p>After just 5 minutes on my computer, the NN is correctly identifying most of the digits. After 10 minutes the neural network seems as if it has fully trained, reaching an average error of around .2. It is important not to over-train the model, this causes the NN to just memorize images which would make it really bad at predicting things it has never seen.</p><p>Let’s use that mnist_test.csv file we downloaded to see how well our neural network performs on data it has never seen before. Below I call the predict function on each picture in the mnist_test file, then check if the prediction was correct. I then calculate the percent that this NN predicted correctly.</p><pre><strong>test_data = pd.read_csv(‘mnist_test.csv’)<br>test_labels = np.array(test_data.iloc[:,0])<br>x_test = np.array(test_data.iloc[:,1:])/255</strong></pre><pre><strong>correct = 0</strong></pre><pre><strong>for i in range(len(test_data)):<br>  prediction = np.argmax(model.predict(x_test[i]))<br>  if prediction == test_labels[i]:<br>    correct +=1</strong></pre><pre><strong>percent_correct = correct/len(test_data) * 100<br>print(percent_correct,’%’)</strong></pre><p>Below is the final code for this project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1dc80a365ec51e4e8506b65c63e664a/href">https://medium.com/media/d1dc80a365ec51e4e8506b65c63e664a/href</a></iframe><p>I end up getting a 93.5%. Feel free to try to train longer, increase the number of layers and/or neurons, change the activation function or loss function, and change the learning rate to see if this can be improved. Although 93.5% is very exciting, we can actually do <em>much</em> better. We can make the neural network able to identify unique features within the picture to help it identify the image. This is the idea behind <em>convolutional neural networks</em>, which I will explain in detail in a future article.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><blockquote>This is a continuation of a series of articles that give an intuitive explanation of neural networks from the ground up. For the other articles see the links below:</blockquote><blockquote><a href="https://towardsdatascience.com/what-is-an-artificial-neural-network-b508c821ace8">Part 1: What is an artificial neural network</a></blockquote><blockquote><a href="https://towardsdatascience.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">Part 2: How to train a neural network from scratch</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">Part 3: Full implementation of gradient descent</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">Part 4: Implementation of gradient descent (an example)</a></blockquote><blockquote>Part 5: How to classify handwritten digits in python</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7706b1ab93a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">How to classify handwritten digits in python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Gradient Descent — Example]]></title>
            <link>https://medium.com/data-science/implementing-gradient-descent-example-102b4454ea67?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/102b4454ea67</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 15:57:48 GMT</pubDate>
            <atom:updated>2021-01-22T20:39:38.468Z</atom:updated>
            <content:encoded><![CDATA[<h3>Implementation of Gradient Descent</h3><h4>A fundamental example of the implementation of gradient descent</h4><p>We have derived an algorithm on how to implement gradient descent <a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">here</a>, but there are a lot of nuances when implementing this algorithm in code. If you try to tackle this algorithm with a huge project right out the gate, you will find that it is very difficult to keep track of the shapes of all your matrices. Because of this, we will start very small with the same architecture we used in the derivation.</p><p>First, let’s just focus on getting a general form of this algorithm working. After we have something that works, we can clean it up and make it useable. To test our algorithm, we are going to try to map one input to one output.</p><h4>Initializing our Neural Network</h4><p>Our first step is to create the weights for our neural network. We can use a simple for loop to do this. First, we specify the layers that our neural network will have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*AYulsGbhy6V4LGUf.png" /><figcaption><em>This is the neural network we will be creating. </em>*Image by author*</figcaption></figure><p>We can specify the layers to this neural network by saying; layers = [2,3,3,2]. It is important to note that we do not include the bias as part of each layer. We will include them later.</p><p>Before we create our for loop to generate the weights, take a look at the shape of each layer&#39;s weights and how they relate to the layer sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/0*1eN39flVGHeXl-ce.PNG" /><figcaption><em>Only pay attention to each matrix shape here. </em>*Image by author*</figcaption></figure><p>We can see that our weight shapes are; (neurons in the next layer, neurons in the current layer + 1). Using this we can make a for loop that generates the weights for the entire network for us. These weights are initialized as random numbers to start.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a19c09bef217f49e2080c3d8c832a2/href">https://medium.com/media/56a19c09bef217f49e2080c3d8c832a2/href</a></iframe><h4>Forward Phase</h4><p>Now that we have our weights, we need to perform our forward phase and collect all the layer&#39;s inputs. For this example, we will be using 2 random inputs <em>that are between 0 and 1</em>. It is important that they are between 0 and 1, so we are not dealing with huge numbers in our computation (more on this later).</p><p>First, we define the sigmoid function, since this is the activation function we will be using. Now, if we simply do the dot product of the weights and our input, we will get an error. This is because we must add our bias term onto our input. So, we first add the bias onto our input then do the dot product between the weights and input, activate this weighted sum, and finally record the output as the input for our next layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4edfeea12ea4b8ea332bdd281089e3db/href">https://medium.com/media/4edfeea12ea4b8ea332bdd281089e3db/href</a></iframe><p>Alright, let’s take a look at the list ‘x_s’ after we run the above code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*o5mB4RYdTpwIECxf.PNG" /><figcaption><em>The last list is our final output of the neural network. This is what we compare to the expected output to find our error. </em>*Image by author*</figcaption></figure><p>Everything checks out. So, our next step is to update our weights so our final output matches our expected output. For this example, our expected output will again be two made up numbers between 0 and 1.</p><h4>Backward Phase</h4><p>If you didn’t go through the page where we <a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">derived our gradient descent algorithm</a>, or you didn’t understand it very well, the practical information is this: finding the gradients for all of our layers can be done in 3 steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/0*-ORzx9aOwZ7aVg8-.png" /><figcaption><em>We would then use these gradients to update our weights. Remember the circle with the x through it means we multiply the rows. </em>*Image by author*</figcaption></figure><p>Our first step is to initialize psi. Each term of psi is just ∂E/∂Xi * ∂Xi/∂Zi. Using the neat fact that the derivative of the sigmoid function = σ(x)(1-σ(x)), and the derivative of our error = -2(y_truei — Xi), we find this partial derivative easily. So, to initialize psi we just loop through each y_true value and append the ∂E/∂Xi * ∂Xi/∂Zi associated with this y_true value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d1b5cb0d52a45f284785876a6749f4a/href">https://medium.com/media/6d1b5cb0d52a45f284785876a6749f4a/href</a></iframe><p>Now here is the first tricky detail. Right now, the shape of psi is (2,). For our algorithm to work, we need psi to be the same shape as it is in our derived algorithm, which is (2,1). This is a small, slightly frustrating, detail; but an easy fix.</p><pre><strong>psi = np.reshape(psi,(psi.shape[0],1))</strong></pre><p>Easy peasy. Now that we have psi initialized, we can move on to step 2, which is to find the gradients for the last layer. This is just psi * the second to last input. Or;</p><pre><strong>gradients = []<br>gradients.append(psi*x_s[-2])</strong></pre><p>Numpy handles the row-wise multiplication for us. Now we are ready to move on to step 3, which is a little tricky. We want to start at the second to last layer since we just found the gradients to the last layer. Moving backward, we then update psi and find the layers gradient until we reach the last layer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b9062cd5b806df29319a99c572850a9/href">https://medium.com/media/0b9062cd5b806df29319a99c572850a9/href</a></iframe><p>We first define the weights and inputs we are dealing with in the term we use to update psi. This is just the layers weights and inputs excluding the bias since none of the weights we are trying to find affect the bias at all (they are always = 1 no matter what). We then get this term into the correct shape by transposing it. Then, we update psi and reshape it just as we did before. Finally, we append our gradient.</p><p>After we run the for loop above, we should end up with the following for our gradient tensor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/0*tiUcWORCn7IMDSO_.PNG" /><figcaption>*Image by author*</figcaption></figure><p>Note that the first gradient is the same size as the weights of the last layer, the second gradient is the same size as the second to last layers gradient, and so on. This is a good sanity check so that we know everything is working properly. We now update our weights with the following fancy indexing:</p><pre><strong>for i in range(len(gradients)):<br>  weights[i] -= .001*gradients[-(i+1)]</strong></pre><p>And that it! We have just updated our weights one time. Now, we can run the above code in a for loop to update our weights say 2500 times, and see if it works.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23296d3e08d09c5bc03c4ba4195839cf/href">https://medium.com/media/23296d3e08d09c5bc03c4ba4195839cf/href</a></iframe><p>Now the moment of truth. Let’s compare our final output to our y_true values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*ZEJkKekiD5g1FP0A.PNG" /><figcaption>*Image by author*</figcaption></figure><p>As you can see our output matches our y_true values exactly. Now, before we clean this code up and throw it into a class let’s try to scale it. Let’s see if this still works will 1000 neurons in each hidden layer (foreshadowing, the weighted sum of 1000 neurons could be a very large number!). Go ahead and try it yourself.</p><p>Now, let me show you the output I get after 10,000 training iterations when I change the layers to [2,1000,1000,2];</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*fBNA4De34oyWz-Cs.PNG" /><figcaption>*Image by author*</figcaption></figure><p>Well, as you can see… It doesn’t work at all! Why is this?!</p><p>To diagnose this, let’s look at our gradients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*4WcGVAculaL_XPQ1.PNG" /><figcaption>*Image by author*</figcaption></figure><p>Well, there’s the problem… Try to think of why our gradients would all be 0. I’ll give you a hint, it has to do with our activation function and its derivative.</p><p>Let’s just look at this last gradient. ∂E/∂W = ∂E/∂X[-1] * ∂X[-1]/∂Z * ∂Z/∂W. The PD (partial derivative) of the error w.r.t (with respect to) the last output, times the PD of the last input w.r.t the last weighted sum, times the PD of the last weighted sum w.r.t the weights.</p><p>If our gradient is 0, at least one of these must be 0. Remember that ∂X[-1]/∂Z is just the derivative of our activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*xmoVLP3U_sX7XJa6.png" /><figcaption>What is the slope of this for very high or low values of x. *Image by author*</figcaption></figure><p>What would be the derivative of this function if x was really large or really small? It would be 0! So, let’s change our sigmoid function so it is more linear. We can do this by multiplying x by a small constant c (.01 works best here). This is kind of a ‘slap a band-aid on it’ solution, a better solution would be to switch to something called the ‘leaky Relu’ activation function. You can if you want to, but I am just going to multiply x by .01 in our sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*fOGVpFKHCfplN5Ql.png" /><figcaption><em>Notice the stretched-out x-axis. </em>*Image by author*</figcaption></figure><p>Now, all we have to do is add a 0.01 into our sigmoid function. Technically, our new derivative would be 0.01 * σ(x)(1-σ(x)), but we don’t have to worry about this since it just gets absorbed into the learning rate. Besides, the whole point of doing this was to scale <em>up</em> our derivative. The new output and only change to the code are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/0*jr6_w9OPl994eNZm.PNG" /><figcaption><em>The only change to code is circled in blue. </em>*Image by author*</figcaption></figure><p>As you can see, we have solved our problem! This is also why we must make our inputs between 0 and 1. If our weighted sum is very large then our derivative will be close to 0. To finish up we can clean this up a little bit and throw it into a class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be0316999d77e5d706d3f49764355184/href">https://medium.com/media/be0316999d77e5d706d3f49764355184/href</a></iframe><p>Now, we can finally do something fun with this! With this algorithm, we will get a program to identify handwritten digits. This project is a classic, but you never see anyone doing it from scratch (maybe for a good reason, but we are learning)! You can find this project <a href="https://doingengineering21.medium.com/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">here</a>.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><blockquote>This is a continuation of a series of articles that give an intuitive explanation of neural networks from the ground up. For the other articles see the links below:</blockquote><blockquote><a href="https://towardsdatascience.com/what-is-an-artificial-neural-network-b508c821ace8">Part 1: What is an artificial neural network</a></blockquote><blockquote><a href="https://towardsdatascience.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">Part 2: How to train a neural network from scratch</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">Part 3: Full implementation of gradient descent</a></blockquote><blockquote>Part 4: Implementation of gradient descent (an example)</blockquote><blockquote><a href="https://doingengineering21.medium.com/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">Part 5: How to classify handwritten digits in python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102b4454ea67" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/implementing-gradient-descent-example-102b4454ea67">Implementing Gradient Descent — Example</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Full implementation of Gradient Descent — no holding back]]></title>
            <link>https://medium.com/data-science/full-implementation-of-gradient-descent-no-holding-back-86e688f36064?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/86e688f36064</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Tue, 19 Jan 2021 01:10:44 GMT</pubDate>
            <atom:updated>2021-01-22T20:39:18.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Full implementation of Gradient Descent</h3><h4>Deep dive into the mathematics of the gradient descent algorithm.</h4><p>This post derives the algorithm for implementing gradient descent. It is messy, ugly, and tedious! It is a fun exercise deriving it yourself, but in the end, it’s just identifying patterns. Don’t let this page make your head explode and make you give up on AI! Just knowing how to use the algorithm is most important (even then it can be argued that you can just use Keras), but why not try it yourself and have some fun! I include the derivation here just because I know I would have loved to see it when I was learning AI.</p><p>We now know that we must find the gradient of the error function with respect to each weight to minimize our error (If you have no idea what I just said, learn/review how to train a neural network <a href="https://doingengineering21.medium.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">here</a>). That’s all fine, but how do we actually do this in code. You can imagine how difficult it would be to find the gradient if we have a neural network with 5,6 or more layers each with hundreds or thousands of neurons.</p><blockquote>We know <em>what</em> to find (the gradient), now we just need to figure out <em>how</em> to find it.</blockquote><p>We could just use the definition of the derivative. Go through each weight and increase it by a tiny amount, then divide the resulting change in the error by this tiny amount. This will give us ∂E/∂W for this particular weight. Now if we did this for all of our weights, we would have the gradient.</p><p>But to put things in perspective, a neural network I trained to play atari games had 1,685,667 weights and I had to update them about 10 million times. Using the definition of the derivative would just take way too long for a network like this.</p><p>Since neural networks have very high repetition, it seems that we could find an algorithm that would find the gradient for us in an efficient way. To try to create this algorithm, we will first write out, by hand, the forward and update phase of a relatively small, but deep, neural network. We will then look for patterns in this process to try to simplify it as much as possible.</p><p>This is the neural network we will be using to derive our gradient descent algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*kOEPE9N4gaxTpMrbj_uy9g.png" /><figcaption><em>This time we are implementing the bias. Note that the above implementation is the exact same as just adding a bias onto each neuron&#39;s weighted sum, as long as we keep our bias ‘input’ at 1. The bias is blue, and anything associated with the bias will be blue on this page. </em><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Forward phase</h4><p>First off, it is very important to remember that we draw a neural network as this computational graph in order to help us visualize what is happening. But, if we are going to find our gradient descent algorithm we will need to write out the computations done. Well, we have a lot of parameters here! The huge amount of parameters we have really made for ugly indexing!</p><p>Let me write out all the parameters we have in this neural network. Then let you in on my convention for indexing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*D0COx6m3cHs2enCbauBEug.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>Xbar above is a list of the <em>‘inputs’</em> for each layer. Notice that the size of each of the lists in Xbar corresponds to the number of neurons in each layer. Xbar[0] is the initial input data with a bias, Xbar[1] is the activated weighted sum of X[0] with a concatenated bias, Xbar[2] is the activated weighted sum of X[1] with a concatenated bias, and so on.</p><p>Wbar is a list of all the weights that connect each layer. Each of these lists should have size:</p><p>(# of neurons in the next layer excluding bias, # of neurons in the current layer including bias).</p><p>For example, the first list of weights has 3 rows since there are 3 neurons in the next layer (excluding the bias). This list has 3 columns because there are 2 inputs and 1 bias.</p><p>Now, the top left index tells what layer the particular element is in. The top right index tells what input neuron in the layer we are talking about, the bottom right index tells what input we are going to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*j_bANH-cfVABcO8qoWptqA.png" /><figcaption><em>X is the input to the layer, w is the weights of the layer, z is the weighted sum before being passed through the activation function. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Now that we are on the same page as far as notation. Here is the forward phase of the neural network. Just going from left to right, top to bottom, writing out the computations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*kl49eb6lBOxOgTDtWIadxQ.png" /><figcaption><em>a(z) is our activation function applied to z. Take a step back and just look at what is happening at a high level. Don’t let your head explode trying to simultaneously be conscious of every detail! </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>The top row of computations brings us from our first layer of inputs to our second layer of inputs. The second row brings us from our second layer of inputs to the third layer of inputs, and so on until we reach an output.</p><h4>Backward phase</h4><p>Ok, now let me write out what we are trying to find;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*6yylr9lyolhHqHRnl41TDg.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>We are going to try to find enough of the third and second list of derivatives to identify a pattern. Using the chain rule, and a lot of staring at the problem, we can show that these derivatives are equal to the following;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*q9epVm0uwDrpJOgbd-T1sQ.png" /><figcaption><em>I highlighted any pattern that I recognized, this will be useful in simplifying. The second gradient matrix is only partially complete. We only need enough to identify a pattern. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>If the above photo is slightly blurry, I suggest you download a copy of it and study it for a while. I first just compute the derivatives, then I highlight any similarities within the matrices. Pattern identification is the name of the game.</p><p>This can be tough deriving yourself. Take a look back at the photo of the forward phase frequently. If you start at the error, then work yourself back to the weight you are trying to find while using the chain rule, you’ll find it’s simple but very tedious.</p><p>Now, we are trying to find a simpler way to express the above equations. If you remember your linear algebra and kind of work backward, you can see that the above equations can be simplified to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*N93xc6fCck4U3EWLOb27mg.png" /><figcaption><em>That circle with the X inside of it means that we are multiplying the rows. The dot between matrices means we are applying the dot product. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Look how beautiful! You can notice that everything that is red, is the same as everything highlighted in the row above it. This means we can start at the last layer, initialize a term, call it Ψ, to be what is in green. Then as we move back to previous layers, we can update Ψ with what is green in that layer (whatever is in red is the current value of Ψ). Now to find the gradient for that layer we just multiply Ψ by ∂Z/∂w row-wise. This is a lot prettier when you plug in values, below I assume the mean squared error function and the sigmoid activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*ugzlSqPdO7FkNT1MkGDYYw.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>Now, we wrap up the update into a very simple for loop:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*cyePA_7iRHeXGM37eDvQBA.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Summary</h4><p>Ok, I know what you’re thinking. What in tarnation just happened!? All I did was identify patterns! Nothing more complicated than the chain rule was used, I just used a LOT of it. I would not blame you if you just believed my result, instead of deriving it yourself. In practice, we will be using Keras for implementation anyway, but now that you know how to do it yourself you don’t have to feel guilty doing so.</p><p>As always, we don’t truly understand this yet! We won’t understand it until we apply it. I go through a simple implementation in python <a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">here</a>, in this link I also build a useful python class that we will later use to identify handwritten digits.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><blockquote>This is a continuation of a series of articles that give an intuitive explanation of neural networks from the ground up. For the other articles see the links below:</blockquote><blockquote><a href="https://towardsdatascience.com/what-is-an-artificial-neural-network-b508c821ace8">Part 1: What is an artificial neural network</a></blockquote><blockquote><a href="https://towardsdatascience.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">Part 2: How to train a neural network from scratch</a></blockquote><blockquote>Part 3: Full implementation of gradient descent</blockquote><blockquote><a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">Part 4: Implementation of gradient descent (an example)</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">Part 5: How to classify handwritten digits in python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86e688f36064" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">Full implementation of Gradient Descent — no holding back</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to train a neural network from scratch]]></title>
            <link>https://medium.com/data-science/how-to-train-a-neural-network-from-scratch-952bbcdae729?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/952bbcdae729</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Mon, 18 Jan 2021 15:52:09 GMT</pubDate>
            <atom:updated>2021-01-22T20:38:46.316Z</atom:updated>
            <content:encoded><![CDATA[<h4>The intuition behind finding the weights of a neural network, with an example.</h4><p>In this article, I will continue our discussion on artificial neural networks, and give an example of a very simple neural network written in python. The purpose of this series of articles I am writing is to give a full explanation of ANN’s from the ground up, with no hiding behind special libraries. Tensorflow is great for prototyping and production, but when it comes to education the only way to learn is to get a pencil and paper and get dirty in math.</p><p>In the previous article, I went over the inspiration behind an ANN and how to model the human brain mathematically (you can find this article <a href="https://doingengineering21.medium.com/what-is-an-artificial-neural-network-b508c821ace8">here</a>). Our next step is to find the correct weights for our model.</p><h4>Mapping inputs to outputs</h4><p>Say we have a list of inputs and their outputs. These could be anything, stock features and price, property features and sale price, student behaviors and average test scores, they could be whatever; but let’s keep things general and say we have some inputs and outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*x3PE4SrKj5K6zKutiyGwxg.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>Our goal is to predict the output to that last input. To do this, we must find the relationship (function) that maps these inputs to their outputs. Now for the sake of learning, I made this relationship linear. This tells us that we can use the identity activation function instead of the sigmoid, and there is only 1 layer (the output layer).</p><p>If you don’t see why a linear relationship only gives us one layer with the identity activation function; just bear with me. Let me give you a visual of our neural network and show you the function it represents before I explain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*kiO9yw8grfI1hPdLInr4eg.png" /><figcaption><em>Notice how we can clean things up by applying the dot product. It is also much more efficient in code. Remember that this NN would also have a bias, we can give in a bias by manually inputting a 1 as one of the inputs then applying a weight to this 1. For now, ignore the bias. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>If we had more layers that used the identity function then we could always simplify it down to the above equation. Try it yourself by adding a middle layer with 2 neurons each with the identity activation function, then write the equation that corresponds to the network and simplify it.</p><p>You could easily solve the weights here using many different methods. After all, it is just a system of linear equations. But, let’s try to solve this in the general case that we do NOT have a linear relationship.</p><h4>Measuring how wrong we are, using an error function</h4><p>So, let’s have some fun. How could we solve for the weights without treating this as a system of linear equations? Well, you have to start somewhere, so let’s first just throw a blind guess at what they could be. I’m going to guess that W1 = .2, W2 = 1.4, and W3 = 30.</p><p>Now let’s see how good our guess was and test it on one of the inputs (using the same data in the table above).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*B8ofnh2SixRmNoxFNmVDqA.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>Recall, the correct output (or expected output) should be 13.5 according to our data; we are way off! Let’s actually quantify how wrong we are by using an <em>error function</em>. When the NN outputs the correct value we want the error to be 0. Let’s start with; Error = correct output-output of our ANN (ex; 0 = 13.5–13.5 if our weights were correct).</p><p>We are almost there. Think practically, our error is something we want to minimize. Well, what’s the minimum of our current error function? There is no minimum! As it is, we can have -∞ error. We fix this by squaring the function, so it can not be negative, Error = (correct output-output of our ANN)². Notice the shape of this error function is just a parabola centered at 0. Now, this is the error in a single output neuron. If we have multiple outputs, then we just take the average error in all of them. So, we have;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*xGQzgbS3AFmTMgmhY9-sig.png" /><figcaption><em>This is called the mean squared error function. This is the general case where there are N outputs. The total error would be the average error of each output. In our example N = 1. </em><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Minimizing how wrong we are (minimizing our error)</h4><p>When you change a weight by a very small amount (∂W), you get and change in error (∂E). So, if we wanted to find how much a change in this weight affects the error, we can take the ratio of the 2, ∂E/∂W. This can be recognized as the partial derivative of the error function with respect to this weight, or how a small change in this weight changes the error.</p><p>How does this help us? Well, if you are good at calculus you may know where this is headed. But, if you are not, take a look at the graph below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*bp0k5zIUD3imajPxKtJDDg.png" /><figcaption><em>Recall that a derivative is just a slope. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>This is just an arbitrary function. Take any point on this line, and put your finger on it. Now, say out loud whether the slope at this point is either positive or negative. If the slope is positive, move your finger along the line a little bit in the +X direction. If it is negative, move it in the -X direction. If the slope is 0…pick another point. Do this for a couple of points. Notice anything?</p><p>No matter what, you will always be moving your finger towards a higher value on the line.</p><blockquote>T<em>he direction of the derivative is always the direction of ascent</em>.</blockquote><p>If the derivative is negative, a decrease in X will increase Y. If the derivative is positive, an increase in X will increase Y.</p><p>Back to our NN with ∂E/∂W. We want to decrease our error, so we want to move our weight in the direction of descent. We can do this by computing this derivative, then negating it. Now, we move our weight a tiny step in the direction of this negated derivative. Or;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*ncj3wWaXq1zb5hBPXhuwog.png" /><figcaption><em>α ensures we take a very small step in this direction. It is called the learning rate and is another hyperparameter. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>This is just for one weight in our network. We can write this expression in matrix form, remembering that the gradient is just a vector containing all the derivatives ∂E/∂Wi. The matrix form is shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*vQRGtIPoIoSxDImwqKAa0w.png" /><figcaption><em>Remember the gradient is just the direction of the steepest ascent. We want to descend so we go in the direction of the negative gradient. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Now the above equation can be repeatedly applied to the weights until they converge to the correct values. Finding this gradient is a bit of a pain if our network is larger, but it is always possible as long as we use differentiable activation functions. The repeated application of this equation is called the <em>gradient descent </em>algorithm.</p><h4>Quick Summary</h4><p>Let me summarize the past 2 pages. We have data and some outputs. We know there is some relationship between this data and the outputs. Inspired by the human brain, we can construct an artificial neural network. We initialize this neural network with random weights, then start testing it on the data and outputs we have. As we are testing, we quantify how wrong our network is by using the error function, then minimize this error function using gradient descent.</p><h3>Example</h3><p>Now that we have an idea about the theory behind training a neural network, we need to focus on how to implement this theory. Earlier, I gave an example of some inputs and outputs and laid out the game plan for finding their relationship.</p><p>It’s tough, almost impossible, to find the correct weights manually (without treating this as a system of linear equations). But by using the gradient descent algorithm and the error function that we derived earlier, we will do this the right way and find these weights with code.</p><h4>Finding the gradient of our function</h4><p>Right now, this is our neural network from input to error. Remember, for learning sake we are ignoring the bias. We will add it in our next project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*FH5Sbt15tLxqltwX3L5XDg.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><p>We want to find the derivative of the error with respect to each weight (how much a small change in each weight changes the error), then move that weight a tiny amount in the direction of the negated derivative (or the direction of steepest descent). We can do this using the chain rule as shown below;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*fkWqwjd0_VAS1UpCiDlIaQ.png" /><figcaption><em>The chain rule looks scary, but it is simple division. Notice that you can cancel the ∂Z’s just like if you were dealing with fractions (you basically are). Another way of thinking about it is; if you want to find how much a change in the weight affects the error, you first need to find how much it affects Z, then you need to find how much Z affects the error. Also, that predator 3 dot symbol means “therefore”. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>That’s it, we found our gradient! Now we just need to iteratively apply the gradient descent update to make our weights converge. Here is the code to do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/181/1*vQRGtIPoIoSxDImwqKAa0w.png" /><figcaption><em>A reminder of gradient descent. </em><strong><em>*Image by author*</em></strong></figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1033f401e66ece1b5284269cb0d66ffe/href">https://medium.com/media/1033f401e66ece1b5284269cb0d66ffe/href</a></iframe><p>Updating the weights 2000 times is usually enough, if you guessed ridiculous weights that were in the tens of thousands or higher, it may take more. Take a look at the weights you ended up with after running this code, did you get [.5,.9,1.2]? Well, that’s the exact weights I used to generate this data.</p><p>Isn’t this incredible?! By using calculus and data we can approximate the relationship between any 2 related things! You might say, “well this is an easy example, I could have solved this in 2 minutes treating it as a system of linear equations”. Well, you’re exactly right. But what if there were 5 or 6 layers each with 1000 + neurons that each used the sigmoid activation function. Solving by hand in any way is out the window. What we need is a systematic algorithm that can find the gradient for the weights in our network, which I go over <a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">here</a>.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><blockquote>This is a continuation of a series of articles that give an intuitive explanation of neural networks from the ground up. For the other articles see the links below:</blockquote><blockquote><a href="https://towardsdatascience.com/what-is-an-artificial-neural-network-b508c821ace8">Part 1: What is an artificial neural network</a></blockquote><blockquote>Part 2: How to train a neural network from scratch</blockquote><blockquote><a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">Part 3: Full implementation of gradient descent</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">Part 4: Implementation of gradient descent (an example)</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">Part 5: How to classify handwritten digits in python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=952bbcdae729" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-train-a-neural-network-from-scratch-952bbcdae729">How to train a neural network from scratch</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is an artificial neural network?]]></title>
            <link>https://medium.com/data-science/what-is-an-artificial-neural-network-b508c821ace8?source=rss-e7cec11c7aba------2</link>
            <guid isPermaLink="false">https://medium.com/p/b508c821ace8</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Drew Parmelee]]></dc:creator>
            <pubDate>Sun, 17 Jan 2021 15:08:29 GMT</pubDate>
            <atom:updated>2021-01-22T20:38:24.512Z</atom:updated>
            <content:encoded><![CDATA[<h3>What Is an Artificial Neural Network?</h3><h4>An intuitive introduction to artificial neural networks.</h4><p>Neural networks have received a lot of hype in recent years, and for good reason. With a basic understanding of this deep learning theory, we can create technology that solves complex problems with human, and sometimes superhuman, capabilities. Whether it be advanced signal processing, object detection, intelligent decision making, or time series analysis, neural networks are a great way to add intelligence to your projects. Before I begin explaining the details of a neural network, let me tell a short story that should give some inspiration as to why artificial neural networks were created in the first place. If you just want to jump straight into the details of neural networks then skip to the “Modeling the biological neuron” section.</p><h4>The tale of the investor, the mathematician, and the neuroscientist</h4><p>Say there is a real estate investor that has data on thousands of properties around the world. This data includes each property&#39;s location, location crime rate, property square foot, and population. He also has the price that each property was sold for. He wants to find the relationship between the data for each property and the price the property was sold for. If he finds this relationship, he can apply it to a new house that isn’t in his data and find out the price it will sell at. Then he can easily find houses that are going for cheaper than what he can resell them for.</p><p>Okay, so that’s the aspirations of a real estate investor. Unfortunately for him, he was never any good at math. So, with riches on his mind, he finds a mathematician to solve his problem. Let’s look at this problem from the mathematician’s perspective.</p><p>To the mathematician, we have a series of inputs and outputs of some function. The inputs being the property&#39;s location, location crime rate, property square foot, and population. The output is the price the property is sold at. This function <em>is</em> the “relationship” that the investor was referring to, but what the mathematician sees is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*i_0_I9BPWy-xA6I5W3a9cg.png" /><figcaption><em>Price is some function of the inputs. This function may be simple or incredibly complicated, we just don’t know! </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>As the mathematician works tirelessly to find this function, the investor grows impatient. And after a couple of days, he loses his patients and becomes business partners with a more experienced investor instead of waiting on the mathematician. This more experienced investor is so good at what he does that he can show up to the property and give a great estimate of what the property can sell for without even using grade school math.</p><p>The mathematician, embarrassed, gives up on manually finding this function. Defeated, he asks himself, “How is this problem so difficult to solve using mathematics, but so intuitive to the experienced investor?”. Unable to answer this question he finds a neuroscientist in hopes to understand how the investor&#39;s brain solves the problem.</p><p>The neuroscientist, unable to answer exactly how the investor is estimating prices so well, teaches the mathematician how the neurons in the brain work. The mathematician then models these neurons mathematically. After years and years of hard work this mathematician finally finds out how he can find the relationship between any 2 related things, including the details of a property and the price it will sell at. He then uses this information to make a hundred million dollars and lives happily ever after.</p><h4>Modeling the biological neuron</h4><p>As we have seen from the story above, if we want to model things that are so intuitive to humans but incredibly complicated to model mathematically we must look at how the human brain does it.</p><p>The human brain is made of billions of neurons. A simplification of a neuron is this; many signals of varying magnitude enter the nucleus, and <em>if the total incoming signal is strong enough</em> (it’s greater than some threshold that is specific to this neuron) the neuron will fire and <em>output</em> a signal. This outputted signal is one of the inputs to another neuron, and the process continues. See the figure below to visualize this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*bUhCnQRnCuA-9Fdtxu8Xfw.png" /><figcaption>This threshold is referred to as the neuron&#39;s “bias” in artificial neural networks. <strong><em>*Image by author*</em></strong></figcaption></figure><p>So how can we model this mathematically? The neuron is receiving many inputs of varying magnitude, the total signal received can be modeled as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*MbP9N4Jw4Ln8jNgGDI6C4Q.png" /><figcaption><em>These W variables are called weights. They add “weight” to the input signals to change their magnitude. In the brain, neurological connections have different electrical resistances. This resistance is the biological equivalent to the weights in our model. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Okay, now if the total incoming signal is greater than this neuron&#39;s threshold then the neuron fires. Or mathematically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/266/1*9HlA4JJaXrVwazCHfDNUIw.png" /><figcaption><em>This threshold is called a bias and labeled B. If the sum of the weighted inputs is greater than B, this will output a 1. If they are less than B, this will output a 0. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Before we call this a complete model of the neuron, we must address one thing. It is beneficial to get rid of the “if” statement in the above equation. We do this by passing the left side of this equation into what is called the <em>sigmoid function</em>. Let’s look at a graph of what we currently have versus the graph of a sigmoid function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*FwF4DF0884qxM7PUIchnTQ.png" /><figcaption><em>The sigmoid function is an example of an activation function. It is currently most popular to use the ReLu function instead, but the sigmoid function makes it easy to understand how they thought of the idea in the first place due to its similarity to the step function. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>As you can see the sigmoid function behaves almost exactly like the step function we had before. The only difference is we don’t have to deal with that ugly if statement. The function is also differentiable now, which is useful for reasons I will explain shortly. Note that we can use any differentiable function here, just some work better than others.</p><p>Below is our final mathematical representation of a neuron.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*FoqE_5OwcChiKwGz2Vda0Q.png" /><figcaption><em>Z = the weighted sum of all inputs-the bias of the neuron. We then pass Z through the sigmoid function to get our output. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>We can now update our picture of the neuron to fit our mathematical model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*uiW-mkWz95d_Q6cARpDjig.png" /><figcaption><strong><em>*Image by author*</em></strong></figcaption></figure><h4>Combining multiple neurons</h4><p>Now we understand the workings of one neuron, and we have modeled it mathematically. As I said before the human brain consists of billions of neurons. These billions of neurons all send and receive signals to and from other neurons, forming a <em>neural network</em>.</p><p>Let’s zoom back down on one neuron. This neuron receives a bunch of inputs, then sends a signal to one or more other neurons. These neurons all do the same, receive a bunch of inputs from neurons then send a signal to more neurons. A brain can be thought of as a big complicated tangled-up (gross) web of connected neurons.</p><p>When we model a neural network mathematically, we bring some order to this web. Most often, we organize the neurons in layers. Each layer receives input from the previous layer and sends output to the next layer. We make the last layer (the output layer) have a number of neurons = the number of outputs we want. Below is an example of an <em>artificial</em> neural network (a mathematical model of a neural network), with 2 outputs and 3 inputs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*GePj-FMHOabZwGAn_v_S9g.png" /><figcaption><em>The weights can be seen as a matrix as you will see in implementation. </em><strong><em>*Image by author*</em></strong></figcaption></figure><p>Going back to our real estate investor&#39;s problem, the data he has on the property would be the input, and the price of the property would be the output. Recall that he had 4 total inputs and wants those inputs to tell him the price. Now, ask yourself what the number of neurons should be in the first and last layer, with 4 inputs and 1 output.</p><p>Your answer should be 4 in the first layer and 1 in the last layer. But, how many neurons should we put in between? And how many layers should we have? This is where the exact mathematics stops and trial and error comes in. We call these values <em>hyperparameters</em>. The optimal number of layers and the number of neurons in each layer is different for every problem, it is just something you have to test. Generally, increasing the number of layers and neurons in each later will make the neural network more robust. BUT if you have too many layers and neurons then the network will overfit to your data and simply memorize the outputs.</p><h4>The fundamental idea behind artificial neural networks</h4><p>So, we have a mathematical model of a neural network. <em>How do we actually make this thing work?</em> How do we make this network actually give us the output we are looking for, given the inputs? Do me a favor and put your brain in sponge mode for just a second and think about the very bold statement below.</p><blockquote><strong><em>If given enough information in the inputs and given a robust enough architecture, there exists some set of weights that will make the neural network give us the output we want. Our goal is to find these weights.</em></strong></blockquote><p>We can say that for any 2 related things, there is some complicated function that models their relationship. This is the function the mathematician was trying to find by hand. The 2 related things being all the data on the property and the price that the property sold at. It turns out that if we have the correct set of weights in our neural network, we can replicate this relationship.</p><p>With some calculus and code, we can find these weights in the blink of an eye. The process of finding these weights is where neural networks and artificial neural networks take their separate paths, however. I’m not sure if it’s known how real neural networks learn, but using calculus and data we can make our artificial neural networks find the weights that will map an input to output if possible.</p><p>The article on finding these weights, or training our neural network, is posted <a href="https://doingengineering21.medium.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">here</a>.</p><blockquote>Thank you for reading! If this post helped you in some way or you have a comment or question then please leave a response below and let me know! Also, if you noticed I made a mistake somewhere, or I could’ve explained something more clearly then I would appreciate it if you’d let me know through a response.</blockquote><blockquote>This is a continuation of a series of articles that give an intuitive explanation of neural networks from the ground up. For the other articles see the links below:</blockquote><blockquote>Part 1: What is an artificial neural network</blockquote><blockquote><a href="https://towardsdatascience.com/how-to-train-a-neural-network-from-scratch-952bbcdae729">Part 2: How to train a neural network from scratch</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/full-implementation-of-gradient-descent-no-holding-back-86e688f36064">Part 3: Full implementation of gradient descent</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/implementing-gradient-descent-example-102b4454ea67">Part 4: Implementation of gradient descent (an example)</a></blockquote><blockquote><a href="https://doingengineering21.medium.com/how-to-classify-handwritten-digits-in-python-7706b1ab93a3">Part 5: How to classify handwritten digits in python</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b508c821ace8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-an-artificial-neural-network-b508c821ace8">What is an artificial neural network?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>