<?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 Ani Karenovna K on Medium]]></title>
        <description><![CDATA[Stories by Ani Karenovna K on Medium]]></description>
        <link>https://medium.com/@karenovna.ak?source=rss-33d6a06bcd2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Gw3-nfYiDMjnBp8OvzVLFQ.jpeg</url>
            <title>Stories by Ani Karenovna K on Medium</title>
            <link>https://medium.com/@karenovna.ak?source=rss-33d6a06bcd2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 13:05:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karenovna.ak/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[Neural Networks From Scratch Series]]></title>
            <link>https://medium.com/@karenovna.ak/neural-networks-from-scratch-series-c969ba5b4e2b?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c969ba5b4e2b</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 04:11:24 GMT</pubDate>
            <atom:updated>2020-06-17T19:13:28.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Mathematics Behind Neural Networks</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*qOIQL6FYmH95jHvAm1DUoA.png" /><figcaption><a href="https://svitla.com/blog/neural-networks-and-cloud-ide-setup-and-run-tensorflow-on-codenvy">Image source</a></figcaption></figure><p>This post describes a series of articles I started publishing on Medium which focuses on the topic of neural networks. More specifically, the series focuses on <strong><em>deriving the mathematics behind neural networks from scratch</em></strong>.</p><p>I took on this project because I wasn’t satisfied with the content on neural networks that I could find online at the time when I became interested in the field myself. I found that there was a deficiency in the mathematical foundation of neural networks in online articles <strong><em>for those readers who didn’t necessarily want to read academic papers on the topic or take a full course but still wanted to get a somewhat reasonable understanding of the math involved (although not in all detail).</em></strong></p><p>While some of the articles in the series are intended to be aimed at any reader who is interested in learning about neural networks, others expect the reader to be familiar with some level of calculus. The articles present graduate level course material on neural networks <strong>explained in the simplest terms possible while involving the most relevant (but not complete) mathematical derivations</strong>. The series is meant to be read in order of the articles I provide here because the content of every article is built on top of the content of the preceding articles.</p><p>This is a live document so I will continue to add the embedded links to the articles in the series as I continue to publish them in the future.</p><blockquote>This being said, I hope this series hits that sweet balance between concept and math for my readers and I hope you enjoy it!</blockquote><ol><li><strong>The Perceptron — The Building Block of Neural Networks</strong></li></ol><p>This is the first article in the series and it is friendly for all types of readers regardless of their math background (some minimal high school level math…maybe). The article <strong>introduces the perceptron and how it can be used to compute the logical ‘OR’ statement.</strong></p><p><a href="https://blog.usejournal.com/the-perceptron-the-building-block-of-neural-networks-5a428d3f451d">The Perceptron — The Building Block of Neural Networks</a></p><p><strong>2. Training a Single Perceptron</strong></p><p>This is the second article in the series which discusses a single perceptron model and <strong>what it means for a perceptron to learn</strong>. Some calculus experience is recommended here as the post derives the basic math behind the learning algorithm of the perceptron.</p><p><a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b">Training a Single Perceptron</a></p><p><strong>3. How Neural Networks Learn</strong></p><p>This article builds on the mathematics introduced in the second article of the series — <em>2. Training a Single Perceptron. </em>The math gets a bit more involved as the derivation of the <strong><em>Feedforward Backpropagation Algorithm </em></strong>is discussed here.<strong><em> </em></strong>Basic to intermediate level of calculus is expected.</p><p><a href="https://medium.com/@karenovna.ak/how-neural-networks-learn-f602d6f77a13">How Neural Networks Learn</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c969ba5b4e2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Neural Networks Learn]]></title>
            <link>https://levelup.gitconnected.com/how-neural-networks-learn-f602d6f77a13?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f602d6f77a13</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 03:19:15 GMT</pubDate>
            <atom:updated>2020-06-17T14:09:34.044Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Feedforward Backpropagation Algorithm Derived</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*ahaU6RPeJ2atMS1vdRNJ5w.png" /></figure><p><em>Note: This post is part 3 of a </em><a href="https://medium.com/@karenovna.ak/neural-networks-from-scratch-series-c969ba5b4e2b"><em>series on Neural Networks From Scratch</em></a><em>. The mathematics herein builds on the mathematics derived in part 2 — </em><a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b"><em>Training a Single Perceptron</em></a><em>, thus I highly encourage you to have a solid understanding of the equations laid out in that post. The reader is expected to have experience in calculus.</em></p><p>In my <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b"><strong>previous article</strong></a><strong> </strong>I derived the mathematics of training a single perceptron. The article here is the continuation of the previous one which extends the notion of training a single perceptron to training a multilayer and multi-perceptron neural network. <strong><em>This post includes all the math necessary to derive the Feedforward Backpropagation Algorithm — the core of how neural networks learn.</em></strong></p><p><a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b">Training a Single Perceptron</a></p><p>Without further ado, let’s jump into the content.</p><ol><li><strong>A QUICK REVIEW OF THE SINGLE PERCEPTRON MODEL</strong></li></ol><p><a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#a773"><strong>Training a single perceptron</strong></a> (the simplest form of a single node, single layer neural network) involves using <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#b7ed"><strong>gradient descent </strong></a>to iteratively <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#b7ed"><strong>update the weights</strong></a> connecting the inputs and the perceptron in a way such that the <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#fe4f"><strong>error function</strong></a><strong> </strong>is minimized<strong>.</strong> The error function measures the deviation of the actual output of a perceptron from the desired output (the label) in a <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#7069"><strong>supervised learning</strong></a> setting. The weights then become updated according to the error we observe with the help of the <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#bfb0"><strong>perceptron delta function</strong></a><strong><em> </em></strong>— a function that quantifies by how much a current weight needs to be changed in order to obtain the updated weight such that error is further reduced. For simplicity, I will ignore the bias throughout this post.</p><p>Consider the perceptron model below with a single perceptron <em>j </em>and an <em>m </em>dimensional input vector <em>x</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hxyi6iPneEwnEHuXPyRZ9w.png" /><figcaption>Diagram 1: A single perceptron model</figcaption></figure><p>From here on I will refer to a perceptron as a <em>node </em>whenever a math discussion is involved. The vector <em>x</em> is often referred to as the <strong>feature vector. </strong>This feature vector contains <em>m</em> elements, each of which represents a single feature describing a single data point. In order to apply gradient descent to this node, we need to calculate the <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#edc0"><strong>gradient vector</strong></a><strong> </strong>. In this case the gradient vector is an <em>m</em> dimensional vector the components of which are the partial derivatives of the error function <em>E</em> with respect to the weights. <em>Thus each component of the gradient vector represents the rate at which E changes in the direction of a single weight.</em></p><p>Recall that each component of the gradient vector can be calculated utilizing the <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#f626"><strong><em>chain rule</em></strong></a> as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3M05d14cVzXM4k2RhBhxkw.png" /></figure><blockquote><strong><em>In single perceptron model, the gradient vector is the expression in which partial derivatives of the error function are taken with respect to all of the weights connecting the inputs to just one node.</em></strong></blockquote><p>We move from the rightmost layers and functions to the edges or weights:<em> E → e → y_j</em> → <em>A_j</em> → <em>w_ij</em>. All the factors in the above equation with some index j can conveniently be aggregated into a factor <em>delta_j</em>. This is more than a mathematical convenience and is essential to the back propagation algorithm as we will see later. After reworking quite a bit of math, we derived the <a href="https://blog.usejournal.com/training-a-single-perceptron-405026d61f4b#bfb0"><strong><em>perceptron delta function</em></strong></a> for a single weight as shown here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S1Dw5TxCSy8dnWgHHc3bUw.png" /></figure><p>But now let’s look at a network that has several inputs that feed into several nodes, such that the output of each node can serve as input to other node(s).</p><p><strong>2. THE FEEDFORWARD BACKPROPAGATION ALGORITHM (FFBP)</strong></p><p><strong>2.1. The Feed Forward Process</strong></p><p>For a multi-layer, multi-perceptron network we have an <em>input layer</em>, a <em>hidden layer</em> and an <em>output layer. </em>Let’s use a concrete example with <em>m</em> inputs in the input layer, <em>n </em>nodes in the hidden layer and a single node <em>k</em> in the output layer as shown in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pIHtcJmIA8hKMpVwbw5Zug.png" /><figcaption>Diagram 2: A multi-perceptron, multi-layer neural network.</figcaption></figure><p>The node in the output layer is what produces the<em> actual output</em> which is then compared to the <em>desired output </em>(the label)<em> </em>via the error function. The process works like this:</p><ol><li>the inputs in the input layer <em>feed through</em> the network to produce an output at each of the nodes in the hidden layer (nodes 1, 2, …j, …n)</li><li>The outputs from the hidden layer (y1, y2, …y_j, …y_n) are then used as inputs (x1, x2, …x_j, …x_n) to node <em>k </em>node in the output layer.</li><li>Node <em>k</em> in the output layer ultimately produces the actual output (y_k).</li></ol><p>This process is what we refer to as ‘<strong><em>feed forward’</em></strong> in the name of the algorithm because the inputs at input layer feed through the network from left to right to produce the actual output at the output layer. You may have also heard this process being called the <strong><em>feed forward epoch</em></strong>.</p><p>The example network here can be generalized to having an arbitrary number of hidden layers and an arbitrary number of nodes in each of the hidden layers and in the output layer. I chose to have a single node <em>k</em> in the output layer to stick with the simple binary classification problem. If the output layer contained more than one node, then we would be dealing with a multi-class classification problem.</p><p><strong>2.2. The Back Propagation Process</strong></p><p>Once we have gone through the feed forward epoch and produced the actual output at node <em>k, </em>we then need to compute the gradient vector similar to how we did for the single perceptron model. The additional number of nodes and the hidden layer in the network, however, greatly amplify the complexity of computing this gradient vector.</p><blockquote><strong><em>In a multi-layer multi-perceptron model, the gradient vector is much more complicated because partial derivatives of error function are computed with respect to all the weights associated with all of the output layer nodes and with respect to all the hidden layer nodes — making the job of the neural network computationally very expensive. In general, if a network has a total of n weights, then there will be n partial derivatives to compute at each iteration and the computation of each partial derivative is quite mathematically involved.</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kg9mApqolVCUhSMCa1rsZQ.png" /><figcaption>Gradient vector expression for a multilayer, multi-perceptron neural network (aka, the monster expression)</figcaption></figure><p>I will call the above expression <strong><em>the monster expression </em></strong>as I need to refer to it later and because it looks like a monstrosity to me. Per diagram 2, we have two layers which we need to account for when calculating the gradient vector: in other words, the elements of the gradient vector are computed first as the partial derivatives of the error function with respect to the weights connecting the output layer to the hidden layer and then as those with respect to the weights connecting the hidden layer to the input layer — going from right to left (backwards). I highly suggest to keep referring to the diagram to visualize what’s being said here.</p><p><strong>Output Layer to Hidden Layer</strong></p><p>If we zoom in to just one of the terms in the monster expression, say the second term, we are looking at the partial derivative of the error function with respect to a weight connecting the output layer to the hidden layer — namely with respect to some weight <em>w_jk</em> (going from right to left). As you can see, we start with the error function which gets calculated after the output has been produced in the output layer by node <em>k </em>upon the completion of the<em> </em>feed forward epoch. This is what the expression for the single partial derivative looks like which connects some jth node in the hidden layer to node k.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhsFZkbtNNGs95KnXKvCnA.png" /><figcaption>Equation 1: Equation for computing the elements of the gradient vector with respect to weights connecting the output layer to the hidden layer (going from right to left)</figcaption></figure><p>This is the equation is a generalized form of how to compute the elements of the gradient vector associated with the outermost layer. In our particular example, since we have three weights connecting node <em>k</em> to three nodes in the hidden layer, we would be computing three partial derivatives. These three partial derivatives are the three of the components (or elements) of the gradient vector describing <em>output layer — to — hidden layer </em>connections. Actually, this generalized expression computes the gradient vector just like we had done previously in the single perceptron model. The only difference is the subscripts which we changed here for the purpose of this example.</p><blockquote><strong><em>Don’t confuse the notion of the gradient vector and the partial derivatives. The gradient vector is a vector containing as its elements the partial derivatives of the error function with respect to the weights within a neural network. A gradient vector of a neural network has as many partial derivatives as there are weights within the network.</em></strong></blockquote><p><strong>Hidden Layer to Input Layer</strong></p><p>Next let’s zoom in on one of the terms (i.e. partial derivatives) in the monster expression which is with respect to one of the weights connecting the hidden layer to the input layer (again, going from right to left). To be more specific, let’s look at the partial derivative of the error function with respect to the weight connecting the jth node in the hidden layer with the ith node in the input layer. <em>The ith node in the input layer is really the same as the ith input — namely x_i.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*tgGvHt9J1XUsmJxSSJA25A.png" /><figcaption>Equation 2: Equation for computing the elements of the gradient vector with respect to weights connecting the hidden layer to the input layer (going from right to left)</figcaption></figure><p>In this case because we are not starting in the output layer, the error is not being propagated backwards one layer at a time. This is why for this term we only have three factors as opposed to four. In general,</p><blockquote>a partial derivative with respect to a weight that connects a <strong><em>hidden layer node to an input layer node</em></strong> (aka an input) has three terms.</blockquote><blockquote>a partial derivative with respect to a weight that connects a <strong><em>hidden layer node to another hidden layer node</em></strong><em> </em>has three terms (in case if there are multiple hidden layers).</blockquote><blockquote>a partial derivative with respect to a weight that connects a <strong><em>hidden layer node to the output layer node</em></strong> has 4 terms.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*IkWMCn6fQyNFbsNERpTi8A.png" /><figcaption>Diagram 3: A simplified diagram of our neural network.</figcaption></figure><p>Recall that earlier I kept mentioning ‘from right to left’. To better describe the process discussed herein, look at the Diagram 3 above as you read along.</p><ol><li>We can use the <em>delta_k</em> value computed at the output node to compute the partial derivatives associated with the error function with respect to weights represented by the straight edges.</li><li>The partial derivatives allow us to compute the <em>delta_j </em>values at the nodes in the hidden layers.</li><li>Then since we now have the <em>delta_j </em>values, we can compute the partial derivatives associated with the weights represented by the curly edges.</li><li>But the values of <em>delta_j </em>depend on the values of <em>delta_k, </em>thus we are, again, moving from right to left in the network — or in other words we are going backwards.</li></ol><p>This is why we call this process of the algorithm<em> ‘</em><strong><em>back-propagation’, </em></strong>also known as the <strong><em>back-prop epoch.</em></strong></p><p><strong>2.3. The Full FFBP Algorithm</strong></p><p>I will now spare you some more math here because it’s not exactly critical to understanding how neural networks learn. What’s important to know is that after doing some calculus and algebra magic, we can further simplify equation 2 as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*6jhG-U2njzrdJNuXhVFwJg.png" /></figure><p>Since an element of the gradient vector represents the direction in which the error function decreases the fastest with respect to a given weight, we can rewrite the above expression like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*zJsSyCpPtUvHX5BrRxK99A.png" /></figure><blockquote><strong>The expression in the box is the <em>FFBP algorithm which quantifies the change (</em>delta<em>) that needs to be applied to a current weight (</em>w_ij<em>) in order to reduce the error for the next iteration of the algorithm.</em></strong></blockquote><p><em>Can you see how this is pretty much the same as the perceptron delta function which we derived for a single perceptron model except applied to a neural network with more nodes and layers? The gradient vector is a lot more complicated but only so due the the added number of nodes and their associated weights. The only nuance is the slight difference in how we compute the elements of the gradient vector for different layers within the network (Equation 1 and 2).</em></p><p>By the way, if you really want to see the math details which I have skipped above, leave me a comment below and I’ll include it.</p><p><strong>3. RECAPPING ALL THE MATH MESS</strong></p><p>I hope that you see that once you understand how the single perceptron learns, understanding a neural network with a more complex topology is a matter of expanding what we already know about the single perceptron to a network made of multiple perceptrons and multiple layers. That is, the FFBP algorithm is essentially the perceptron delta function applied to a more complex topology. I will urge you again to make sure you understand everything in my previous post, especially how gradient descent works as this is a crucial part of the FFBP algorithm.</p><p>To recap, there are two distinct stages in the FFBP algorithm at each iteration: the feed forward epoch and the back-prop epoch.</p><ol><li>During the feed forward epoch inputs are fed through the network into the nodes from the left most layers to the right most layers until an output is produced at the output node. Once the output is produced, the error is computed for the output.</li><li>During the back-prop epoch, the error function is used to compute the gradient vector which contains the partial derivatives with respect to each weight in the network— the key component of gradient descent used to minimize the error. The derivatives are computed backwards in the network — from the rightmost output layer to the input layer in the far left.</li></ol><p>The processes in 1 and 2 describe one iteration of the FFBP algorithm. As more and more such iterations are done, the network keeps updating the weights in a way so that the error function continues to become minimized. <strong><em>Once the error function is minimized, meaning we have found the optimal weights for the network, we say that the neural network has been trained.</em></strong></p><p>My next post in this series will be a numerical example of implementation of the FFBP algorithm. Hopefully the example will further reinforce the mathematics that I laid out in this post.</p><p>This content was adopted from<a href="http://page.mi.fu-berlin.de/rojas/neural/index.html.html"> <em>Rojas, Raul (1996): Neural Networks: A Systematic Introduction. Berlin: Springer-Verlag Publishers. Ch 7.1–7.3.</em></a><em>4, Ch 8.1–8.2.1 and from lecture notes of Dr. M. Fleischer — professor at Johns Hopkins University, Neural Networks Introduction graduate course.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f602d6f77a13" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-neural-networks-learn-f602d6f77a13">How Neural Networks Learn</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Training a Single Perceptron]]></title>
            <link>https://levelup.gitconnected.com/training-a-single-perceptron-405026d61f4b?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/405026d61f4b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 07:39:32 GMT</pubDate>
            <atom:updated>2020-06-17T14:16:26.639Z</atom:updated>
            <content:encoded><![CDATA[<h4>AND ITS LEARNING RULES DERIVED FROM SCRATCH</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LxK-OVZ7POQvolWW0irefQ.jpeg" /></figure><p>In my previous post I introduced the structure and the function of a perceptron — a building block of every neural network. I concluded my post by bringing your attention to the fact that, while I defined most variables and functions that go into the perceptron, I didn’t mention anything about what happens to the weights. Well, the weights themselves and how they’re set or changed are actually at the heart of what it means to <strong><em>train a perceptron</em></strong>. My goal here is explain how a single perceptron can be trained. If you understand how this works on a single perceptron, then you should be able to build up a solid intuition about how a neural network with a more complex architecture gets trained in general.</p><p>In case you’d like a refresher or have not seen my post on the structure and function of the perceptron, check it out in this article below even though I’ll quickly summarize the main points before moving forward into training a perceptron.</p><p><a href="https://blog.usejournal.com/the-perceptron-the-building-block-of-neural-networks-5a428d3f451d">The Perceptron — The Building Block of Neural Networks</a></p><p>NOTE: Some experience in calculus is recommended for this post.</p><h4>1. THE PREREQUISITES</h4><h4>1.1. A Quick Refresher on the Perceptron</h4><p>This diagram is taken directly from my previous <a href="https://blog.usejournal.com/the-perceptron-the-building-block-of-neural-networks-5a428d3f451d">article:</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Na5QShwTC68ngMDsSikyw.png" /><figcaption>Diagram of a single perceptron model where x1, x2 are the inputs, w1 and w2 are the weights connecting input x1 and x2 to the perceptron respectively (represented as the circle) and theta is the bias term. A is the activity function value and f(A) is the activation function value which produces the final binary output of the perceptron. Here f is the sigmoid function.</figcaption></figure><p>Here is a recap of what’s illustrated in the diagram:</p><ol><li>This diagram is of a binary classifier perceptron that can compute simple logical statements.</li><li>The activity function A is a weighted sum of the input variables x and some bias theta. It defines the line or the linear boundary which can bisect the input space in a way such that the binary data points can be separated. The property of a straight line being able to separate such points in space is called <strong><em>linear separability.</em></strong></li><li>The <strong><em>bias</em></strong> term determines the vertical placement of the line in the input space.</li><li>The <strong><em>activation function f </em></strong>is a function that takes the activity value as its argument (the output of <strong><em>activity function A</em></strong>) and maps it to either a 0 or a 1 to ensure that the final output of the perceptron is binary.</li></ol><h4>1.2. Convenient Notation</h4><p>Let’s introduce a slightly refined and generalized representation of the perceptron above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCarYilSqeXnKeHIqTtMlg.png" /><figcaption>A more generalized diagram of the perceptron model.</figcaption></figure><p>I’m adopting this new notation to make the upcoming parts of this post easy to understand. Here we have the following new notations:</p><ol><li><em>w_ij — </em>the weight that links input <em>x_i</em> to perceptron <em>j </em>(the node in the middle of the diagram).</li><li><em>y_j — </em>the output of perceptron <em>j</em>.</li></ol><h4>1.3. Weights — The Things That The Perceptron Learns</h4><p>Recall that the components that make up a perceptron are the inputs, the weights, a bias, the activity function and the activation function, while the output is a final quantity that depends on all of these things. The inputs are fixed — they are the data! We can’t make any changes to the data. The activity function and the activation function are just that — functions, not quantities to be changed around either. So the only thing that we actually have control over to change around when training a perceptron are <strong><em>the weights</em></strong>. This means that …</p><blockquote><strong><em>…when we train a perceptron, we make changes to the weights iteratively until we find the best set of weights so that the activity function produces the correct slope and orientation of a line in order to take advantage of linear separability.</em></strong></blockquote><h4>1.4. Supervised Learning</h4><p>Let’s think of a perceptron in the context of supervised learning. Imagine that we have a some label for what the output y_j of perceptron j needs to be: let’s call this our <strong><em>desired output d_j</em></strong>. This desired output d_j is the ground truth, the target output we know the perceptron should be producing. In other words, this desired output <strong><em>supervises our perceptron in what weights it should learn in order to produce a certain output </em></strong>— thus the term supervised learning.</p><p>If we know what the desired output is, we can use some math to our advantage to define some function that will allow us to compare the desired output d_j to the <strong><em>actual output y_j </em></strong>that the perceptron produced. But we also want this function to be dependent on the weights since the weights are what we want to update when training a perceptron. Let’s call this function an <strong><em>error function</em></strong> because if the actual output is not equal to of the desired output, then the value of the error function is non-zero and we can say that the perceptron has made an error! I’m calling it an error function here to stick with intuitive language but this is what is conventionally referred to as the<strong><em> loss function</em></strong>.</p><p>Our goal is then to find the minimum of this function — as error is something we wish to minimize.</p><blockquote><strong><em>We can define some function that depends on the weights and which will allow us to relate the actual output of the perceptron to some desired output. This function is the error function and the goal is to minimize it by iteratively updating the weights.</em></strong></blockquote><p>Once the error is minimized, we can they say the perceptron has been trained.</p><h4>2. TRAINING THE PERCEPTRON</h4><h4>2.1. Initialize the Weights and Calculate the Actual Output</h4><p>Let’s look at the perceptron again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCarYilSqeXnKeHIqTtMlg.png" /><figcaption>A more generalized diagram of the perceptron model.</figcaption></figure><p>The input x_i is multiplied by a randomly initialized weight w_ij and is fed into the perceptron along with a bias and all other weighted inputs. Inside the perceptron the activity function is applied to this weighted sum of inputs plus a bias and its value is then fed as an argument into the activation function f. The value of the activation function produces the output y_j of perceptron j.</p><h4>2.2. Define and Calculate the Error</h4><p>Before we can calculate the error, we first need to define the error. Remember that I mentioned that the error function has to be dependent on the weights and it needs to relate actual output y_j to desired output d_j. So let’s define it as this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pvXoGnihpUEnWZtAOEA0AQ.png" /><figcaption>A prerequisite to the error function of a perceptron</figcaption></figure><p>This function e_j does relate d_j to y_j and is in fact dependent on the weights because we know the y_j term itself is dependent on the weights. We know that we want to minimize e_j. But depending on the values of d_j and y_j, we might get a negative value for the error e_j. So let’s square it to ensure that the error is always a positive number and define it as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j9qFUgKpDmTG3C93enjhfQ.png" /><figcaption>Error function of a perceptron</figcaption></figure><p>So then, we’ve redefined the error function e_j as E_j to ensure that it is never negative. But I’ve also included a factor of 1/2. As one of my favorite professors used to say, ‘we do what is convenient in mathematics’. The factor of 1/2 is there to make things more convenient later. I will come back to this shortly.</p><h4>2.3. Gradient Descent — Updating the Weights to Further Reduce Error</h4><p>Now that we have an error function, we can use it to help us determine how to update w_ij so we can reduce the error further. Let’s define some mathematical expression for what an updated weight looks like based on current the current and the error function E_j:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mTftkLEujPqm8efPxUvgKQ.png" /><figcaption>Representation of gradient descent</figcaption></figure><p>The equation in the box is an expression for finding an <strong><em>updated weight w_ij(k+1) </em></strong>using</p><ol><li>the <strong><em>current weight w_ij(k)</em></strong></li><li>some <strong><em>step size</em></strong> given by the greek letter <strong><em>eta</em></strong></li><li>the <strong><em>derivative of the error function E_j with respect to w_ij.</em></strong></li></ol><p>This is, in other words, the formula of <strong><em>gradient descent — </em></strong>an iterative method of finding the minimum of a function.</p><blockquote><strong><em>Gradient Descent — given an initial starting point w_ij(k) we want to move in a direction of steepest descent which can be calculated by the derivative of the error function scaled by some amount eta — thus arriving to some new point w_ij(k+1) which corresponds to the point w_ij(k) either reduced or increased by some amount that is equivalent to the quantity eta * derivative of E_j.</em></strong></blockquote><h4>Why the Partial Derivative?</h4><p>A question arises: Why have I indicated the derivative of the error function with a <strong><em>partial derivative</em></strong>? Well, the graph above is a graph of the error as a function of a <strong><em>single weight</em></strong>. In more realistic cases a perceptron will have multiple weights. If we had 2 weights for example, the the graph of the error function would be a 3 dimensional surface in 3 dimensional space, thus two partial derivatives of the error function would need to be calculated with respect to both weights. More generally, if we had n weights, then the error function would be an n+1 dimensional hyper-surface in n+1 dimensional space and its derivative would be calculated with the help of a <strong><em>gradient vector </em></strong>with n components — each representing a partial derivative of the error function in the direction of a single weight.</p><p>But let’s go back to the expression of an updated weight w_ij(k+1). From this we can actually derive the quantity by which we need to change the current weight during the next iteration (either increase it or decrease it by some amount) in order to further reduce E_j. This quantity of change to the current weight is denoted by the term <strong><em>delta w_ij </em></strong>in the box below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBIMCJ-lrNuWOX8KoWN-cw.png" /><figcaption>Weight update equation</figcaption></figure><p>The expression in the box above is an application of the method of gradient descent in the context of the perceptron where we try to modify the weights in order to reduce the value of the error function.</p><h4>Derivative of the Error Function and the Chain Rule</h4><p>So how do we calculate the derivative of the error function? To calculate this derivative we have to acknowledge that the error function E_j is pretty complicated <strong><em>composite function</em></strong> composed of function e_j which in turn is composed of yet another function y_j, etc. More specifically,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ciEQtLf7EzXeE2A-EWzNSA.png" /><figcaption>The error function is a complex function comprised of other functions which in turn are comprised of other functions, thus leading to the necessity to apply the chain rule</figcaption></figure><p>thus, we need to make use of the <strong><em>chain rule </em></strong>to take the derivative of E_j with respect to the weight w_ij.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*1fr1Xxd2rlb3jxqbXtCxlA.png" /><figcaption>The chain rule applied to the error function</figcaption></figure><p>Next, we need to compute each of the four partial derivative terms on the rights side of the above equation, but that’s not a very difficult task given that we know E_j, e_j, y_j and A_j:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*dYL9kBJa4lvQ9v0Z5Z_cqw.png" /><figcaption>Individual terms that make up the gradient vector of the error function</figcaption></figure><p>Now that we have each of those terms computed, we can plug them back into the chain rule equation for the derivative of E_j and we will get the following expression:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*h99ky4BqC7B9WxhAWh833Q.png" /><figcaption>A cleaned up version for calculating the gradient vector of the error function</figcaption></figure><h4>2.4. The Perceptron Delta Function — Putting it all together</h4><p>Again, in the above expression recall that the subscripts i_j for the weight indicate that this is the weight linking input i to perceptron j. The partial derivative of E_j here is in the direction of the weight w_ij only, and therefore this derivative is only one of the elements of the gradient vector of of E_j for perceptron j. Notice all the terms excluding x_i have the same subscript j indicating they all relate to output of perceptron j!</p><p>Let’s simplify even further by grouping the terms that share the same subscripts as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*WSKX-aykImxQCDvC4z2pfw.png" /></figure><p>And plugging this back into the expression for <strong><em>delta w_ij </em></strong>we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4avxTnJ1DuK4LU6tFn6c6w.png" /><figcaption>The perceptron delta function</figcaption></figure><p>The expression in the box is the <strong><em>perceptron delta function</em></strong> — <em>a function that quantifies by how much a current weight w_ij(k) needs to be changed in order to obtain the updated weight w_ij(k+1).</em></p><blockquote><strong><em>the</em> <em>perceptron delta function</em> <em>quantifies by how much a current weight w_ij(k) needs to be changed in order to obtain the updated weight w_ij(k+1) which will contribute to the further reduction of the error.</em></strong></blockquote><p>Iteratively repeating this process until the error is minimized is the very process we call training the perceptron.</p><h4>3. THE MULTIVARIATE CASE</h4><p>The computations above were done for a single perceptron j that contributes to the output y_j using a single weight w_ij. If we had m perceptrons contributing to some output y_j (that is m perceptrons in the output layer of a neural network for example) then the formula for the error function would be given as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*GEN-Cm_WBZveJnajXhmKHA.png" /><figcaption>Defining the multivariate version of the error function</figcaption></figure><p>Furthermore, if we want to account for all n inputs with the n weights that link them to every perceptron, then for each perceptron j in the above formula, we would need to calculate n updated weights using the perceptron delta function n times, and thus n partial derivatives of E_j that are components of the gradient vector of E_j. Thus you can see how this quickly becomes incredibly complex as soon as we start accounting for more weights and more perceptrons — attesting to the computational complexity that neural networks are a quite notorious for.</p><h4><strong><em>4. RECAPPING ALL THE MATH MESS</em></strong></h4><ol><li><strong><em>Training a perceptron</em></strong> is an optimization problem which involves iteratively updating the weights in a way that minimizes the error function.</li><li>We derived the <strong><em>error function</em></strong> and defined what an <strong><em>updated weight </em></strong>should be based on a current weight and the error calculated at the current iteration. We did this all using an example of a single weight and a single perceptron.</li><li>We then derived <strong><em>the perceptron delta function</em></strong> which quantifies the change that needs to be added to or subtracted from the current weight in order to arrive at the updated weight that further reduces the error.</li></ol><p>For my next post, I will build on the mathematical formulations derived herein to do a walkthrough of the <strong><em>feed forward back propogtation algorithm</em></strong> as applied to an example of a simple multi-layered perceptron (MLP). ___________________________________________________________________</p><h4>BONUS— Why Use Gradient Descent and Not Set the Derivative to Zero to Find the Minimum?</h4><p>A question arises as to why not simply minimize the error function by setting its derivative to zero. Well, if the number of weights gets large, then the error function quickly becomes very complex. Let’s say the graph below is a slice or a cross sectional view of some 3 dimensional (three weights) error function that makes up a surface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKSF055FCpTMlWHHluEvCQ.png" /><figcaption>A simplified graph of an error function over a single weight. Of course, in realistic cases we deal with many more weights. Each additional weight would add another dimension to this graph</figcaption></figure><p>As you can see the error function is very complex! The problems with such complex functions are :</p><p>1. we have many minima</p><p>2. such functions are too complicated to be expressed mathematically in a neat formula</p><p>3. taking the derivative of such complex functions may not even be feasible without a neat mathematical formula</p><p>4. finding the arguments (the optimal weights) that correspond to the global minima is not realistic.</p><p>Minimizing a function by setting its derivative to zero is an analytic approach to solving optimization problems, but analytic solutions aren’t always accessible to us. Therefore we can use an alternative method that is computational — a numerical approximation to this analytic method. That’s what gradient descent is — an iterative method of finding the minimum of a function by randomly initializing some weights from which we can move forward or backwards along the surface in the direction of the steepest descent until we get to the weights that correspond to the minimum of the surface.</p><ul><li>This content was adopted from<a href="http://page.mi.fu-berlin.de/rojas/neural/index.html.html"> <em>Rojas, Raul (1996): Neural Networks: A Systematic Introduction. Berlin: Springer-Verlag Publishers. Ch 4.1–4.2.5</em></a><em> and from lecture notes of Dr. M. Fleischer — professor at Johns Hopkins University, Neural Networks Introduction graduate course.</em></li></ul><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405026d61f4b" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/training-a-single-perceptron-405026d61f4b">Training a Single Perceptron</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Perceptron — The Building Block of Neural Networks]]></title>
            <link>https://medium.com/@karenovna.ak/the-perceptron-the-building-block-of-neural-networks-5a428d3f451d?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a428d3f451d</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Tue, 14 May 2019 08:41:36 GMT</pubDate>
            <atom:updated>2019-06-09T07:51:58.210Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Perceptron — A Building Block of Neural Networks</h3><h4>AND HOW IT CAN COMPUTE LOGICAL STATEMENTS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*yImBa3iyvODMcPg7Pbr_0A.jpeg" /></figure><p>A perceptron is the basic building block for any neural network and I don’t think anyone can firmly say they understand how neural networks work unless they can explain a basic perceptron to their grandmother. In this post, I will explain how the problem of finding the truth value of a simple logical statement can inspire us to build a single perceptron model which can in turn be used to find a solution to this problem. More specifically, I will show you how to solve the AND-statement problem with a single perceptron. But before we jump into it, do you recall what a truth table is? If you don’t know or don’t remember what a truth table is, that’s OK! I will first give you some quick overview which will cover everything necessary to understand here. But if you’d like to dive in deeper into some basic logic and how its used to prove things in mathematics, here is a great <a href="https://math.berkeley.edu/~hutching/teach/proofs.pdf">resource</a> .</p><p>Without further due…</p><h4>LOGIC 101</h4><p>In logic, every statement has a truth value — that is — every statement is either true or false. For example the statement ‘I have a cat’ is either true or it is false, but not both. You can combine statements into more complex statements with logical operators. An example of such logical operators is the <em>OR operator</em> and the <em>AND operator</em>. A complex statement is still just that — a statement, therefore it also has a truth value. The truth value of such a complex statement depends on two things: 1) the truth value of the individual statements that it is made of and 2) the rules of the logical operator that links those individual statements. From now on I will use the binary values 0 and 1 to represent ‘false’ and ‘true’ truth values respectively for any given simple or complex statement.</p><p><strong><em>Truth tables</em></strong> are used to represent the truth values of various logical statements and combinations thereof. For example, the table below is a truth table for the statement x1, the statement x2 and the AND-statement which is a conjunction of statements x1 and x2 (represented as x1 ^ x2 inside the table):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*l2TaMFX5qgCMWnOqubhJEw.png" /></figure><p>Here x1 and x2 are <strong><em>simple</em></strong> statements which I will refer to as input variables throughout this post. On the other hand, the statement x1^x2 is a complex statement.</p><p>Row 3 in this table, for example, represents the following information: statement x1 is true, statement x2 is false, statement x1 ^ x2 is false. The table contains information about the rules of the AND operator: for the statement x1 ^ x2 to be true, statements x1 and x2 must both be true. Otherwise the statement x1 ^ x2 is false.</p><p>An interesting question arises… Can we model this truth table mathematically? In other words, can we effectively model the binary truth value of the AND-statement given the truth values of some inputs x1 and x2?</p><h4><strong>THE MOTIVATION — PLOT THE TRUTH TABLE</strong></h4><p>Well, because the AND-statement is a function of inputs x1 and x2, we can plot the truth values of the AND-statement (or its output) like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGh15DmUnhkEWv1IlhKZfQ.png" /></figure><p>In this graph, the point (1,1) — corresponding to x1 = 1 and x2 = 1, is a filled-in circle. A filled circle is one that has a truth value of 1 and in this case it represents the x1 ^ x2 statement. The point (0,0) on the other hand is empty because it represents a truth value of 0 for the x1 ^ x2 statement for which the inputs are x1 = 0 and x2 = 0.</p><p>The line with the negative slope is some line I placed on the graph which bisects the input space in such a way that the points represented by empty circles (truth value of x1 ^ x2 = 0) are separated from points represented by the filled circle (truth value of x1 ^ x2 = 1). Let’s make this our objective — to come up with some mathematical model which will be able to correctly identify whether a given point is an empty circle or a filled circle by separating the these two classes of points.</p><p>How to find such a line that strategically separates these points though? Well, it is a straight line so we can represent it as some linear function A which we will call the <strong><em>activity function</em></strong>.</p><h4><strong>THE ACTIVITY FUNCTION</strong></h4><p>Let’s define an activity function A as some weighted sum of input variables x1 and x2 such that the function represents the line that serves as a boundary bisecting the input space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*IDACKa4L75m2KA1lWxz2vA.png" /></figure><p>According to this definition of the activation function, there is no intercept — that is — we have no information about the placement of the line: it can be placed higher or lower and we don’t exactly know where its best placement is so that it guarantees the separation of filled circles from empty circles. To make sure we account for this possible variation in the placement of the line, let’s introduce a <strong><em>bias term</em></strong> — theta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCOFPtaPGpkIVb5EacKPmg.png" /></figure><p>A bias term is nothing more than just an intercept. A positive bias term shifts the line up and a negative bias term shifts the line down without affecting the slope of the line.</p><p>Now, how can we use this slightly modified activity function A to model the truth value of our AND-statement? The answer lies within the perceptron.</p><h4>THE PERCEPTRON</h4><p>A perceptron is a mathematical model inspired by a simplified structure and function of a single biological neuron. This model is a binary classifier used in a supervised learning context which can classify a set of inputs to belong to one of two classes — in the case of our example, the classes correspond to the truth values of the AND statement.</p><p>We can model the truth value of the AND statement with a single perceptron in the following way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nr0p4SntwGmolqxG-rqwUA.png" /></figure><p><strong>When inside the node of the perceptron</strong>, the activity function A is represented by its output value therefore I’ll refer to it as the <strong><em>activity value</em></strong>. Our hope is that have <strong><em>output </em></strong>of this perceptron be a 0 or a 1 for the corresponding truth value of the AND-statement.</p><p>Let’s calculate a simple example with the following values of inputs, weights and bias:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cpxiGsWcFxHjnUiK5KZzA.png" /></figure><p>In this example, the activity value is 0.5. What if we had chosen inputs x1 = 0 and x2 = 2 and kept the bias as theta = -1.5? In this case, the activity value would be a negative number. This is problematic because this does not output a binary value as we would have liked. However, consider the following slightly more complicated representation of a perceptron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*BetlMweLlVxbYb7HyOLRqA.png" /></figure><p>There are some additional pieces here: an activation function and a threshold. Let’s define what these are.</p><h4>THE ACTIVATION FUNCTION</h4><p>The <strong><em>activation function f</em></strong> takes the activity value as input and combined with some <strong><em>threshold</em></strong> transforms the output to a binary value 0 or 1. Thus we can use the activity function A along with some activation function f to map the activity value into the appropriate truth values for the AND_statement. One possible candidate for an activation function is the following <strong><em>threshold logic function</em></strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*xBjwqNqRzHPeznIjjb1fnQ.png" /></figure><p>Such an activation function will map the activity value to a 1 if the activity value is greater than or equal to the threshold represented by a constant C, and to 0 otherwise.</p><p>A more convenient activation function that is used very often in binary classification problems is the sigmoid function represented by the dashed curve below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*Kbaz5NZal1iXpaLtxdhU8A.png" /></figure><blockquote><strong><em>The activation function f takes the activity value as input and combined with some threshold transforms the output to a binary value 0 or 1.</em></strong></blockquote><p>here are a number of activation functions that can be used and this <a href="https://medium.com/the-theory-of-everything/understanding-activation-functions-in-neural-networks-9491262884e0">blog post</a> has a good discussion on some, including the threshold logic function (referred to as the step function) and the sigmoid function.</p><h4>THE BIG PICTURE…</h4><p>It is possible for a perceptron to solve a truth table. Here I showed specifically how a perceptron can solve the logical AND-statement. I encourage you to try and see if you can get the perceptron to solve the OR-statement and perhaps even consider whether the perceptron is capable of solving the XOR-statement. <em>Hint here: in the case of the latter you might be disappointed.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OsXsUBFhzlhSbjUNg0ymRQ.png" /></figure><ol><li>The activity function A is a weighted sum of the input variables and some bias. It defines the line or the linear boundary which can bisect the input space in a way such that the binary truth values of the AND-statement represented by the filled circle and the empty circles can be effectively separated. The property of a straight line being able to separate such points in space is called <strong><em>linear separability</em></strong> and this property can be used to solve various other logic statements.</li><li>The bias term determines the vertical placement of the line in the input space.</li><li>The activation function is a function which maps the activity value to either a 0 or a 1 to ensure that the final truth value of the AND-statement is a binary outcome. The sigmoid function is one of the most commonly used activation functions in binary classification problems.</li></ol><p>It is important to note that I have not at all mentioned how to choose the values for the weights w1 and w2 or whether we even need to choose the values for the weights as opposed to randomly initializing them. Check out the article below in which I address the weights in a discussion of how to train a single perceptron:</p><p><a href="https://medium.com/@karenovna.ak/training-a-single-perceptron-405026d61f4b">Training a Single Perceptron</a></p><ul><li>A large portion of this content was adopted from <a href="http://page.mi.fu-berlin.de/rojas/neural/index.html.html">Rojas, Raul (1996):<em> Neural Networks: A Systematic Introduction, Ch 3</em></a><em> and from lecture notes of Dr. M. Fleischer — professor at Johns Hopkins University, Neural Networks Introduction graduate course.</em></li></ul><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxBP_WV7LI6zc-zdUkNqQ.png" /></a></figure><p>📝 Read this story later in <a href="https://blog.usejournal.com/r/?url=https%3A%2F%2Fusejournal.com%2F%3Futm_source%3Dmedium.com%26utm_medium%3Dnoteworthy_blog%26utm_campaign%3Dtech%26utm_content%3Dguest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://blog.usejournal.com/r/?url=https%3A%2F%2Fusejournal.com%2Fnewsletter%2Fnoteworthy-in-tech%2F%3Futm_source%3Dmedium.com%26utm_medium%3Dnoteworthy_blog%26utm_campaign%3Dtech%26utm_content%3Dguest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a428d3f451d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part II. Evaluating a Predictive Model: Cross Validation and Bias and Variance Tradeoff]]></title>
            <link>https://medium.com/@karenovna.ak/part-ii-evaluating-a-predictive-model-cross-validation-and-bias-and-variance-tradeoff-9874b836cd2e?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9874b836cd2e</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[model]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Sun, 14 Apr 2019 03:51:16 GMT</pubDate>
            <atom:updated>2019-06-09T08:06:57.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part II. Model Evaluation: Cross Validation, Bias and Variance Tradeoff and How to Diagnose Overfitting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZpG5TQh1EOQRzW-BV0Qtg.png" /></figure><p>In my previous <a href="https://medium.com/@karenovna.ak/build-and-evaluate-a-predictive-model-with-scikit-learn-a-walkthrough-for-beginners-7fcea2e5ff2">post</a>, I laid out a conceptual framework for building and evaluating a simple predictive model. I discussed the need for doing a train-test split and retrieved the training and testing scores using the R-squared value as an evaluation metric.</p><p><a href="https://medium.com/@karenovna.ak/build-and-evaluate-a-predictive-model-with-scikit-learn-a-walkthrough-for-beginners-7fcea2e5ff2">Build and Evaluate a Predictive Model with scikit-learn: A Walkthrough for Beginners</a></p><p>But there are some limitations with a simple train-test split which prevent us from getting a reliable understanding on how well the model will generalize to unseen data. In this post I will discuss these limitations and will introduce a remedy — cross validation. I will also discuss the bias and variance tradeoff and will dive deeper into what it means to evaluate a model.</p><h4>Limitations of a Simple Train-test Split</h4><p>Imagine a scenario in which a random train-test split just happens to result in most of the outliers in the train set. In this case, our model will train on data full of outliers, meaning, it will train on a sample that is not representing the true population well. When we run this model on our test set, or deploy it on any out of sample data, it is likely that its predictions will be very poor. This generalizes to the notion that the scores we use to evaluate the model can be highly variable depending on which observations end up being in the train set and which observations end up being in the test set. Consider the graph below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xCUT9JVIvZK4J97fYrFdg.png" /><figcaption>This figure is borrowed from <em>An Introduction to Statistical Learning with Applications in R </em>written by G. James, D. Witten, T. Hastie and R. Tibshirani (figure 5.2, pg. 178).</figcaption></figure><p>The x-axis represents the degree of polynomial included in the model (the equation for a simple linear regression is of degree 1 but if we include quadratic terms in the equation then we have an equation of degree 2 and so on). The y axis represents the mean squared error (MSE) scores. <strong><em>Note:</em></strong><em> In this case, the evaluation metric is the MSE and not the R-squared value.</em> The overall graph depicts ten different MSE scores over models with different degrees of polynomial from 10 random train-test splits. While the overall trends among all the curves appear to share the same shape, indicating that the MSE is lowest for a model which has quadratic terms in it, the height of the curves is highly variable. This confirms that different train-test splits will result in different MSEs. So when we do a single train-test split, we only get one score among many others that we could potentially get if we were to do many random train test splits. This doesn’t tell us much about the overall model performance.</p><p>Now consider another point. When we do a train-test split, depending on the size of the data, we often have to reserve about 30–40% of the data for the test set in order to have enough observations in the test set to evaluate predictions on. This is a significantly large subset of the data that is not being used to train the model. This is not ideal because training a model on few observations generally means that the model is not going to be very good.</p><blockquote><strong><em>The limitations of a single train-test split:</em></strong></blockquote><blockquote><strong><em>1. The scores for evaluating the model are highly variable depending on the observations that make up in train set and test set from a single train test split.</em></strong></blockquote><blockquote><strong><em>2. Reserving much of the data for a single test set reduces the number of observations we can use to train the model.</em></strong></blockquote><h4><strong>The Remedy — k-Fold Cross Validation</strong></h4><p><strong><em>k-fold cross validation</em></strong> is a resampling method that is essentially a train-test split on steroids: we randomly divide the data into k groups (folds) of equal size. The first group becomes the test set and the remaning k-1 groups combined together become the train set. A model is is trained and built on the train set and is evaluated on the test set with an R_squared score (assuming a linear regression model) much like in a simple train-test split. However, this procedure is repeated k times where each time the train set and the test set end up being different. k models are built and evaluated resulting in k different R_squared scores. The average of these scores is the <strong><em>cross validation score</em></strong>. Here is how to retrieve the cross validation score in scikit-learn:</p><pre><strong>from</strong> <strong>sklearn.model_selection</strong> <strong>import</strong> cross_val_score</pre><pre>cv_score = cross_val_score(model, X, y, cv=5).mean()</pre><p>where <em>model</em> is the instantiated model we want to fit and evaluate, <em>X </em>is the data containing predictor features and <em>y</em> is the target feature we wish to predict.</p><p>The visual example below shows how data is partitioned 4 times in a 4-fold cross validation for which our test set is 25% and the train set is 75% of our data for a given fold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzrwaOsXUH9IfRwYDxpvKw.png" /></figure><p>In a nutshell, cross validation allows us to use one data set available to us as k different samples to train our model on. Every single observation in the dataset eventually ends up being used once in a test set when we cross validate. It’s much like repeating an experiment of building a model k times on k different datasets and then averaging the results.</p><p>This is why the cross validation score is a much more reliable metric in helping us understand how the model can be <em>expected to perform</em> on unseen data. We could not draw such expectations from the train score and the test score resulting from a simple train-test split alone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7JfQzbg62g3uoKWEJXXRIw.png" /><figcaption>This figure borrowed from <em>An Introduction to Statistical Learning with Applications in R </em>written by G. James, D. Witten, T. Hastie and R. Tibshirani (figure 5.4, pg. 180).</figcaption></figure><p>The figure above shows how 10-fold cross validation was run 10 separate times, each with a different random split of the data into ten parts. Each cross validation provides one cross validation score. There are 10 slightly different cross validation error curves, but the curves are not as drastically different as they were in the case of doing 10 different train-test splits. <strong><em>Note:</em></strong><em> In this case, the evaluation metric is the MSE and not the R-squared value. </em>Thus, the results from 10 cross validations are not as highly variable as they were in the case of doing 10 simple train-test splits.</p><p>Additionally, cross validation allows us to reserve less observations for a test set for any given fold, and therefore more observations are used in training the model.</p><blockquote><strong><em>Cross validation score gives us a more reliable and general insight on how the model is expected to perform on out of sample data.</em></strong></blockquote><h4>Variance</h4><p>So far the term ‘variability’ or ‘variance’ has come up a couple of times. Actually, this is a very important term in model evaluation and is closely tied with the notion of bias. Have you ever heard the aphorism <em>“All models are wrong but some are useful?”</em> A model is a mathematical function which is a simplified representation of some phenomenon or a process that’s captured in our data. A good model is one that has just the right amount of complexity: it is simple enough that it excludes all unnecessary and irrelevant details we don’t care about, but it’s complex enough to accurately represent the thing which we wish to model.</p><p>Let’s say we want to build a linear regression model and we have 100 predictor features in our data that we can use to train the model. Some features are good predictors for our target. They provide the <strong><em>signal</em></strong> in the data. Their relationship to the target is the function that we wish to capture with the model.</p><p>However, it’s likely that among all those 100 features, many of them are not really useful or relevant at all. They don’t predict the target feature. Such features are just additional information that happens to be in our data and they add <strong><em>noise.</em></strong></p><p>If we were to include all 100 features to train and build a model, the model would use all of them without any discrimination between relevant and irrelevant features. It would not differentiate between signal and noise but rather it would fit itself on everything that’s provided to it in the train set.</p><p>When we have too many features, the model is prone to <strong><em>overfitting</em></strong> — the phenomenon in which a predictive model fits itself to noise in the data. Models that overfit are too <strong>complex</strong>. They tend to perform really well on training set because the large number of features provides more information for the model to train on, but they fail to generalize well on out of sample data. It’s as if the model is customized for the observations in the train set. Such a model is known to have <strong><em>high variance</em></strong>. If we were to train a high variance model on a different set of observations, then it would likely end up being a very different model.</p><blockquote><strong><em>Variance refers to the amount by which the predictions of a model would change if the model was trained using a different train set.</em></strong></blockquote><h4>Bias</h4><p>On the other hand, if we pass too few predictor features to our model and neglect including some that are actually relevant for predicting the target, then we are risking a model that’s too simple. Such a model is likely to be insufficiently complex to capture the signal in our data and in general ends up being just an inaccurate, bad model. In this case we say that the model has <strong><em>high bias.</em></strong> A biased model is also known to be <strong><em>underfit</em></strong>.</p><blockquote><strong><em>Bias refers to the error that is introduced by approximating a real-life comlex problem by a much simpler model that doesn’t contain all the relevant information necessary to represent the underlying signal in the data.</em></strong></blockquote><p>Here is a useful visualization:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObyRSEgKTSUsSuRhQvZPlg.png" /><figcaption><a href="http://storybydata.com/datacated-weekly/the-bias-and-variance-tradeoff/">Source</a></figcaption></figure><blockquote>As a general rule, more complex models will have high variance, and models that are too simple will suffer from high bias.</blockquote><h4>Bias and Variance Tradeoff</h4><p>Both bias and variance contribute to errors the model makes on unseen data therefore affecting its generalizability. Our objective is to minimize both. This poses another challenge because reducing variance increases bias and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TF6hoU_PBqJf5tQT2qjtdA.png" /><figcaption><a href="http://scott.fortmann-roe.com/docs/BiasVariance.html">Source</a></figcaption></figure><p>The above figure represents the relationship between error and the bias and variance tradeoff. The best model is the one which achieves lowest error rate by minimizing bias and variance simultaneously. This is the model with just the right complexity represented by the dashed vertical line. Such a model will have good accuracy scores on train data but also on test data which means that it will be generalizable.</p><h4><strong>How Does This All Relate to Cross Validation?</strong></h4><p>It turns out that we can use cross validation score together with train score and test score obtained from a simple train-test split to diagnose bias and variance issues with a model. Here is a table that summarizes different scenarios of these scores which assumes accuracy scores as evaluation metrics:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*S8twsjEIDSmRj2YtW9Urig.png" /></figure><p>If we were to choose an evaluation metric for error, rather than accuracy to assess the performance of our model, then the ‘high’ and the ‘low’ in the table would be reversed.</p><blockquote><strong><em>It’s important to remember the evaluation metric we choose: if we evaluate a model on accuracy, then the goal is to maximize it. If we evaluate a model on error, then the goal is to minimize it.</em></strong></blockquote><h4>Baseline Accuracy</h4><p>One other component that should be accounted for in model evaluation is the baseline score. A <strong><em>baseline score</em></strong> is the accuracy score we obtain from a <strong><em>null model</em></strong> — a model that always predicts the mean in case of a regression problem, and the majority class in case of a classification problem. Such a model has no predictive power. Prior to any model evaluation, a baseline score should always be obtained to give us an idea of what the lowest bar for our model is. The train score, test score and cross validation score must all beat the baseline score in order for us to be confident that the model has any predictive power at all. If these scores are roughly about the same as the baseline score, then we can certainly know that the model is no good and we should just discard it.</p><h4>Let’s Review</h4><p>A simple train-test split has certain limitations and we can use cross validation to remedy these. Cross validation gives us a score which more reliably tells us how well we can expect our model to perform on out of sample data. Using the cross validation score in combination with train score and test score can be very informative on diagnosing bias and variance issues our model may have. A good generalizable model will have high scores in all three cases (cross validation, train and test scores) which is an indication that we have achieved that sweet spot that balances and minimizes the bias and the variance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9874b836cd2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and Evaluate a Predictive Model with scikit-learn: A Walkthrough for Beginners]]></title>
            <link>https://medium.com/@karenovna.ak/build-and-evaluate-a-predictive-model-with-scikit-learn-a-walkthrough-for-beginners-7fcea2e5ff2?source=rss-33d6a06bcd2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fcea2e5ff2</guid>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[predictive-modeling]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Ani Karenovna K]]></dc:creator>
            <pubDate>Thu, 28 Mar 2019 04:22:59 GMT</pubDate>
            <atom:updated>2020-06-17T16:39:33.292Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part I. Build and Evaluate a Predictive Model with scikit-learn: A Walkthrough for Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6JAV0eqWYENT2YJ2RWzkqg.png" /></figure><p>For those new to data science, phrases like predictive modeling and model evaluation may seem daunting. Of course depending on the model, these terms may mean less or more complex things. But in this post, I will attempt to disillusion the perceived complexity of these terms with a guided walkthrough of building a <strong><em>Simple Linear Regression (SLR) </em></strong>and providing an appetizer for evaluating the model with scikit-learn. My goal is to leave you both with a conceptual and practical understanding of what predictive modeling is and how to do it. The variable names used here may seem confusing so I highly advise referring to the images in this post as they are designed to help in visualizing the processes described and what all the variables are.</p><h4>So What is A Prediction Model?</h4><p>A prediction model is a function which takes a feature or a set of features <strong>X </strong>as input and outputs some approximation of feature <strong>y</strong> which we wish to predict (<em>y</em> is often referred to as the target feature). This output is an approximation because no model is perfect and therefore our function can only <strong><em>predict y </em></strong>within some<strong><em> </em></strong>error of what the <strong><em>true y</em></strong> is. Let’s refer to our predicted approximations of y as <strong><em>y_pred</em></strong> and the true values of y as <strong><em>y_true</em></strong>.</p><h4><strong>Evaluating a Prediction Model: the What, the Why and the How</strong></h4><p>In order to evaluate how well a prediction model is performing we need a way of measuring how far or close its predictions of y are from true y. Needless to say, this means that we must have both <strong><em>y_pred</em></strong> and <strong><em>y_true</em></strong>. Why do we care to evaluate our model? Well, because we want to understand whether we can rely on it to make accurate predictions about some future y using new data that it has not yet seen.</p><p>For example, in a SLR setting, you can evaluate how good the predictions are by looking at the <strong><em>mean squared error (MSE) . </em></strong>This is a metric which takes all the errors our model produced, squares them and then takes the mean of those squared errors. In other words, MSE measures how far our <strong><em>y_pred </em></strong>deviates from <strong><em>y_true</em></strong><em> </em>on average<strong><em>. </em></strong>There are a variety of metrics we can use and MSE is just one of them.</p><p>Another metric, for example, is the <strong><em>coefficient of determination —</em></strong>the <strong><em>R_squared </em></strong>value<strong><em>.</em></strong> R_squared value measures the amount of variability in the data that is explained by our model as compared to a null model which would simply be always predicting the mean of y. The range for an R_squared value is between 0 and 1. An R_squared value of 0.35, for example, would mean that 35% of the variability in our data is explained by our model. The closer the R_squared value is to 1, the better the model.</p><blockquote><strong><em>Improving the performance of a SLR model comes with the objective to minimize MSE or to have an R_squared value as close to 1 as possible.</em></strong></blockquote><p>To build and evaluate a model, we need to have historical data with which to ‘inform’ our model so it can later make ‘educated’ predictions. By historical data I mean data that includes X and y from the past which we currently have. We feed a subset of this historical data to the model, let it train on it and learn from it. This subset is referred to as <strong><em>training data</em></strong>. We then test our model to see how well it’s performing by computing the MSE or the R_squared value on training data. But the point of modeling here is not to get the optimal MSE or a great R_squared value for our training data — we already know what we want our model to predict because our historical and therefore, training data comes with the true y! Instead…</p><blockquote><strong><em>…we want our model to work really well on ‘future’ data which it has never seen before. This means that we wish to build a model that can be generalizable to new, unseen data.</em></strong></blockquote><p>Generalizability is an important concept for the predictive power of a model and is achieved by balancing out <strong><em>the bias and variance tradeoff </em></strong>which I will discuss in my next post. For now, let’s just focus on building the model and getting the necessary scores we need to evaluate it.</p><h3>Diving Right In…</h3><h4>1. Define X and y</h4><p>Let’s say we have data on the rate of cricket chirps (X) and the average outside temperature in Fahrenheit (y). This is our historical data. Keeping in mind the generalizability concept, our goal is to build a model which will predict the outside temperature in the future assuming we will have new data on the rate of cricket chirps — that is, assuming we will have only some new <em>X, </em>but not y at some point in the future.</p><p>We define our historical X and y in pandas as follows:</p><pre>X = data[[‘chirps per second’]]</pre><pre>y = data[‘temperature (F)’]</pre><p>The double brackets around <em>‘chirps per second’ </em>are<em> </em>there because we will later be ingesting our X and y into scikit-learn. Scikit-learn can take any number of predictor features X and it expects a 2-D array for X which is why we need the double brackets.</p><h4>2. Train-Test Split the Data</h4><p>Next we need to partition our historical data into a train set and a test set. This is because we want to train our model, make it smarter, and then we want to test it later to see how well it’s performing.</p><p>Let’s define some terminology:</p><p><strong><em>Train Set</em></strong> — a subset of our entire historical dataset which is used to train and build the model.</p><p><strong><em>Test Set</em></strong> — a subset of the entire historical dataset which is used after we have trained our model for the purpose of making predictions and evaluating model performance.</p><p>Scikit-learn’s <em>test_train_split</em> method will randomly split our data into train and test subsets.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size = 0.26)</pre><p>It’s important to set the <em>random_state</em> parameter to a fixed value. This will ensure that you will get the same train and test sets every time you do a train-test split on the same dataset.</p><p>The test_size parameter here is set to 0.26. This means that I want my test data to be about 26% of the entire dataset, while the remaining portion will become the train set.</p><p>The picture below shows what the train and test split accomplishes using a random subset of the actual data I use for this example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZR7shgTLvvVqE4JbOBEkSw.png" /></figure><p>Now we’re ready to train and build our model.</p><h4>3. Instantiate the Model</h4><p>First step towards actually building our SLR model is to <strong><em>instantiate </em></strong>it. This creates a blank model object which is much like an empty template ready to be filled with our training data.</p><pre>from sklearn.linear_model import LinearRegression  </pre><pre>slr_model = LinearRegression()</pre><h4>4. Fit the Model on Train Set</h4><p>Next, we feed our train data into the <em>slr_model </em>template and let the model ‘fit itself’ to the training data. This is the step where the model is ‘learning’. What this means is that the template <em>slr_model</em> learns the intricacies of our data and it adjusts itself to it so that when the model sees data like this in the future, it will recognize the most salient patterns in the data and will make its predictions accordingly in a more ‘informed’ way.</p><blockquote><strong><em>Fitting the model requires inclusion of both X and y from our training set.</em></strong></blockquote><p>Thanks to scikit learn, this process is a simple one-liner:</p><pre>slr_model.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihnMFCuVGH9cIBcRcVfC4Q.png" /></figure><p>The picture above illustrates the high-level process of what happens when you fit a model. The equation represents the regression line which fits our data and it has unique slope and intercept values. Now let’s look up the slope and the y-intercept for our model and then view a scatterplot with the actual regression line.</p><pre>slope = slr_model.coef_<br>y_intercept = slr_model.intercept_</pre><pre>--------------------------------------------------------------------</pre><pre>slope = 2.90165464<br>y_intercept = 31.359529272367354</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qS4Xn9btv4UQQGBYybXsTg.png" /></figure><p>Great! We have a working model! Let’s see how well of a fit it is to our data.</p><h4>5. Make Predictions on Train Set</h4><p>In simple terms, the prediction step is equivalent to plugging in X values to our equation from above and calculating the corresponding y values.</p><p>The following code produces predictions <strong><em>y_pred_train</em></strong> on the train set</p><pre>y_pred_train = slr_model.predict(X_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hF45AnH01DBcQcQNx4a5GQ.png" /></figure><h4>6. Evaluate the Fit on Train Set</h4><p>Remember that we have our true y from the train set — <strong><em>y_true_train</em></strong>. We can compare it to <em>y_pred_train</em><strong><em> </em></strong>by making use of the R_squared metric and the MSE metric.</p><pre>from sklearn.metrics import r2_score, mean_squared_error</pre><pre>r2_train = r2_score(y_true_train, y_pred_train)<br>mse_train = mean_squared_error(y_true_train, y_pred_train)</pre><pre>--------------------------------------------------------------------</pre><pre>[Output]:</pre><pre>r2_train = 0.6599654904754202<br>mse_train = 12.744526804119651</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oCblfXLeKSUvwrcyW9M6fQ.png" /></figure><p>The training R_squared value is 0.66. This means that the model we just built explains about 66% of the variability in our data.</p><p>The training MSE is 12.74 which means our predictions on average deviate from the true values of y by about 3.57 degrees of Farenheit. The MSE is the mean <strong><em>squared</em></strong> error, so in order to get the actual error with the same units as our y (deg. Farenheit) we need to take the square root of the MSE.</p><blockquote><strong>It’s critical to understand the purpose of the train set and the test set. </strong>We train and build the model using the train set. We can evaluate the model on the train set to see how well the fit is. But we use the test set to gain insight on how generalizable the model is to future data. We only make predictions on X_test and never ingest y_true_test to the model.</blockquote><blockquote><strong><em>We always want to make sure our model is agnostic to y_test_true because y_test_true represents unseen data.</em></strong></blockquote><h4>7. Make Predictions on Test Set</h4><p>Just like we saw before with predicting on train data, we can do the same on test data:</p><pre>y_pred_test = slr_model.predict(X_test)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*D5t4_79c4_6pvUt2Q5FhXw.png" /></figure><h4>8. Evaluate Performance on Test Set</h4><p>And our test scores are…</p><pre>r2_test = r2_score(y_test, y_pred)<br>mse_test = mean_squared_error(y_test, y_pred)</pre><pre>--------------------------------------------------------------------</pre><pre>[Output]:</pre><pre>r2_test = 0.7728120770684193<br>mse_test = 16.095126545492537</pre><p>The testing scores can be interpreted in the same way as we did the training scores above.</p><p>We now have both our training scores and the testing scores which means we can compare the two. By comparing the performance of the model on train set to that of the test set, we can infer a lot about how good our model really is.</p><p>This is where I’ll stop as this leads to the broader discussion in my next post of how to interpret the relationship between train and test scores, how to do cross validation, and how to deal with the bias and variance tradeoff to achieve the optimal model. Here is a link to the article:</p><p><a href="https://medium.com/@karenovna.ak/part-ii-evaluating-a-predictive-model-cross-validation-and-bias-and-variance-tradeoff-9874b836cd2e">Part II. Evaluating a Predictive Model: Cross Validation and Bias and Variance Tradeoff</a></p><h4>Let’s Review</h4><p>To recap everything we’ve done so far, we built a SLR model, made predictions with it and obtained training and testing scores. Thankfully, with scikit-learn’s help, the steps outlined here are not specific to SLR only and can be applied to other models. Here are the general steps of building an evaluating a predictive model:</p><ol><li>Define X and y</li><li>Train-test-split your data</li><li>Instantiate the model</li><li>Fit the model using X_train and y_train</li><li>Make predictions on train set using X_train (obtain training score)</li><li>Evaluate the model fit on train set</li><li>Make predictions on test set using X_train</li><li>Evaluate the model on test set (obtain testing score)</li></ol><p><a href="https://college.cengage.com/mathematics/brase/understandable_statistics/7e/students/datasets/slr/frames/frame.html"><em>Data Source</em></a><em> . The data used in the example above was augmented via simulation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fcea2e5ff2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>