<?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[Gadictos - Medium]]></title>
        <description><![CDATA[The noblest pleasure is the joy of understanding - Medium]]></description>
        <link>https://medium.com/gadictos?source=rss----2ec62e967886---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Gadictos - Medium</title>
            <link>https://medium.com/gadictos?source=rss----2ec62e967886---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:36:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/gadictos" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Logistic Regression: A Detailed Overview from Scratch]]></title>
            <link>https://medium.com/gadictos/logistic-regression-a-detailed-overview-from-scratch-ad0491f14c3b?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/ad0491f14c3b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Sat, 08 May 2021 11:11:28 GMT</pubDate>
            <atom:updated>2021-06-14T20:20:53.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>Fundamentals of logistic regression and concepts like <strong>maximum likelihood function</strong>, <strong>cross-entropy</strong> are covered briefly</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*njS7QYGrWrvL9GkXIDFfQQ.jpeg" /><figcaption>photo taken from <a href="https://www.knowledgehut.com/blog/data-science/logistic-regression-for-machine-learning">knowledgehut</a></figcaption></figure><p><strong>Logistic regression</strong> is one of the most commonly used algorithms for machine learning and is a building block for <a href="https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12"><strong>neural networks</strong></a>. It is important to understand the fundamentals and maths behind logistic regression. In this post, we will explore the fundamentals of logistic regression, and concepts like <strong>maximum likelihood function</strong>, <strong>cross-entropy/log-likelihood</strong> are covered briefly. In the end, we have provided <strong>codes</strong> for Logistic Regression in Python from <strong>scratch</strong>.</p><p>Previously, we have covered <a href="https://medium.com/gadictos/linear-classifiers-an-introduction-to-classification-786fe27eef83"><strong>linear classifier</strong></a> models and we have described the concept of <a href="https://medium.com/gadictos/linear-classifiers-an-introduction-to-classification-786fe27eef83"><strong>decision boundaries</strong></a>. In linear classifier models, we take some features xᵢ, some random weights wᵢ and calculate the weighted sum. Then we use a simple sign function to determine if the value is positive or negative :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*G1GlfWP2bRbr51bWGHa-EQ.png" /></figure><p>If the value is positive we have got a positive prediction and if the value is negative we have got a negative prediction. But there are problems with these models e.g. numbers like .0000001 and 10 are going to have the same predictions. Another problem is, the model we have used in linear classifiers relies on a simple sign function that gives output depending on the sign of the values and it is not continuous but a discrete value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1a6BhvlVTo5RTuHhNj0Yg.png" /></figure><p>To use gradient descent, our error function needs to be both continuous and differentiable. So, we want to move from discrete predictions to continuous predictions. Also, what if we can define a model in which we can predict and at the same time we can define a confidence metric that will reflect how confident we are about a prediction. Probability can help us do that and using probability we can interpret how confident we are about a prediction.</p><h3>Class Probabilities</h3><p>In logistic regression, we don’t just use discrete predictions like <strong>+1</strong> or <strong>-1</strong>, we actually predict a number generally between <strong>0</strong> and <strong>1</strong> which we will consider as a probability. These probabilities are extremely useful because they give us an indication of how sure we are about the predictions we make. However, a model can not predict correctly every time. But using probability we can actually predict how confident we are about a prediction.</p><p>So, we want to use a continuous error function and we want to keep the predictions in between <strong>0</strong> and <strong>1</strong>. The way we address both of these problems is by changing our step function from a discrete step function to a continuous step function. The function is called the <strong>Sigmoid</strong> function and it is a continuous function that gives output between <strong>0</strong> and <strong>1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*fYGHe_N03zog31P-Enix-g.png" /></figure><p>The graph of the <strong>Sigmoid</strong> function is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tb9hQLadH7Cj76ZwX-DVbg.png" /></figure><p>Now that, we have our function for continuous prediction, we just need an algorithm that will help us find the best model. The best model is the model that gives a higher probability to the events that are more likely to happen. We call the method as <strong>Maximum likelihood</strong> in which we pick the model that gives the existing labels the highest probability. Thus by maximizing probability, we can pick the best possible model.</p><h3>Maximum Likelihood</h3><p>Maximum likelihood is a quite simple but interesting concept. Suppose, we have some probabilities of events <strong>p₁, p₂, …, pₙ</strong>. In order to obtain the probabilities of the whole arrangement, we have to multiply these probabilities <strong>p₁* p₂* …* pₙ</strong>. The bigger the individual probabilities will be the resulting value will get bigger as well. Now, all we need to do is to maximize this resulting probability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*PTQQCY6IzdWN4JPmezf9DQ.png" /></figure><p>In maximum likelihood, we use the <strong>product</strong> of numbers and the product has got some issues. If we have a big data-set with thousands of probabilities and if these probabilities <strong>p₁, p₂, …, pₙ</strong> get really small then the resulting multiplication will become really tiny since the value of the probability is always between <strong>0</strong> and <strong>1</strong>. Also, if we have a product of thousands of numbers and we change one of them the product can change drastically. So, we want to avoid products and one good alternative is to use sums. One easy way to convert products to sums is by using <strong>logarithms</strong> and the concept is called the <strong>cross-entropy</strong> or <strong>log-likelihood</strong>.</p><h3>Log-Likelihood/Cross-Entropy</h3><p>In <strong>cross-entropy/log-likelihood</strong>, we take products and find the logarithms of them. We know:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/1*IczQqPKzoidIgAyild6fYg.png" /></figure><p>So, if we take the logarithm of the multiplication of the probabilities we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*BTmJJHAHLnUWtGoeyK6R-Q.png" /></figure><p>It’s a good solution but there’s a small problem. Since logarithms of numbers between <strong>0</strong> and <strong>1</strong> are always negative and <strong>ln(1) = 0, e</strong>very <strong>ln(pᵢ)</strong> will be a negative number. But if we take the negative of the logarithms of the probabilities we get positive numbers and the concept is called <strong>Cross-Entropy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*VCnQ-5D3OLUmqNPQqGYOvw.png" /></figure><p>What cross-entropy says if we have some events and some corresponding probabilities, how likely those events are going to happen based on the probabilities. If it is very likely then we have a small cross-entropy, if it is unlikely cross-entropy will be large. It is important to notice that, our goal has changed from maximizing the probability to minimizing the cross-entropy. Now, we just need to derive a general formula for cross-entropy.</p><p>Let’s say we are going to do an assignment and our supervisor has suggested three books to look at to get some help. Suppose, the probability of getting something useful from these books are <strong>p₁= 0.9, p₂= 0.7</strong> and <strong>p₃ = 0.2</strong> respectively, and suppose these are all independent events. So, the probability of these events to be happening is <strong>0.9</strong> for the first book, <strong>0.7</strong> for the second book, and <strong>0.8</strong> for <strong>not having</strong> useful content in the third book.</p><p>Notice that, for the third book we are considering probability for <strong>not having</strong> useful content. This is because we are always looking for events that have the <strong>maximum probability</strong> and for the third book probability of not having useful content has got the larger probability. Since cross-entropy is the sum of the negative logarithms of the probabilities,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*TIoxLSb1XrsxMbwz8Q4-2A.png" /></figure><p>Now, let’s there be another variable called <strong>yᵢ</strong> which will be <strong>1</strong> if there is something useful in the book and <strong>0</strong> if it’s not. So, for the first book <strong>y₁= 1</strong>, for the second book <strong>y₂ = 1,</strong> but for the third book <strong>y₃ = 0 </strong>since there’s nothing useful in the third book. Using these pieces of information we can actually modify the cross-entropy formula like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*sQcBNHagHBzYrBUTxIuPJQ.png" /></figure><p>If we look closely, we will notice if there is something useful in the books <strong>yᵢ</strong> will be <strong>1</strong> and the second term will be zero and if there is not something useful then <strong>yᵢ = 0</strong> and the first term becomes zero. That is the beauty of this formula and it really gives the sums of the negatives of the logarithms of the probabilities which we have defined as cross-entropy. If we calculate the cross-entropy of the events:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*C3Ql5QmB9lqgznfAEsGWeQ.png" /></figure><p>which is low since the event is more likely. On the other hand, if we calculate</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*DYkJA5rYFtvjsSXpepLmWg.png" /></figure><p>the cross-entropy is high since the event is not more likely. By convention, we actually use average instead of using the sum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*2fcN_Dv1feUP_sfX-MBm6w.png" /></figure><p>This is our overall equation of the cross-entropy equation. In this example, we only had two classes. Having something useful in the book and not having something useful in the book. When we have more than two classes we use the more general approach called <strong>Multi-Class Cross Entropy</strong>.</p><h3>Multi-Class Cross-Entropy</h3><p>Suppose this time we need to do an assignment and like before our supervisor has suggested looking at three different books. But in this case, we have three different topics: Science, Technology, and Sports. For these cases, we use <strong>Multi-Class Cross Entropy</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*etFAs9m2ZXZNien4FoLwFg.png" /></figure><p>The above formula is actually the same as the one we have used for two classes. So, now that we have our error function we can use the gradient descent algorithm to minimize the function.</p><h3>Gradient Descent</h3><p>Let’s recall that we have<em> </em><strong><em>n</em></strong><em> </em>points labeled <strong>x₁, x₂,…,x</strong>ₙ<strong>. </strong>We know the error function, E and the prediction, <strong>ŷ</strong> is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*4Vw1lBONWtKDrJyDFkuxSg.png" /></figure><p>The derivative of the sigmoid can be derived as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*OaTe3m21f7nFDf8Qp5ZTbQ.png" /></figure><p>Then, we can use the above formula to get the derivative of the prediction:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*3XdO3hRoAWjnJ3YfXFYwYQ.png" /></figure><p>Our main goal is to calculate the gradient of the error term, <strong>E</strong> at a point <strong>x = (x₁, …, xₙ)</strong> given by the partial derivatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*z95mLbqn_XX8mEcAUj8ITg.png" /></figure><p>For simplicity, we’ll actually calculate the derivative of the error that each point produces. The total error, then, is the average of the errors at all the points. First, we will calculate the derivative of the error E at a point <strong>x</strong> with respect to the weight <strong>wⱼ</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*AgypXQKSb3tfhEbmNsqRJw.png" /></figure><p>We can have a similar calculation for the bias term to get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*2Hqq6gIj6bGFJvV6oN5hRA.png" /></figure><p>These derivations actually tell us something very important. For a point with coordinates <strong>(x₁, …, xₙ)</strong>, label <strong>y</strong>, and prediction <strong>ŷ</strong>, the gradient of the error function at that point is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*wq4QhvBwEgDLma-nnFO6Yw.png" /></figure><p>In summary, the gradient can be written as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*qnsa98SnxybNKjlltlHNAA.png" /></figure><h3>Logistic Regression Algorithm</h3><p>We now have all the tools we need to describe the Logistic Regression algorithm. Here is the pseudocode for the Logistic Regression algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*GbaNmWcgvvV6NtcfLA9wog.png" /></figure><p><a href="https://github.com/milon101/Logistic-Regression"><strong>Here we have provided python code for the logistic regression algorithm using our derived algorithm from scratch.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad0491f14c3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/logistic-regression-a-detailed-overview-from-scratch-ad0491f14c3b">Logistic Regression: A Detailed Overview from Scratch</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Descriptive Statistics: A Brief Introduction]]></title>
            <link>https://medium.com/gadictos/descriptive-statistics-a-brief-introduction-921c9fbec84b?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/921c9fbec84b</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Sat, 08 May 2021 11:06:35 GMT</pubDate>
            <atom:updated>2023-03-11T16:23:37.674Z</atom:updated>
            <content:encoded><![CDATA[<h4>Descriptive and summary statistics associated with histogram, boxplot, and scatter plot are covered briefly.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*tOFbY7ud5Zwptajj3MyCWw.jpeg" /></figure><p>Statistics is very important in our day-to-day life and at the core of many data-related applications. There are so many applications of statistics in sectors like data and predictive analytics, machine learning, deep learning, etc. It is really important to understand statistics well in order to understand these high-level concepts. In this post, I will introduce concepts of descriptive statistics with examples and potential use cases.</p><h3>Descriptive Statistics</h3><p><strong>Statistics</strong> is the discipline that concerns data collection, organization, analysis, interpretation, and presentation. So what is data? Data is simply defined as distinct pieces of information that can be in many forms e.g. text, video, databases, spreadsheet, audio, images, etc. In this machine learning era, there are numerous use cases of data. From speech recognition to autonomous driving data has influenced our life like never imagined and statistics play a big role in it. Descriptive statistics is all about describing various features of the data by summarizing the sample of the collected data. Data can be divided into two basic types e.g. <strong><em>quantitative</em></strong> and <strong><em>categorical</em></strong>.</p><h3>Quantitative or Categorical Data</h3><p><strong><em>Quantitative</em></strong> data is the kind of data that contains the numerical value and <strong><em>categorical</em></strong> data contains labeled data. We can do mathematical operations in quantitative data while in categorical data we define a group or set of items. Quantitative data can be divided into two groups, <strong><em>discrete</em></strong> and <strong><em>continuous</em></strong>. Discrete data represents particular countable values. For example, the number of pages in a book, the number of dogs, etc. Continuous data on the other hand are not restricted to defined values but can take any value within a certain range. For example, the age of a child, the amount of rain in a year, etc. Categorical data can also be divided into two groups e.g. <strong><em>nominal</em></strong> and <strong><em>ordinal</em></strong>. Categorical data that can be represented as a ranked order, e.g. grade results of an exam (A+, A, A-) is defined as <strong><em>nominal</em></strong>. If there’s no ranked order in categorical data then it is defined as <strong><em>ordinal</em></strong> data e.g. different accessories. Understanding different data types are important since it enables us to determine which types of analysis are best suited for which type of data. Here we will take a dataset containing 2015 Homicide data in the USA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*0lD9WccRqAbqjvwUT8Lzlw.png" /></figure><p>In this dataset, age is continuous and the number of homicide deaths is discrete data. To describe or analyze both discrete and continuous quantitative data we generally discuss four main aspects of data e.g. <strong><em>measures of center</em></strong>, <strong><em>measures of spread</em></strong>, <strong><em>shape</em></strong>, and <strong><em>outliers</em></strong>.</p><h3>Measures of Center</h3><p>The measures of center, also known as <strong><em>central tendency</em></strong>, are summary statistics that represent the central or the typical value of a dataset. These measures indicate where the most values of a distribution fall and are also referred to as a central location of a distribution. The three most common types of measures of center are:</p><ul><li><strong>Mean</strong></li><li><strong>Mode</strong></li><li><strong>Median</strong></li></ul><h4>Mean</h4><p>In the US homicide dataset, the number of homicide deaths associated with age 21 is 652, 633 for age 22, 653 for age 23, and so on. If we want to know what is the expected number of deaths associated with any given age we generally use mean or average to answer these questions. Mean is defined as the sum of the values divided by the count of the values on our dataset and denoted as <strong><em>x̅</em></strong>. <em>Suppose, we have a set of real-valued data (x</em>₁<em>, x</em>₂<em>, …, x</em>ₙ<em>). Then the sample mean of the data is defined as:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*BnABMugD5mciXS19_x_zvg.png" /></figure><p>For our dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*73Z48f_zLQ1-Yk0VLYczSA.png" /></figure><blockquote>Mean is very important in data science and a common preprocessing step for data analysis is to center a set of data by subtracting its mean. An example of centering the dataset is given below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*5GittC2aGYLWP6VR.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*_1644DOY3oXm3jXF.png" /><figcaption>Before centering (left), After centering (right)</figcaption></figure><p>However, mean is not always the best measure of center. Since mean has the nature of giving a larger or smaller value if one or two values in the dataset get bigger or get smaller. Also, mean can give decimal values for discrete data.</p><h4>Median</h4><p>Mean gives us the average of the dataset and doesn’t always give the center value of the dataset except if the dataset is <strong><em>symmetric</em></strong>. So, we need a measurement that will always give us the center of the dataset. Median does that for us and it has some other advantages over mean.</p><blockquote>Extreme values (outliers) do not affect the median as strongly as they do the mean and it is useful comparing different sets of data since it’s unique and there is only one possible value.</blockquote><p>Median is defined as the middle value of the <strong><em>sorted</em></strong> dataset. Median divides our dataset in a way such that fifty percent of our dataset is less than the median and the other fifty percent is greater than the median. If the number of observations is an odd value then the median is simply the middle value of the observations. For example, if we take the first five values of our given dataset <strong><em>652, 633, 652, 644, 610 </em></strong>then first we need to first order our dataset (ascending in this case) to get <strong><em>610, 633, 644, 652, 652</em></strong>. Then we will choose only the middle value which is <strong><em>644</em></strong> in our case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*0sfJZcKINSq1aZpCPrZc4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*TqQxcvMxSFTgg2_3Q5jd9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*zomFsQLj0SZP2ItRYqQ_Ug.png" /><figcaption>Mean provides the center of the data for symmetric dataset and suffers with extreme values</figcaption></figure><p>For the even number of observations, the median is the mean of the two middle values of our dataset. For example, if we take the first six observations from our above dataset <strong><em>652, 633, 652, 644, 610, 565</em></strong> and order our data to get <strong><em>565, 610, 633, 644, 652, 652</em></strong>. So the median will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*ogsYvbEc_PInhZZMuZMTeQ.png" /></figure><h4>Mode</h4><p>Another popular measure of center is <strong><em>Mode</em></strong> which is defined as the most frequent or common value in the dataset. In our dataset, <strong><em>652, 633, 652, 644, 610, 565</em></strong> we can see <strong><em>652</em></strong> appears twice and most frequent. So, <strong><em>652</em></strong> is the mode here. There can be multiple modes in a dataset. For example, if a dataset contains <strong><em>1, 2, 2, 3, 3, 4</em></strong> then the mode will be <strong><em>2</em></strong> and <strong><em>3</em></strong>. However, if the observations in a dataset contain similar frequencies there is no mode e.g. <strong><em>1, 1, 2, 2, 3, 3, 4, 4</em></strong> have no mode since all observations occur a similar number of times. We generally use mode if the data is categorical e.g. colors, fruits, etc.</p><h3>Measures of Spread</h3><p>Measures of spread are the second aspect of analyzing quantitative data. While the measures of center tell us about the center of a dataset measure of spread is defined as the numerical values that are associated with the spread of the data or how far is each observation in a dataset from one another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*zLlnBOdb3KAJeaif.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*KFCTI6fQ8-dzCMQb.png" /><figcaption>Small spread (left), Large spread (right)</figcaption></figure><p>From the above images, we can see that both have a similar mean, mode, and median which is about 100. But the spread of data is different. In the left image, the data ranges from 90 to 109 while in the right image it ranges from 86 to 115 indicating more spread in data. To measure the spread of data we generally use:</p><ul><li><strong>Range</strong></li><li><strong>Interquartile Range (IQR)</strong></li><li><strong>Standard Deviation</strong></li><li><strong>Variance</strong></li></ul><h4>Five Number Summary</h4><p>One of the most common ways to calculate the spread of data is by looking at the <a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad"><strong><em>five-number summary</em></strong> </a>of data. The five-number summary consists of five values:</p><ul><li><strong>Maximum</strong></li><li><strong>Third Quartile (Q3)</strong></li><li><strong>Second Quartile/Median (Q2)</strong></li><li><strong>First Quartile (Q1)</strong></li><li><strong>Minimum</strong></li></ul><p>To calculate the five-number summary we need to order our data first and let’s say we put our data in ascending order. After ordering, maximum and minimum values are the highest and lowest values of the dataset respectively. The second quartile (Q2) is the middle value or the median of the dataset. The first quartile (Q1) value is the median of the data that is on the left side of the second quartile while the third quartile (Q3) value is the median of the data that is on the right side of the second quartile.</p><p>For example, suppose we have a dataset containing 5, 2, 8, 1, 3, 6, 8. To get the five-number summary, we will first order our data, ascending in this case e.g. 1, 2, 3, 5, 6, 8, 8. Then, the minimum value will be 1 and the maximum will be 8. The second quartile (Q2) or median will be 5. Now, the first quartile will be the median of the data that is on the left side of the second quartile, and for our case, it will be 2. Finally, the third quartile will be the median of data that is on the right side of the second quartile, and in our case, it will be 8.</p><p>The best way to visualize the five-number summary is by using a <a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad">boxplot</a>. Suppose, we have a distribution of the age of NBA players in the 2013–14 session. If we plot the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*RlXkc5VGL3SGBxaS.png" /><figcaption>Boxplots help us to visualize five number summary</figcaption></figure><p>From the box plot, we can easily visualize the five-number summary. Minimum and Maximum are located at the far left and right sides of the whiskers respectively. The first quartile is the far left of the box while the third quartile is the far right of the box. The Median is shown as a line inside the box.</p><h4>Range &amp; Interquartile Range (IQR)</h4><p>After we get the five-number summary getting the range and interquartile range is simple. We calculate the range as the difference between the maximum and minimum values in the dataset. For our dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*a_P4FZttZ7_O7ZlJxA01Bw.png" /></figure><p>Then the interquartile range will be the difference between the third and first quartile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*g2iC-2fzDDsQ8Vrfaebkkw.png" /></figure><h4>Standard Deviation &amp; Variance</h4><p>Previously, we used the five-number summary to understand the spread of the distribution. But what if we want to use only one number instead of using five numbers to compare the spread of the two distributions? The easiest and most common way to do that is by using the standard deviation and variance.</p><blockquote>Standard deviation is defined as the average distance of each observation from its mean. To calculate the standard deviation, we need to calculate the variance first.</blockquote><p>Suppose, we have a dataset containing values of <strong><em>1, 1, 2, 4</em></strong>. If we take the mean we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*7THfhiXICOhiTpq6ABEd2g.png" /></figure><p>If we calculate the sum of the difference between each observation and the mean we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*gbS33vLpOY67m9sVhdcbfw.png" /></figure><p>Now, calculating the mean we get <strong><em>0</em></strong> indicating there’s no spread in the data. But that’s not true and to stop this we will make all the distances positive by squaring them. And, we can calculate the average squared distance of each observation from the mean of the dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*zT9kqo-2aTCVY_YBvHPHEw.png" /></figure><p>This average value is called variance and it is defined as the average of the squared difference of each observation from the mean. To get the standard deviation, we simply take the square root of the variance. In our dataset, we calculate the variance of 1.5 and the standard deviation of 1.22, respectively. So, Standard deviation is defined as the root mean square (r.m.s) deviation from the average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*jSD9nL_2kgrAbJMJhM2J_w.png" /></figure><h3>Shape</h3><p>The <strong>shape</strong> of the distributions helps us get an insight into measures of center and spread. Looking at the histogram we can easily identify the shape of the data and from that, we can extract valuable information. Generally, there can be three different shapes of our data, e.g.</p><ul><li><strong>Symmetric</strong></li><li><strong>Left Skewed</strong></li><li><strong>Right Skewed</strong></li></ul><blockquote>Distributions, where we can draw a line in the middle and right side mirrors the left side are called symmetric distributions. One common example is normal distribution also known as the bell curve.</blockquote><p>For a symmetric distribution, generally <strong><em>mean = median = mode, </em></strong>and mode is the tallest bar in our histogram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*jCt-w15HrIEaUMr9.png" /></figure><p>For skewed distribution mean is pulled by the tail of the distribution where the median stays close to the mode. Histograms that have the shorter bins on the right and taller bins on the left are called right-skewed shapes. For right-skewed distribution <strong><em>mean &gt; median. </em></strong>We can also easily visualize the skewed distribution in the boxplot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*D2url1sGJtWXYqCk.png" /></figure><p>Histograms that have shorter bins on the left and taller bins on the right are called left-skewed. In the left-skewed histogram <strong><em>mean &lt; median</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*sQhA8DdYyK4FBuMU.png" /></figure><h3>Outliers</h3><p>In simple terms, <a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad"><strong>outliers</strong></a> are the points that fall very far from the rest of the data points and outliers can have a big impact on our analysis. For example, if we have a dataset containing values 10, 11, 14, 15, and 120 then the mean will be 34 which is misleading since most of our data points are actually much less than that.</p><blockquote>Outlier doesn’t affect the median or mode. An outlier can also be useful for retrieving useful data. For example, to identify medical practitioners who under- or over-utilize specific procedures or medical equipment, such as an x-ray instrument.</blockquote><p>We can easily visualize outliers by creating a quick plot e.g. scatter plot, box plot, histogram, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*PY7p6rievcWB0q20.png" /><figcaption>Detecting outliers using Scatter Plot</figcaption></figure><p>From the above scatter plot, we can easily visualize an outlier that is far from the other data points. In the <a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad"><strong>box plot</strong></a>, an outlier is defined as a data point that is located outside the whiskers of the box plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*b-C_aWQPT9d0N3Sq.png" /></figure><p>If data follows a normal distribution and there’s no outlier in the data then the mean and standard deviation are sufficient to describe the data. On the other hand, if the data is skewed or if there are outliers in the data, using the five-number summary values is often a better measure than the mean and standard deviation. More information on the outlier detection methods can be found <a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad"><strong>here</strong></a>.</p><h3>Conclusion</h3><p>In this article, we have covered the basics of descriptive statistics. We have explained different parts of Measures of Center, Measures of Spread, Measures of Shape, and Outliers. We have also covered how to understand data using histograms and boxplots. In the next post, we will explain the concepts of outliers with different methods to detect and remove outliers.</p><p><em>Originally published at </em><a href="https://gadictos.com/dstat/"><em>https://gadictos.com</em></a><em> on July 10, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=921c9fbec84b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/descriptive-statistics-a-brief-introduction-921c9fbec84b">Descriptive Statistics: A Brief Introduction</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Outlier Detection: A Comprehensive overview of different methods]]></title>
            <link>https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/49c18304bfad</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Sat, 08 May 2021 11:01:06 GMT</pubDate>
            <atom:updated>2023-03-11T16:27:40.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xy89JzLoBXGGgZRFGXBBmg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@will_myers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Will Myers</a> on <a href="https://unsplash.com/s/photos/outliers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Mathematical and statistical background of Various outlier detection methods with a detailed comparison between the use cases</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xy89JzLoBXGGgZRFGXBBmg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@will_myers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Will Myers</a> on <a href="https://unsplash.com/s/photos/outliers?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Most real-world data sets have outliers that have unusually small or big values than the typical values of the data set. Outliers can have a negative impact on data analysis if not detected correctly and also outliers can reveal significant information and characteristics of data. There are several methods to detect an outlier in the data set. It is important to understand the characteristics of these methods properly since they might be quite powerful with large normal data but it is problematic to apply them to nonnormal data or small sample sizes without proper knowledge of their characteristics. In this article, we will discuss different outlier detection methods and how to apply them properly in the data set.</p><h3>Outlier</h3><p>An <em>outlier</em> is an observation that lies at an unusual distance from other observations in a random sample of a population. There’s actually no specific way to define the unusual distance and it depends on the datasets, use cases, and applications. Generally, the person who works with data defines what should be the unusual distance. Outliers can be caused by many reasons e.g. data entry mistakes, taking data from different populations, wrong measurements, etc. To see the impact of an outlier we can take a simple data set <strong><em>1,2,3,4,5,6,7,8,9 </em></strong>and explore the various <a href="https://medium.com/gadictos/dstat-fc8a9ae0a559"><strong><em>statistics</em></strong></a> of this data set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*BIdVJzu2ENlx1bZxPLTubg.png" /></figure><p>Now, if we change the last observation from <strong><em>9</em></strong> to <strong><em>99,</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*8C-ExYpGWJoNfqdcMN98QQ.png" /></figure><p>As we can see, the mean and <a href="https://medium.com/gadictos/dstat-fc8a9ae0a559"><strong><em>variance</em></strong></a> have become much bigger due to one value got bigger while the median remains the same. Also, the <strong><em>95%</em></strong> confidence interval has become wider. Due to this one data point, we can get the wrong insight about the whole dataset and it can affect our analysis.</p><h3>Outlier Detection Methods</h3><p>Outliers can be <strong>univariate</strong>, one variable, or <strong>multivariate</strong>, more than one variable, as well. There are two types of outlier detection methods e.g. <strong>formal tests</strong> and <strong>informal tests</strong>. Formal tests are also known as tests of discordancy while informal tests are known as outlier labeling methods.</p><h3>Standard Deviation Method</h3><p>One of the simplest and classical ways of screening outliers in the data set is by using the <a href="https://medium.com/gadictos/dstat-fc8a9ae0a559"><strong><em>standard deviation</em></strong></a> method. We can define an interval with mean, <strong><em>x̅ </em></strong>as a center and <strong><em>x̅ — 2SD</em></strong>, <strong><em>x̅ + 2SD</em></strong> being two endpoints respectively. This is called the <strong><em>2SD</em></strong> method. Observations that fall outside the interval are defined as outliers. Generally, we use <strong><em>3SD</em></strong> by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*eeoDcOKFvALm5HN8gnmpDA.png" /></figure><p>According to the Chebyshev inequality, if a random variable <strong><em>X</em></strong> with mean <strong><em>μ </em></strong>and variance <strong><em>σ²</em></strong> exists, then for any <strong><em>k&gt;0</em></strong>,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*46kC_piNOCYL0vy4DePhIA.png" /></figure><p>From this inequality, we can say that at least <strong><em>1 — (1/k²) </em></strong>proportion of<strong><em> total </em></strong>data must fall within the <strong><em>k</em></strong> standard deviation of mean e.g. about<strong><em> 75%</em></strong>, <strong><em>89%</em></strong>, and <strong><em>94%</em></strong> of the total data are within <strong><em>2</em></strong>, <strong><em>3</em></strong>, and<strong><em> 4</em></strong> standard deviations of the mean, respectively. This theorem is true for any data in any distribution. Now, let’s look at an example data set <strong><em>X</em></strong> to explain this method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*H6O1xFKYa0kze8TD67iBeA.png" /></figure><p>The mean for this data set <strong><em>x̅ = 14.53</em></strong> and <strong><em>SD = 14.45</em></strong>. If we calculate the interval for the <strong><em>2SD</em></strong> method we get an interval <strong><em>(-14.37, 43.43)</em></strong>. We have detected <strong><em>45</em></strong> and <strong><em>55</em></strong> as outliers. But if we take an interval for 3SD we get <strong><em>(-28.82, 57.88)</em></strong> that doesn’t detect any outliers. The drawback of this method is, standard deviations are dependent on the mean and mean can be affected by outliers. If the outlier is big it can affect the Standard Deviations.</p><h3>Z-score</h3><p>One of the common tools in all of the statistics is <strong><em>Z-score</em></strong>. Z-score can be defined as the number of standard deviation, <strong><em>σ</em></strong> a certain data point is, below or above, from the mean, <strong><em>x̅</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/402/1*251TpaLIebUY7KKralak-A.png" /></figure><p>In the <strong><em>SD</em></strong> method, we have formed an interval <strong><em>x̅ — 2SD</em></strong>, <strong><em>x̅ + 2SD</em></strong>. In the Z-score method, we take the difference from the observation and mean and divide it with the standard deviation to find out the number of standard deviations is equivalent to the difference. For any observation, if the absolute value of the Z-score exceeds <strong><em>3</em></strong> then that observation is considered as outliers. If we look closely Z-score formula is actually the same as the 3SD method. The possible maximum Z-score is dependent on the sample size and computed as <strong><em>(n-1)/√n</em></strong> for a sample size of <strong><em>n</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*z0olTs4CdmDldAs3CdQYOg.png" /></figure><p>For case 1, with all of the observations included even though <strong><em>45</em></strong> and<strong><em> 55</em></strong> are outliers but Z-score for no observation exceeds the absolute value of <strong><em>3</em></strong>. For case 2, when we have excluded <strong><em>55</em></strong>, the most extreme value, we have detected <strong><em>45</em></strong> as an outlier. This is because multiple extreme values have inflated standard deviation.</p><h3>Modified Z-score Method</h3><p>In the Z-score method, we have used two estimators, the sample mean and standard deviation, that can be affected by a single or multiple extreme values. To avoid these issues we use the median and the Median Absolute Deviation in the modified Z-score method. The modified Z-score <strong><em>Mᵢ</em></strong> is computed as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*nh1E-gA_EeJvNuTib8KEHg.png" /></figure><p>To find out MAD let’s take a set of numbers: <strong><em>1,2,3,4,5</em></strong>. The median will be <strong><em>3</em></strong>. Now, we will subtract the median from each x-value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*vEF2KRwXA2lgRtmTl6J9kg.png" /></figure><p>We consider an observation as an outlier if <strong><em>|Mᵢ|&gt;3.5</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*xKYGIj7dC0LnnO5bXtIzow.png" /></figure><p>Here a comparison of the Z-score method and modified Z-score is presented on the previous data set. We can notice that even though the Z-score method is failed but using modified Z-score, we have detected <strong><em>45</em></strong> and <strong><em>55</em></strong> as outliers. This is because the modified Z-score is less sensitive to extreme values.</p><h3>MADₑ Method</h3><p>The <strong><em>MADₑ</em></strong> method is similar to the SD method but it uses median and Median Absolute Deviation (MAD), instead of mean and standard deviation. <strong><em>MADₑ</em></strong> method is defined as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*YnQrcBQ75r6VA1DuTP69KQ.png" /></figure><p>After scaling the MAD value by a factor of <strong><em>1.483</em></strong>, it is similar to the standard deviation in a normal distribution. In our dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nsx7B4g-45UTKxsIJkvffg.png" /></figure><h3>Tukey’s Boxplot Method</h3><p>Tukey’s <a href="https://medium.com/gadictos/dstat-fc8a9ae0a559"><strong><em>boxplot</em></strong></a><strong><em> </em></strong>method is a well known simple graphical method to find out five-number summary and outliers in univariate data. This method is less sensitive than previous methods since it doesn’t use sample mean and variance but quartiles instead. From the five-number summary, we first get the value of <strong><em>Q1</em></strong> and <strong><em>Q3</em></strong> and from that, we get the interquartile range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*4ogQ-o2EZjd7j1tOOBDIfQ.png" /></figure><p>Using this we define an interval and any value outside this interval will be defined as outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*DsOVq1RcrhY1Q3W1CXVcPQ.png" /></figure><p>Jhon Tukey proposed that <strong><em>k = 1.5</em></strong> indicates an outlier where <strong><em>k = 3.0</em></strong> indicates that the data is far away. There is no statistical basis for which Tukey uses <strong><em>1.5</em></strong> for inner and <strong><em>3</em></strong> for outer fences. For our example dataset,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*NywZvBcn38WflT-RR1SE5A.png" /></figure><p>So the defined interval according to Tukey will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*MLBEbB0HU9CtMJPg8biFiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*NzZCcC-2RT_aovlg.png" /></figure><p>We can see the lowest value from our data set that falls in this interval is <strong><em>3</em></strong> and the largest value is <strong><em>15.00</em></strong> while <strong><em>45</em></strong> and <strong><em>55</em></strong> are detected as outliers.</p><h3>Carling Median Rule</h3><p>The median rule was introduced by Carling and it actually a substitution method for Tukey’s method where quartiles are substituted by median and a different scale is used. The method was defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*qAAAFiOYcGIVHlQu8uDBcQ.png" /></figure><h3>Conclusion</h3><p>In this article, we have seen different outlier detection methods with their strengths and weaknesses. We have also seen the statistical and mathematical backgrounds behind the methods. Outliers can play a very crucial and significant role in data analysis. These methods can help us detect and remove outliers efficiently.</p><p><em>Originally published at </em><a href="https://gadictos.com/outliers/"><em>https://gadictos.com</em></a><em> on July 23, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49c18304bfad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/outlier-detection-a-comprehensive-overview-of-different-methods-49c18304bfad">Outlier Detection: A Comprehensive overview of different methods</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimization Algorithms Around the World]]></title>
            <link>https://medium.com/gadictos/optimization-algorithms-around-the-world-4a348be0ea9?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/4a348be0ea9</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Sat, 08 May 2021 10:55:36 GMT</pubDate>
            <atom:updated>2023-03-11T17:40:11.083Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3gS47fCy8xxvn1p5.jpeg" /></figure><h4>Key concepts and mathematical foundations behind the popular optimization algorithms</h4><p>In this era, everything is influenced by Artificial Intelligence, Machine Learning, and deep learning. Nowadays it is common to use very big datasets and we need fast and efficient optimization algorithms to get the leverage of this big amount of data. Training <a href="https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12"><strong>Neural Networks</strong></a> is generally much harder than the other optimization problems in deep learning. A good optimization algorithm is easy to implement and faster at the same time. In this post, we will explain the mathematical foundations behind the most common and effective optimization algorithms for <a href="https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12"><strong>neural networks</strong>.</a></p><p>We will start with the gradient descent algorithm which is the most basic and useful optimization algorithm for neural networks. Then we will explain the concept of mini-batch and Stochastic Gradient Descent (SGD) which is just a modification of Gradient Descent. After that, we will introduce the concept of momentum which is the core concept of many modern optimization algorithms. Finally, we will derive the mathematical concepts of RMSProp and Adam Optimization which are two highly efficient algorithms.</p><h3>Gradient Descent</h3><p><a href="https://en.wikipedia.org/wiki/Gradient_descent#:~:text=Gradient%20descent%20is%20a%20first,function%20at%20the%20current%20point."><strong>Gradient descent</strong></a> is a mathematical concept of a first-order iterative optimization algorithm for finding a local minimum of a differentiable function. In a neural network, this differentiable function is called the loss function or cost function. Suppose we want to solve a classification problem using neural networks. For simplicity, suppose the neural network contains a single hidden layer only.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*9r5uzFS9lUMd07jlD8uEOA.png" /></figure><p>Suppose, we have a set of inputs or features <strong><em>X</em></strong> with associated classification labels <strong><em>Y</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*7h7rFtMVnQKanQmOvufNRw.png" /></figure><p>where x ⁽¹⁾, x⁽²⁾, …, x⁽ᵐ⁾ are different training examples and we have <em>m</em> training examples. Then the output, <strong><em>A</em></strong> will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*EIIt9xdaqlgc4yKwJwq8OA.png" /></figure><p>where <strong><em>a[ˡ]⁽ᵐ⁾</em></strong> denotes the output of different layers of different examples, <em>l</em> denotes the layer number and <em>m</em> denotes the different examples. The weights of this network are initialized with <strong><em>0</em></strong> or randomly.</p><p>Then we will use a loss function <em>E</em> to find the error between the prediction and the real value. Our goal is to minimize this error and make predictions as close as possible to the real values by updating the weights. To measure this error we use a metric known as the loss function. A common loss function is the <strong><em>Sum of Squared Error (SSE)</em></strong> defined as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*KMVmeFYZK7jh6vdl8mSxVQ.png" /></figure><p>where <strong><em>ŷ</em></strong> is the prediction and <strong><em>y</em></strong> is the true value. One thing to notice is that errors are the functions of weights. We have to tune up the weights to alter the network’s prediction which in turn will influence the overall error. Our goal is to find the weights that will minimize the errors and to do that we use <strong><em>gradients</em></strong>. Suppose, we plot the weights in the x-axis and the error (<strong><em>E</em></strong>) in the y-axis to get a curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*tsvUfPJKTcy-dqAPvxvWTg.png" /></figure><p>Here we are showing a simple depiction of the error with one weight. Our goal is to find the weight that minimizes the error. We start with a random weight and step toward the direction of the minimum. The direction is opposite to the gradient or the slope. After taking several steps in that direction eventually, we will be able to reach the minimum of the error function. To update the weights we use</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*v64KzZYsY8J43QWYTGoJWQ.png" /></figure><p>Here <strong><em>η</em></strong> is a constant that is called the learning rate of a neural network. The learning rate is a hyperparameter that needs to be adjusted in the network. Deriving the derivative term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*Xx_86oJc4PmSfPDZvzQa5g.png" /></figure><p>Simplifying the equation by defining another term <strong>𝛿</strong> called the error term</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*PxWTVETulE4DoXWM3t5apw.png" /></figure><h3>Mini-Batch and Stochastic Gradient Descent(SGD)</h3><p>In the gradient descent algorithm, we used all the training examples, this is also known as batch gradient descent. But there are some problems with the batch gradient descent. If the number of training examples is too big it takes longer and requires a lot of memory to compute one single epoch. For example, if we have ten million training examples we have to process all the training examples before taking a single step toward the minimum. To resolve this issue we use mini-batch gradient descent by splitting the training examples into small chunks called batches and training one batch at a time. Suppose, we have a set of <strong><em>m</em></strong> number of inputs or features <strong><em>X</em></strong> with associated classification labels <strong><em>Y</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*pXLg9bJPlExoB_EXzcP-Zw.png" /></figure><p>In mini-batch gradient descent, instead of processing all the training examples together, we split them into small batches e.g. 1000 training examples each.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*iK9WjTQoZcxzbCCu_w4J3Q.png" /></figure><p>For simplicity, we can denote mini-batches as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*OS1TF-wnEU6cLKg-SlZ7Cw.png" /></figure><p>The training process is now similar to batch gradient descent. We will pass the split batches for training and have to update the weights for every single batch. The forward propagation and loss function for mini-batch gradient descent will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*sugjEmNV8NwkrtxGSnFDAA.png" /></figure><p>Like before, we can define the error term <strong>𝛿</strong> for simplification and write the equations as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*MnrjkTKn-dZzum_IzJjCWw.png" /></figure><p>When the mini-batch size is <strong><em>1</em></strong> the method is called stochastic gradient descent.</p><ul><li>If <strong><em>t=N</em></strong>, Batch Gradient Descent</li><li>If <strong><em>1&lt;t&lt;N</em></strong>, Mini-Batch Gradient Descent</li><li>If <strong><em>t=1</em></strong>, the Stochastic Gradient Descent</li></ul><h3>Gradient Descent With Momentum</h3><p>Gradient descent is a very basic and fundamental optimization algorithm and has some problems. While converging to the minimum gradient descent generally oscillates up and down direction and takes a lot of steps. These oscillations make gradient descent a lot slower preventing us to use a larger learning rate. Another big problem is getting stuck in a local minimum instead of a global minimum. Gradient descent with momentum helps to address these issues. In this method, we calculate an exponentially weighted average of our gradients and use that to update our weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*LnruyV4tgTaf8xdR1fdJIA.png" /></figure><p>Suppose, we are trying to optimize a cost function that has contours like the above and the red dot denotes the position of the local optima. Starting gradient descent from the first point we reach the second position after one iteration and after another iteration, we reach the third position, and so on. With each iteration, we move closer to the local optima. If we look closely we can see there are two types of motions, e.g. horizontal and vertical. We can see that there are up and down oscillations in a vertical direction. Due to these oscillations, it takes longer to reach the optima. Also, due to these oscillations, we can not use a bigger learning rate since it may diverge for a bigger learning rate.</p><p>In this method, we use an exponentially weighted average which in simple words is just taking previous values into account while updating the weights. Previously, to update weights we used</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*fuQ3jd_b440MofLlZgCVBQ.png" /></figure><p>In the momentum method, we use exponentially weighted averages of <strong><em>∆w₁</em></strong> and <strong><em>∆w₂</em></strong> and denote it <strong><em>V∆ᵥᵥ₁</em></strong> and <strong><em>V∆ᵥᵥ₂ </em></strong>respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*bW__MxDJhpNfmB1IiRMNWw.png" /></figure><p>Here <strong>β₁</strong> is a hyperparameter that balances values between the previous and the current values and ranges from [0,1]. After calculating the exponentially weighted averages we will update our parameters using these averages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*SC5-gLLlApOFIGeA61aeew.png" /></figure><p>The intuition behind this method is quite simple. When we are taking the exponential average of the previous values the up and down oscillations cancel out each other and the vertical motion gets closer to zero. But in the horizontal direction, all the gradients are pointing in the same direction. So it doesn’t slow down in the horizontal direction after adding up the previous values.</p><h3>RMSProp</h3><p>Root Mean Square Prop or RMSProp is another optimization algorithm that is quite similar to the gradient descent with momentum algorithm. Like previously, suppose that we are trying to optimize a cost function that has contours like below and the red dot denotes the position of the local optima. We can see that there are up and down oscillations in the vertical direction. Due to these oscillations, it takes longer to reach the optima. Also, due to these oscillations, we can not use a bigger learning rate since it may diverge for a bigger learning rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*LnruyV4tgTaf8xdR1fdJIA.png" /></figure><p>For simplicity, we are deriving the equations on two-dimensional space with two weights <strong><em>w₁</em></strong> and <strong><em>w₂</em></strong> where <strong><em>w₁</em></strong> is moving in the horizontal direction, and <strong><em>w₂</em></strong> is moving in the vertical direction. In RMSProp, we use exponentially weighted averages like before but here we use the square of the gradients</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*24ze9SFSsg-CoMpebiQ2Ew.png" /></figure><p>After calculating the exponentially weighted averages we will update our parameters using these averages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*ly1nGkChQY39bWslWbmxbQ.png" /></figure><p>Here we use <strong><em>ε</em></strong> for numerical stability and it is generally a very small number, <strong><em>10⁻⁸</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*7gxWAV466KSN68VFg-w8_Q.png" /></figure><p>The intuition behind RMSProp is that in the horizontal direction or in our case in <strong><em>w₁ </em></strong>direction we want optimization to go fast while in the <strong><em>w₂ </em></strong>direction, we want to slow it down to reduce the oscillations. Since we are dividing by <strong><em>S∆ᵥᵥ₁</em></strong> and <strong><em>S∆ᵥᵥ₂</em></strong> we want <strong><em>S∆ᵥᵥ₁</em></strong> to be bigger and <strong><em>S∆ᵥᵥ₂ </em></strong>to be smaller. If we look at the derivatives the angle or slope is much larger in the vertical direction while much smaller in the horizontal direction. So the square of <strong><em>S∆ᵥᵥ₂</em></strong> will be relatively larger than <strong><em>S∆ᵥᵥ₁</em></strong>. In summary, we are dividing the updates in the vertical direction with a much bigger number to reduce the oscillations while dividing the updates in the horizontal direction with a smaller number that has very little impact.</p><h3>Adam Optimization</h3><p>Adam or Adaptive moment estimation algorithm is another very popular optimization algorithm for different types of neural networks. This algorithm is basically using momentum and RMSProp together. Below is the algorithm for the Adam optimization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*5N_URx28wDILlKZQmT7iTg.png" /></figure><h3>Conclusion</h3><p>In this post, we have discussed various optimization algorithms used in deep learning. In these optimization algorithms, there are different hyperparameters as well. Even though there’s no straightforward rule to choose these hyperparameters, we try to follow some common values for <strong><em>β₁</em></strong>, <strong><br><em>β₂</em></strong>, and <strong><em>ε</em></strong>.</p><ul><li>Learning Rate, <strong><em>η</em></strong> — Needs to be tuned while training</li><li><strong><em>β₁</em></strong> — 0.9</li><li><strong><em>β₂</em></strong> — 0.999</li><li><strong><em>ε</em></strong> — <strong><em>10⁻⁸</em></strong></li></ul><p><em>Originally published at </em><a href="https://gadictos.com/optimization-algorithms/"><em>https://gadictos.com</em></a><em> on October 7, 2020.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a348be0ea9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/optimization-algorithms-around-the-world-4a348be0ea9">Optimization Algorithms Around the World</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Overfitting and Regularization in Machine Learning]]></title>
            <link>https://medium.com/gadictos/overfitting-and-regularization-in-machine-learning-e8e60aaf37f9?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/e8e60aaf37f9</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Sat, 08 May 2021 10:46:02 GMT</pubDate>
            <atom:updated>2023-03-11T13:37:30.971Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why regularization is used in machine learning and how it reduces overfitting balancing bias-variance</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2M82jrEQ8UOA6QLSmWxgLg.png" /><figcaption>Image by <a href="https://pixabay.com/users/OpenClipart-Vectors-30363/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1293312">OpenClipart-Vectors</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;amp;utm_medium=referral&amp;amp;utm_campaign=image&amp;amp;utm_content=1293312">Pixabay</a></figcaption></figure><p>In the earlier era of machine learning, there used to be a lot of discussion on the <a href="https://medium.com/gadictos/bias-variance-a-comprehensive-graphical-representation-2a1cc7000e62"><strong>bias-variance trade-off</strong></a> as we could increase bias and reduce variance, or reduce bias and increase variance. But back in the pre-deep learning era, we didn’t have many tools that just reduce bias or just reduce variance without hurting the other one.</p><p>But in modern deep learning, <a href="https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12?source=friends_link&amp;sk=caecf88153c2ffa029fb322ca40c6adc"><strong>neural networks</strong></a>, or big data era getting a bigger network almost always just reduces bias without necessarily hurting variance, so long as we regularize appropriately. Also, getting more data always reduces variance and doesn’t hurt bias much. But we can’t always get more training data, or it could be expensive. Adding regularization will often help to prevent overfitting, or to reduce the errors in our network.</p><p>So generally, high complexity models overfit the data having very low bias but the high variance and low complexity models underfit the data having a high bias, but low variance. We want to balance the <a href="https://medium.com/gadictos/bias-variance-a-comprehensive-graphical-representation-2a1cc7000e62?source=friends_link&amp;sk=d5b913d6c6947271f439c6b4670394ab"><strong>bias-variance trade-off</strong></a><strong> </strong>to get to that spot of having good predictive performance. In this tutorial, we will show how we can use regularization to automatically balance between bias and variance. We will show concepts like R<strong>idge</strong> and L<strong>asso regression</strong> and we will develop these ideas using <a href="https://medium.com/swlh/logistic-regression-a-detailed-overview-from-scratch-738bc8b2a85f?source=friends_link&amp;sk=7cb864c76fd405c28a66d495b166c579"><strong>logistic regression</strong></a>.</p><h3>Regularization</h3><p>We use regularization to prevent overfitting but how do we know that a model is overfitting? We have to find a quantitative measure that’s indicative of when a model is overfitting. Consider two models</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*jVEnRDlpIk1trgijCa2iiA.png" /></figure><p>Our task is to separate two points (<strong>1</strong>,<strong>1</strong>) and (<strong>-1</strong>,<strong>-1</strong>) with a line using these models. We will use the sigmoid activation function. In the first model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*6GXgSEh_h9AUQsx4pCaYqA.png" /></figure><p>Now in the second model, for (<strong>1</strong>,<strong>1</strong>) and (<strong>-1</strong>,<strong>-1</strong>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*b7b92q8X0Onz1OU2JfqOHg.png" /></figure><p>Looking for the first time at the probabilities one might think that since the second model is giving us better probabilities it is the better model. But that’s not the case since the second model is actually overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JAhJ4A7jOoziiQf7CSXhyg.png" /></figure><p>When we use sigmoid to the small values we get the first model which has a nice slope for gradient descent. But when we multiply the linear function x₁+ x₂ with 10 and take σ(10x₁+ 10x₂) our predictions are much better since we are closer to 0 and 1 but the function becomes much steeper and much harder to apply gradient descent. Since the derivatives are mostly close to zero and they are very large when we approach the middle of the curve. Therefore in order to apply gradient descent, we prefer model 1 more than model 2. In a conceptual way, the second model is too certain and it gives little room for applying gradient descent.</p><p>So, when models become overfit the estimated coefficients of these models tend to become really large in magnitude. So, the idea is every time weights/ coefficients get bigger we just penalize them and we will do this by modifying our cost function using Ridge and lasso regression.</p><h3>Lasso Regression or L1 Norm</h3><p>So, in our desired new cost function we want to balance:</p><ol><li>How well function fits data</li><li>Magnitude of coefficients</li></ol><p>We will name it as the total cost function that has these two terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*nd3l5EK8RH5zGMT0DSMNXA.png" /></figure><p>Saying the measure of fit means a small number indicates there’s a good fit to the data. On the other hand, if the measure of the magnitude of the coefficients is small this indicates the size of the coefficients is small and we’re unlikely to be in the setting of a very overfit model. Now, our goal is to minimize this total cost function. We use cross-entropy as our measure of fit for <a href="https://medium.com/swlh/logistic-regression-a-detailed-overview-from-scratch-738bc8b2a85f?source=friends_link&amp;sk=7cb864c76fd405c28a66d495b166c579"><strong>logistic regression</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*mPWMhLkFEHI9-oeZTNYp7w.png" /></figure><p>Now we just need a measure of the magnitude of the coefficients which will tell us that the coefficients are big. One way is just summing all the coefficients together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*rU2oUG5VeR9beMNWD2OjtA.png" /></figure><p>But the problem is if we take two coefficients w₁= 1,527,301 and w2= -1,605,253 in our model and if we look at w₁+ w₂, this is going to be a small number despite the fact that each of the coefficients themselves was quite large. We can fix this issue by taking the absolute value:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*LAXV1Ls05KX946uJo1v_FQ.png" /></figure><p>This is one of the well-known solutions and is defined as the <strong>lasso regression</strong> or <strong>L₁ norm</strong>. Our resulting objective is to try and search over all possible <strong><em>w</em></strong> vectors. To find the ones that minimize our cost function plus the L₁ norm. That is <strong>ŵ</strong>, our estimated model parameters. But we’d like to be able to control how much we’re weighing the complexity of the model as measured by this magnitude of our coefficient, relative to the fit of the model. We’d like to <strong>balance</strong> between these two terms, so we’re gonna introduce another parameter <strong>λ</strong>. This is called a tuning parameter and this is balancing between this fit and magnitude. So, our cost function becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*DVrlJ4kfh38hvmwOlNTzmA.png" /></figure><h3>Ridge Regression or L2 Norm</h3><p>Another choice is to consider the sum of the squares of the coefficients which is called the ridge regression or L₂ norm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*AiN0nBGVI6aIeAWmrLQK-g.png" /></figure><p>Our cost function for L₂ norm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*06i19gFoNIK7o5FqV2PGVQ.png" /></figure><p>Now, there are many ways to implement ridge regression, and here we will just add the L₂ norm after our cost function. We will use λ\2 instead of λ since it will be easier to take the derivative and implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*68e8dhrx67VIrrZtAU88SQ.png" /></figure><h3>Gradient Descent</h3><p>So, how do we implement Gradient descent in regularization? Previously without regularization, our gradient descent was like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*nJVX6zGTsjJlFMi3bBV5Jg.png" /></figure><p>where <strong><em>E</em></strong><em> </em>was the previous cost function. For <strong><em>L₁</em></strong> regularization the problem is the gradient of the norm does not exist at <strong>0</strong>, so we need to be careful. As for the regularization term, if <strong>wᵢ&gt;0</strong> then <strong>|wᵢ| = wᵢ</strong> and the gradient is <strong>+1</strong>, similarly when <strong>wᵢ&lt;</strong>0 the gradient is <strong>−1</strong>. So in summary</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*rYNUZu2ykFKM7WcqS-FKtQ.png" /></figure><p>For L₂ regularization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*ApsyEyeXGkXbEBWqdbqa_Q.png" /></figure><p>Then we just compute this update, the same as before</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*5ijX6TF28cm6eWbjHSfGGg.png" /></figure><p>L2-regularization is also called weight decay since we making <strong>wᵢ </strong>smaller.</p><h3>Balancing Bias variance Trade-off</h3><p>In the above equations, if we take <strong>λ = 0</strong>, we get the cost function without regularization. Now, let’s take <strong>λ = ∞</strong> and we have a massively large weight on this magnitude term. In this case, the solution that will minimize the cost function will be <strong>ŵ = 0</strong>. For solutions where <strong>ŵ ≠ 0</strong>, the total cost is <strong>∞</strong>. But for sure, if <strong>ŵ = 0</strong>, then the total cost is minimum. So, the minimizing solution here is always <strong>ŵ = 0</strong> to minimize the total cost over all possible <strong>w</strong>. So, we will be operating in a regime where <strong>λ</strong> is between <strong>0</strong> to <strong>∞</strong>.</p><p>Now, let’s talk about this in the context of the bias-variance trade-off. When we had a very large <strong>λ</strong>, we had a solution with a very high bias, but low variance. One way to see this as, when we’re cranking <strong>λ</strong> all the way up to <strong>∞</strong>, in that limit, we get coefficients shrunk to <strong>0</strong>, and clearly, that’s a model with high bias but low variance. On the other hand, when we had a very small <strong>λ</strong>, we have a model that is low bias, but high variance. And to see this think about setting <strong>λ</strong> to <strong>0</strong>, in which case, we just get our old solution. And there we see that for higher complexity models we have low bias but high variance. So, <strong>λ</strong> tuning parameter controls our model complexity and controls the bias-variance trade-off.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8e60aaf37f9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/overfitting-and-regularization-in-machine-learning-e8e60aaf37f9">Overfitting and Regularization in Machine Learning</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IRIS Data Classification Using Neural Net]]></title>
            <link>https://medium.com/gadictos/iris-data-classification-using-neural-net-335d3303abd8?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/335d3303abd8</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Fri, 17 Apr 2020 16:09:36 GMT</pubDate>
            <atom:updated>2020-04-17T16:09:39.103Z</atom:updated>
            <content:encoded><![CDATA[<p>The Iris flowers dataset is one of the best-known datasets found in the classification literature. The goal is to classify Iris flowers among three species (Setosa, Versicolor or Virginica) from measurements of length and width of sepals and petals. <br>The dataset is also known as Fisher’s Iris Data contains a set of 150 records under five attributes — petal length, petal width, sepal length, sepal width, and species.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GAaQhvWUBwCAebUa.png" /></figure><h3>Data set</h3><p>First, we have to prepare the data set, which provides necessary information in a machine-readable way. Let’s First import and examine the data set.</p><pre>import pandas as pd import numpy as np # Loading the dataset dataset = pd.read_csv(&#39;Iris_Dataset.csv&#39;) # Print top Five rows dataset.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/0*slpjrP1_9BX-M8-Z.png" /></figure><p>Here we are seeing Sepal Length, width, Petal Length and width for each flower.</p><h3>Preprocessing</h3><p>Now, we have to convert the flowers into numbers so that we can pass it into our neural network. The technique we are gonna using is called one-hot coding. Which is simply a multidimensional array. Where each row is representing the example and each column is representing the flowers. When the example is Setosa then only Setosa column will be 1 and the rest of the columns will be zero.</p><pre># One Hot Encoding dataset = pd.get_dummies(dataset, columns=[&#39;Species&#39;]) values = list(dataset.columns.values)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*vMjO9KHWlyVvVQdL.png" /></figure><p>Now, we have to define input and output data for the Neural network and shuffle them so that there’s no bias.</p><pre># output data y = dataset[values[-3:]] y = np.array(y, dtype=&#39;float32&#39;) # input data X = dataset[values[1:-3]] X = np.array(X, dtype=&#39;float32&#39;) # Shuffle Data indices = np.random.choice(len(X), len(X), replace=False) X_values = X[indices] y_values = y[indices]</pre><h3>Neural Network Architecture</h3><p>Here we will use the simplest neural network architecture with only one hidden layer which consists of 8 hidden units .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/0*U_Fkfsd8GyWGMVHp.png" /></figure><h3>Define model Parameters</h3><p>We are now ready for splitting data in training and test set with test set size 10. Will use 500 epochs for training.</p><pre># Creating a Train and a Test Dataset test_size = 10 X_test = X_values[-test_size:] X_train = X_values[:-test_size] y_test = y_values[-test_size:] y_train = y_values[:-test_size] # Session sess = tf.Session() # Interval / Epochs interval = 50 epoch = 500 hidden_layer_nodes = 8</pre><p>We have to create variables for the parameters in the neural network. We must be careful about the shape of the parameters. We also have to create placeholders which will be fed eventually.</p><pre># Create variables for Neural Network layers w1 = tf.Variable(tf.random_normal(shape=[4,hidden_layer_nodes])) # Inputs -&gt; Hidden Layer b1 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes])) # First Bias w2 = tf.Variable(tf.random_normal(shape=[hidden_layer_nodes,3])) # Hidden layer -&gt; Outputs b2 = tf.Variable(tf.random_normal(shape=[3])) # Second Bias # Initialize placeholders X_data = tf.placeholder(shape=[None, 4], dtype=tf.float32) y_target = tf.placeholder(shape=[None, 3], dtype=tf.float32)</pre><p>We now have to define the operations for the hidden layer output and final output. Finally, we have to define our cost function and optimizer for backpropagation.</p><pre># Operations hidden_output = tf.nn.relu(tf.add(tf.matmul(X_data, w1), b1)) final_output = tf.nn.softmax(tf.add(tf.matmul(hidden_output, w2), b2)) # Cost Function loss = tf.reduce_mean(-tf.reduce_sum(y_target * tf.log(final_output), axis=0)) # Optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)</pre><h3>Training</h3><p>To train the model we just have to run the session for the number of epochs in a loop.</p><pre># Training print(&#39;Training the model...&#39;) for i in range(1, (epoch + 1)): sess.run(optimizer, feed_dict={X_data: X_train, y_target: y_train}) if i % interval == 0: print(&#39;Epoch&#39;, i, &#39;|&#39;, &#39;Loss:&#39;, sess.run(loss, feed_dict={X_data: X_train, y_target: y_train}))</pre><pre>import matplotlib.pyplot as plt iterations = list(ls.keys()) costs = list(ls.values()) plt.plot(iterations,costs) plt.ylabel(&#39;cost&#39;) plt.xlabel(&#39;iterations (per tens)&#39;) plt.title(&quot;Learning rate = &quot; + str(.001)) plt.show()</pre><p>After training the model if we want to predict we just have use the test set.</p><pre># Prediction for i in range(len(X_test)): print(&#39;Actual:&#39;, y_test[i], &#39;Predicted:&#39;, np.rint(sess.run(final_output, feed_dict={X_data: [X_test[i]]})))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/0*KGQI7szZsVZ2Xz1a.png" /></figure><p>Complete code will be in <a href="https://github.com/milon101/Iris_Classification">here</a>.</p><p><em>Originally published at </em><a href="https://gadictos.com/iris-data-classification-using-neural-net/"><em>https://gadictos.com</em></a><em> on March 31, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=335d3303abd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/iris-data-classification-using-neural-net-335d3303abd8">IRIS Data Classification Using Neural Net</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network: A Complete Beginners Guide from Scratch]]></title>
            <link>https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/cf1fc9d5cd12</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Fri, 27 Sep 2019 08:14:48 GMT</pubDate>
            <atom:updated>2023-03-10T01:53:52.289Z</atom:updated>
            <content:encoded><![CDATA[<h4>A detailed explanation of Mathematics and concepts behind Neural Network</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uYLPmbpB4GzALL-2MbxSYA.jpeg" /></figure><p>Neural Network has become a crucial part of modern technology. It has influenced our daily life in a way that we have never imagined. From e-commerce and solving <a href="https://gadictos.com/iris-data-classification-using-neural-net/">classification</a> problems to autonomous driving, it has touched everything. In this article, we are going to discuss all the important aspects of neural networks in the simplest way possible and at the end of the tutorial, we have also provided <strong>code</strong> implemented in <strong>python</strong> for all the described parts.</p><h4>Motivation</h4><p>Animal brains even the small ones like the brain of a pigeon were more capable than digital computers with huge processing power and storage space. This puzzled scientists for many years and turned the attention to architectural differences. Traditional computers process data very much sequentially and there is no fuzziness or discreteness. Animal brains, on the other hand, although apparently running at much slower rhythms, seemed to process signals in parallel, and fuzziness was a feature of their computation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*yzK9ECDjUUxDSEb0WukcbA.png" /></figure><p>The basic unit of a biological brain is the <strong>neuron</strong>. Neurons have various forms of them, their job is to transmit electrical signals from one end to another, from the dendrites along the axons to the terminals. These signals are then passed from one neuron to another. This is how our body senses light, touch pressure, heat, and so on. Signals from specialized sensory neurons are transmitted along with our nervous system to our brain, which itself is mostly made of neurons too. Now, the question is why are biological brains so capable even though they are much slower and consist of relatively few computing elements when compared to modern computers?</p><p>Let’s look at how a biological neuron works. It takes an electrical input and pops out another electrical signal. But can we represent neurons as linear functions? The answer is no! A biological neuron doesn’t produce an output that is a linear function of the form</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*9hqkxc58MFBGm955RuA4Ow.png" /></figure><p>So, neurons don’t exactly react readily but instead, suppress the input until it has grown so large that it triggers an output. Here comes the idea of the <strong>activation functions</strong>.</p><h4>Activation Function</h4><p>A function that takes the input signal and generates an output signal, but takes into account some kind of <strong>threshold</strong> is called an activation function. There are many such activation functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*G5T-RwuPSslbQesN.png" /></figure><p>Here, we can see for the <strong>step function</strong> the output is zero for low input values. But once it reaches the threshold, output jumps up. We can improve the step function in many ways. The S-shaped function shown above is called the <strong>sigmoid</strong> or <strong>logistic</strong> function is another very popular activation function whose equation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*6XZ8-7es1Bab5LyO8M5a6g.png" /></figure><p>Another very important activation function that is used vastly is called <strong>ReLU</strong> or <strong><em>Rectified Linear Unit</em></strong> activation function which equation is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*fV6xK4Z8lrgi_o6eeyP7bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*N_MbgFQrVajIL2Fr.png" /></figure><p><a href="https://en.wikipedia.org/wiki/Activation_function"><strong><em>Here</em></strong></a><strong><em>, a </em></strong>brief table of different types of activation functions can be found.</p><h4>Neurons</h4><p>The basic computational unit of a neural network is also called a neuron. It receives input from some other nodes, or from an external source and generates an output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*7PKdvAK8vNBEdEh3J2PSNA.png" /></figure><p>Each input has an associated weight (<strong><em>w</em></strong>), which is assigned on the basis of its relative importance to other inputs. The node applies an activation function e.g. <strong>sigmoid</strong> to the weighted sum of its inputs. If the combined signal is not large enough then the effect of the sigmoid threshold function is to suppress the output signal and fire otherwise.</p><h4>Neural Network</h4><p>In a biological neural network, electrical signals are collected by dendrites and these combine to form a stronger signal. If the signal is strong and passes the threshold the neuron fires a signal down the axon towards the terminals to pass onto the next neuron’s dendrites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*bG1Zv7yKgaIhiGw2df63RQ.png" /></figure><p>The important thing to notice is that each neuron takes input from many before it and also provides signals to many more. One way to replicate this from nature to an artificial model is to have layers of neurons, with each connected to every other one in the preceding and subsequent layer. The following diagram illustrates this idea:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*42gM4-m7B28qaSjmGg5kxQ.png" /></figure><p>we can see a neural network with three layers, each with several artificial neurons or nodes. Also, each node is connected to every other node in the preceding and next layers. This is how we actually take the idea from the biological brain and apply it to build a neural architecture for computers. But how this architecture actually learns?</p><p>The most obvious thing is to adjust the strength of the connections between nodes. Within a node, we can adjust the summation of the inputs, or we can adjust the shape of the sigmoid threshold function, but that’s more complicated than simply adjusting the strength of the connections between the nodes. The diagram on the top right shows the connected nodes, but this time weight is shown associated with each connection. A low weight will de-emphasize a signal, and a high weight will amplify it.</p><p>Next, we will see the idea of calculating signals in a neural network from the inputs through the different layers to become the output. The idea is called the <strong>forward propagation</strong> part of a neural network.</p><h4>Neural Network: Forward Propagation</h4><p>Suppose, we have a Boolean function represented by F(x,y,z) = xy + z̄. The values of this function are given below which we will use to demonstrate the calculations of the neural network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*GltITy6oqVSFxR8P1QXEbQ.png" /></figure><p>Let’s use the fourth row <strong>(1, 0, 1) =&gt; 0</strong> to demonstrate the forward propagation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*EZF39n_YHXfWk024yOlR6g.png" /></figure><p>Here, there is a neural network with three layers. The first layer is called the input layer and the last layer is called the output layer. The layers in the middle are called the hidden layer. We have used one hidden layer for simplicity. Input and hidden layers contain three nodes and the output layer contains a single node. We now assign weights to the synapses between the input and hidden layers. The weights are taken randomly between <strong>0</strong> and <strong>1</strong> since it is the first time we’re forward propagating. It is called <strong>random initialization</strong> of weights which is very important.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1eihGhF8u9O0FhB-kAGISw.png" /></figure><p>Now for a single neuron or node, we take all the connected inputs, multiply them with the associated weights and sum it. Then the node applies an activation function e.g. sigmoid to the weighted sum of its inputs to introduce non-linearity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*M6N0IOGdhtdrahE52P5M2Q.png" /></figure><p>We repeat this process for every node on every layer. Let’s focus on the first node of the hidden layer. All the nodes in the input layer are connected to it. Those input nodes have values of <strong>1</strong>, <strong>0,</strong> and <strong>1</strong> with the associated weights of <strong>0.9</strong>, <strong>0.8</strong>, and <strong>0.1</strong> respectively. We sum the product of the inputs with their corresponding set of weights to arrive at the first value for the hidden layer and do the same for the other nodes of the hidden layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*whNMnSK9Pse92RBKM4fEag.png" /></figure><p>We put these sums smaller in the circle because they’re not the final value. We can now, finally calculate the node&#39;s final output value using the activation function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*Ib0wln4ZwBsQoWV1fuIsGw.png" /></figure><p>Applying <strong><em>σ(z)</em></strong> to the three hidden layer weighted sums, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*umH_AtIBCxwdma9BhbH2wg.png" /></figure><p>We add this to our neural network as a hidden layer result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*lRqIY81dCURoVpf_wqIO5A.png" /></figure><p>Then, we calculate the weighted sum of the hidden layer results with the second set of weights (also determined at random) to determine the output sum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*hL2glsgpSIWBItwNYhXHZA.png" /></figure><p>Finally, we apply the sigmoid activation function to get the final output result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*WMEQWobKkssZIZDdFFN46g.png" /></figure><p>Because we used a random set of initial weights, the value of the output neuron is off the mark; in this case by <strong><em>+0.77</em></strong> (since the target is<strong><em> 0</em></strong>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*3-7kojwfcYtgL7-kKZJ6ow.png" /></figure><p>We can see that we are not even close to our target value. That’s because we have initialized weights randomly and we have to calibrate them. The process we will use to calibrate the weights is called <strong><em>backpropagation</em></strong> which we will cover next. But, before diving into backpropagation we need to give some ideas about computing the forward propagation process using matrix computation.</p><h4>Matrix vs Neural Network</h4><p>A matrix is nothing but a table or a grid of numbers. For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*K1GTeU8Hv96XklTOG2i1dg.png" /></figure><p>Here, matrix values are the weights of the neural network and we can represent the inputs of the network with another matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*l2LxkPHQGT4V8Fei2MfZTw.png" /></figure><p>When we multiply these two matrices we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*aIhccUCFqNpVtAOBJKbG3Q.png" /></figure><p>This is the result that we have found as the weighted sum of the input and the hidden layer. So, we can calculate the hidden layer output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*9QSvS-reTuQ4A98nreBBAA.png" /></figure><p>where W is the weight matrix and x is the input matrix. Which will be much easier and faster to calculate, since it doesn’t require calculating every node individually. This technique is called <strong>vectorization</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*1KDbrtL4Ac7Gpa735dFLMQ.png" /></figure><p>So, the general equations will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*r8W--yk3stltSH4G8OfkWw.png" /></figure><p>Where <strong><em>zᵢ[ˡ]</em></strong> is the weighted sum of a single node and <em>l</em> denotes the number of layers and<strong><em> i </em></strong>denotes the node number in a layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*MuPJ_PRqUVOXJkyuSkH91w.png" /></figure><p>Now, these equations are for a single training example! But in general, we will have many such examples like the values of the Boolean functions shown above. Let</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*ZR0DmIhbHABDOPKPi9voAQ.png" /></figure><p>where x⁽¹⁾, x⁽²⁾, …, x⁽ᵐ⁾ are different training examples when we have m training examples. Then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*ZmTExjt_F14IoCTp7IlYBw.png" /></figure><p>where a[ˡ]⁽ᵐ⁾ denotes the output of different layers of different examples, <strong><em>l </em></strong>denotes the layer number and m denotes the different examples.</p><h4>Neural Network: Back Propagation</h4><p>To improve our model, we first have to quantify how wrong our model predictions are compared to the target values of the model. Then, we adjust the weights accordingly so that the margin of error is decreased. Similar to forward propagation, backpropagation calculations occur at each layer but as the name indicates, backwardly. We begin by changing the weights between the hidden layer and the output layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*TVZYdo7C_XvC9xLbARcVXw.png" /></figure><h4>Cost Function</h4><p>For quantifying how wrong our model is, first we have to calculate the error between predicted values and the output values of the model. To do this we have to use a cost function. A cost function can be the sum of the difference between the output value and the predicted value like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*EvzNheqaqB5pvdfh1zp0CQ.png" /></figure><p>Let&#39;s assume, we have target values <strong>2</strong>, <strong>3</strong>, <strong>5</strong>, and <strong>9</strong> and output values <strong>1</strong>, <strong>5</strong>, <strong>3</strong>, and <strong>6</strong> respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*iacqDsi03dACsAMM.png" /></figure><p>Then the <strong>total error</strong> becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*a_uxRHEB3YDqD9-aCw0znw.png" /></figure><p>There is a problem with this error function. We can see that the second and third value cancels each other and we are not getting the actual error. To make our model more accurate we have to use a different cost function. What about the sum of the absolute value of the error?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*qcm5VPqh--hw83uUkmO0AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*lgRDHmZX8AKRtnEK.png" /></figure><p>Then the total error becomes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*gTk3BgHvFQ2LAS4zoeNPYQ.png" /></figure><p>and it doesn’t cancel anything. The reason this isn’t popular is that the slope isn’t continuous near the minimum and this makes gradient descent not work so well, because we can bounce around the V-shaped valley that this error function has. The slope doesn’t get smaller or closer to the minimum, so our steps don’t get smaller, which means they risk overshooting. A better option is to use the sum of the squares of the errors. So, we will calculate the error for each output neuron using the <a href="http://en.wikipedia.org/wiki/Backpropagation#Derivation"><strong><em>squared error function</em></strong></a> and sum them to get the total error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*36w6IvG9l52PSZ_0ZNKz8A.png" /></figure><p>For example, the target output for our network is <strong>0</strong> but the neural network output is <strong>0.77</strong>, therefore its error is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*I3NjVJLYHS639BXViNVyMQ.png" /></figure><p><strong>Cross-Entropy</strong> is another very popular cost function whose equation is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*jZeb_782sfGT8L0k3FPuPQ.png" /></figure><h4>The Backward Pass</h4><p>With backpropagation, our goal is to update each of the weights in the network so that the cause&#39;s actual output is closer to the target output, thereby minimizing the error for each output neuron and the network as a whole. Like forward propagation, we will derive equations for a single neuron to update the weights and then expand the concept for the rest of the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*AtRxS7u6LgRbzBlaZB2A6A.png" /></figure><p>Consider, a network with inputs x₁, x₂, and x₃ and the associated weights w₁, w₂, and w₃ respectively. we know from the forward propagation part that</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*eRvb9wMlozApEYlX3gbauQ.png" /></figure><p>which we call the output of the network. We have a target value for the network and for an untrained network when weights are not calibrated, there will be a big error. We denote this error as <strong><em>Eₜₒₜₐₗ</em></strong> where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*rcyFVLM-fllWDg0BcgfctQ.png" /></figure><p>Our job is to find out how we will adjust the weights to decrease this error. Consider <strong><em>w₁</em></strong> and we want to know how much a change in <strong><em>w₁</em></strong> affects the total error. If we look closely, we can see that the error is affected by the output, and output is affected by <strong><em>z</em></strong> while <strong><em>z</em></strong> is affected by the weight <strong><em>w₁</em></strong>. By applying the chain rule, we know that,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*xwI7BOFy3JdD2vJexe_DtA.png" /></figure><p>If we break down each piece of the equation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*j4ehIvc238oGbXafeNGZyA.png" /></figure><p>Next, we have to find out how much the output changes with respect to its total net input where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*xBjG9_wDsn3rzD7KjLWD_A.png" /></figure><p>Finally, how much the total net input z changes with respect to w₁ needs to be determined</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*SgYi0Vx6jnwlnLJafdlJpw.png" /></figure><p>Putting all the pieces together</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*EAqSbosUOQDSMea3GcQiLw.png" /></figure><p>To adjust the weights we then use the formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*5ZOyxi5Nno6_ZPcgCjmb-g.png" /></figure><p>This rule for updating weights is called <strong>Gradient Descent</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*AAEp85t8vqxLu3qbQlPxNA.png" /></figure><p>Now, let’s do a workout example for updating the weight <strong><em>w₁₀</em></strong> in the given figure. Here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*JVZWML5OgQiKSVVNoJeaVg.png" /></figure><p>Similarly, we can update other weights and this is generally a long process.</p><h4>Prediction</h4><p>We have done all the hard work so far so that we can predict new data using our neural network. The dataset we work on is generally split into two parts. One part is called training data where we do all the training and another is called the test data where we test our network. We have developed equations for training and using them we have got a calibrated set of weights. We will then use this set of weights to predict the result for our new data using the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*tqj8yuo_w7f9v5QXqCE7dQ.png" /></figure><p>where <strong><em>W</em></strong> and <strong><em>b</em></strong> are the calibrated set of weights and bias respectively and <strong><em>Xₜₑₛₜ </em></strong>is the test set split from our dataset.</p><p>Now that we have finished the theoretical part of our tutorial now you can see the <a href="https://github.com/milon101/Irirsh-Data-Classification-from-Scratch"><strong><em>code</em></strong></a> and try to understand different blocks of the code.</p><p><em>Originally published at </em><a href="https://gadictos.com/neural-network-pt1/"><em>Gadictos</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf1fc9d5cd12" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/neural-network-a-complete-beginners-guide-from-scratch-cf1fc9d5cd12">Neural Network: A Complete Beginners Guide from Scratch</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiple Regression from Scratch in Python]]></title>
            <link>https://medium.com/gadictos/multiple-regression-from-scratch-in-python-f75bce4184b6?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/f75bce4184b6</guid>
            <category><![CDATA[multiple-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[regresssion]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Mon, 09 Sep 2019 16:49:36 GMT</pubDate>
            <atom:updated>2019-09-09T16:49:36.526Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LZjbwaBfBswudkCI.png" /></figure><p>Previously, we have discussed briefly the <a href="https://medium.com/gadictos/simple-linear-regression-an-introduction-to-regression-from-scratch-180297b3784d">simple linear regression</a>. Here we will discuss <strong>multiple regression</strong> or multivariable regression and how to get the solution of the multivariable regression. At the end of the post, we will provide the <strong>python code</strong> from scratch for multivariable regression.</p><h4>Motivation</h4><p>A single variable linear regression model can learn to predict an output variable y when there is only one input variable, x and there is a linear relationship between y and x, that is, y≈w₀+w₁*x. Well, that might not be a great predictive model for most cases. For example, let’s assume we are going to begin a real estate business and we are going to use machine learning to predict house prices. In particular, we have some houses that we want to list for sale, but we don’t know the value of these houses. So, we’re going to look at other houses that sold in the recent past. Looking at how much they’ve sold and the different characteristics of those houses, we will use that data to inform our listing price for our house that we’d like to sell.</p><p>Now, there are many aspects depend on the house price. But very first we might think about the relationship between the square foot and the price of the house and find a simple linear regression between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*OxcKhPr9vPDRNZ3T.png" /></figure><p>But we might go into the data set and notice there are these other houses, that have the very similar square footage but they’re just the fundamentally different house. For example, one house only has one bathroom but the other house has three bathrooms. So the other house, of course, should have a higher value than the one with just one bathroom. So, we need to add more input to our regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*8f0ayIFzKIOa1urXeGJfyA.png" /></figure><p>So instead of just looking at square feet and using that to predict the house value, we’re going to look after other inputs as well. For example, we’re going to record the number of bathrooms in the house and we’re going to use both of these two inputs to predict the house price. In particular, in this higher dimensional space, we’re going to fit some function that models the relationship between the number of square feet and the number of bathrooms and the output, the value of the house. And so, in particular, one simple function that we can think about is just modeling this function as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*b99gS8TAXN3R7rR708TZRA.png" /></figure><p>where x₁ is the number of square feet and x₂ is the number of bathrooms.</p><p>We have just talked about square feet and number of bathrooms as the inputs that we’re looking at for our regression model. But, associated with any house, there are lots of different attributes and lots of things that we can use as inputs to our regression model and here the multivariable regression comes into play.</p><h4>Model</h4><p>When we have these multiple inputs, the simplest models we can think of is just a function directly of the inputs themselves. Input <strong>x</strong> is a d-dim vector and output y is a scalar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*0oahBoghc6HA16Oi1rsCPw.png" /></figure><p>where <strong>x</strong>[1], <strong>x</strong>[2], …, <strong>x</strong>[d] are the arrays containing different features e.g. number of square foot, number of bathrooms, number of bedrooms, etc. Taking these inputs and plugging those directly entirely into our linear model with the noise term, εᵢ we get output yᵢ in the iᵗʰ data point:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*84hHD-4QGu39b7z_gF75TA.png" /></figure><p>where the first feature in our model is just one, the constant feature. The second feature is the first input, for example, the number of square feet and the third feature is our second input, for example, the number of bathrooms. And this goes on and on till we get to our last input, which is the little d+1 feature, for example, maybe lot size. For generically, instead of just a simple hyperplane e.g. a single line, we can fit a polynomial or we can fit some D-dimensional curve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*5ZIEKzcwQV0KmUIl76Sn0A.png" /></figure><p>Because we’re gonna assume that there are some capital D different features of these multiple inputs. So just as an example, maybe our zero feature is just that one constant term and that’s pretty typical. That just shifts up and down where this curve leads in the space and maybe our first feature might be just our first input like in the hyperplane example which is quite fit. And the second feature, it could be the second input like in our hyperplane example or could be some other function of any of the inputs. Maybe we want to take the log of the seventh input, which happens to be the number of bedrooms, times just the number of bathrooms.</p><p>So, in this case, our second feature of the model is relating log number of bathrooms times number, log number of bedrooms times number of bathrooms to the output and then we get all the way up to our capital D feature which is some function of any of our inputs to our regression model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*sjldczWjz78g6Ki8W_Bcqw.png" /></figure><p>So this is our generic multiple regression model with multiple features.</p><h4>Matrix</h4><p>Like the <a href="https://medium.com/gadictos/simple-linear-regression-an-introduction-to-regression-from-scratch-180297b3784d">simple linear regression</a>, we’re going to talk about two different algorithms. One is just a closed-form solution and the other is gradient descent and there are gonna be multiple steps that we have to take to build up to deriving these algorithms and the first is simply to rewrite our regression model in the matrix notation.</p><p>So, we will begin with rewriting our multiple regression model in matrix notation for just a single observation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*x_t7xccJ2GoYMWnrsMZLVQ.png" /></figure><p>and we are gonna write this in matrix notation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ybCCPbD5hYxOXBN0DnFZFg.png" /></figure><p>In particular, we’re going to think of vectors always as being defined as columns and if it defines a row, then we’re going to call that the transpose.</p><p>Now, we are going to rewrite our model for all the observations together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*rTgUjNifS5yPaFSRohSr0A.png" /></figure><p>So, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*b_z066hm-Ahmoz7PyXdygQ.png" /></figure><p>here, we can write our entire regression model for <em>N</em> observations as this <strong>y </strong>vector and it is equal to the H matrix times this <strong>w</strong> vector plus <strong>ε</strong> vector that represents all the errors in our model. So this is the matrix notation for our model of N observations.</p><h4>Quality Metric</h4><p>In <a href="https://gadictos.com/slr/">simple linear regression</a> model, we have used Residual Sum Squares(RSS) as cost function. For any given fit, we define the residual sum of squares(RSS) of our parameter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*gI-26-GxCOQcod97Ep3a4A.png" /></figure><p>where ŷᵢ is the predicted value for yᵢ and w₀ and w₁ are the intercept and slope respectively. Now we will explain the residual sum of squares in the case of multiple regression. The residual is the difference between the actual observation and the predicted value. So what is our predicted value for the iᵗʰ observation? Well in our vector notation, what we do is we take each one of the weights in our model and then we multiply our features for that observation by that factor. So</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*8fk_BoBeYh6SprXBYKAa3Q.png" /></figure><p>which is our predicted value for the ith observation. So our RSS for multiple regression is going to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Pepm4kfb9-_e0pUQeOL6Wg.png" /></figure><p>So why are these two things equivalent? Well, we’re gonna break up the explanation into parts. We know that ŷ, the vector of all of our end predicted observations is equal to H times w or ŷ = <strong>H</strong> * <strong>w</strong> implies:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/127/1*vMKoQAYe1ifpeMVjHqJRxA.png" /></figure><p>this is equivalent of looking at our vector of actual observed values and subtracting our vector of predicted values. So we take all our house sales prices, and we look at all the predicted house prices, given a set of parameters, w, and we subtract them. What is that vector?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*aRw7sO4DoW5PH7iYOA5_Cg.png" /></figure><p>That vector is the vector of residuals because the result of this is the difference between our first house sale and our predicted house sale, we call that the residual for the first prediction, and likewise for the second, and all the way up to our nᵗʰ observation. So the term <strong>y — H</strong>.<strong>w</strong>, is equivalent to the vector of the residuals from our predictions. So,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*M3fT_BhKMGsr2AUJ3O8HBg.png" /></figure><p>By definition, that is exactly what residual sum of squares is using these <strong>w</strong> parameters.</p><h4>Closed-form solution for Multiple Regression</h4><p>Now we’re onto the final important step of the derivation, which is taking the gradient. The gradient was important both for our closed-form solution as well as, of course, for the gradient descent algorithm. So, the gradient</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*LDJ_JWmEsXiu73LOcH-HoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KepXR8OC8kIByL6H.png" /></figure><p>From calculus, we know that at the minimum the gradient will be <strong>zero</strong>. So, for closed-form solution, we take our gradient, and set it equal to <strong>zero</strong>, and solve for w</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*alcEbGDcFzwQiXaiOt2jVQ.png" /></figure><p>we have a whole collection of different parameters, w₀, w₁ and all the way up to D’th parameter and multiplying all the features we’re using in our multiple regression model. And in one line we are able to write the solution to the fit using matrix notation. This motivates why we went through all this work to write things in this matrix notation because it allows us to have this nice closed-form solution for all of our parameters written very compactly.</p><h4>Gradient Descent solution for Multiple Regression</h4><p>The other alternative approach and maybe more useful and simpler method is the Gradient Descent method where we’re walking down the surface of residual sum of squares and trying to get to the minimum. Of course, we might overshoot it and go back and forth but that’s a general idea that we’re doing this iterative procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*UcUweGb-rog0vub6K-pteQ.png" /></figure><p>what this version of the algorithm is doing is it’s taking our entire <strong>w</strong> vector, all the regression coefficients in our model, and updating them all at once using this matrix notation shown here.</p><p>Now that we have finished the theoretical part of the tutorial now you can see the <a href="https://github.com/milon101/Regression/blob/master/Multiple%20Regression/Multiple%20Regression.ipynb">code</a> and try to understand different blocks of the code.</p><p><em>Originally published at </em><a href="https://gadictos.com/mlr/"><em>Gadictos</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f75bce4184b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/multiple-regression-from-scratch-in-python-f75bce4184b6">Multiple Regression from Scratch in Python</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Classifiers: An Introduction to Classification]]></title>
            <link>https://medium.com/gadictos/linear-classifiers-an-introduction-to-classification-786fe27eef83?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/786fe27eef83</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 11:07:19 GMT</pubDate>
            <atom:updated>2019-08-15T11:07:19.029Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*M1zEDfLTWbCKulmt.png" /></figure><p>Linear Classifiers are one of the most commonly used classifiers and Logistic Regression is one of the most commonly used linear classifiers. The concepts we are going to learn here will actually extend a lot of other classification methods beyond linear classifiers. We’re going to learn the fundamental concepts, but also the underlying algorithms that let us optimize the parameters of this model to fit your training data.</p><h4>Motivation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gohjgqdZKGuTY9aT.png" /></figure><p>Suppose, we want to make a spam filter which will filter spams from our email list automatically. So, for every email, we’re going to feed it to a classifier and the classifier will say if this is a spam or maybe we want to visit a restaurant for a specific food e.g. sushi but before visiting the restaurant we want to make sure that the sushi there is good. So, what we want to do is to check the review of others visiting this restaurant about sushi and see if it is positive. It is actually very difficult to manually check all the reviews. Instead, what we can do is to feed these reviews to a classifier and it is going to say, is this a positive sentiment or negative sentiment and then watching the number of positive sentiment and the negative sentiment we will decide whether the sushi there is good to go or not.</p><h4>Linear Classifiers Intuition</h4><p>A linear classifier will take some quantity x as input which in our case will be emails or reviews and is going to make a prediction ŷ that says is this a positive statement which means is this a no spam or a positive review in which case ŷ = +1 or is this a negative statement which implies it is a spam or a negative review in which case ŷ = -1. We will use restaurant review classifier for the rest fo the tutorial as our use case. A linear classifier does a little bit more associating every word for weight or coefficient which says how positively or negatively influential this word is for a review. For example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*OsW2T-woxZEvWO9IQ686ug.png" /></figure><p>Here good and delicious have a coefficient of 1.0 and 1.5 respectively. Wonderful is very positive and has a coefficient of 2.7. On the negative side, bad and terrific might have a coefficient of -1 and -2.1 respectively. But awful is just awful, so -3.3. There are also some words that are not that relevant to the sentiment of the review, might have 0 coefficient.</p><p>Now how will we use these coefficient’s to make a prediction of whether a sentence is positive or negative? Let’s take a review, for example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*8ndwYD07g38l2SS82hK90A.png" /></figure><p>here good, delicious and great have coefficients greater than 0 and rest of the terms having coefficients greater than 0 as they are not relevant. After calculating we get a positive score which implies the sentiment in the sentence is positive and ŷ = +1. This is called a linear classifier because the output is the weighted sum of the inputs.</p><p>So more generally for a simple linear classifier, we are going to take a review and the coefficient associated with each word and feed that in our classifier and calculate the score for that input. If the score is greater than 0 the prediction is positive and ŷ = +1 and if the score is less than 0 we say the prediction is ŷ = -1. Now, what we need to do is to train the coefficients or weights of these linear classifiers from data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YkyIlS8LBFGwIxUY.png" /></figure><p>So given some input training data that includes sentences of reviews labeled with either +1 or -1. We’re going to split those into some training set and some validation set. Then we’re going to feed that training set to some learning algorithm which is going to learn the weights associated with each word. And then after we learn this classifier, we’re going back and evaluate its accuracy on that validation set. Now, how do we learn this classifier from data?</p><h4>Decision Boundary</h4><p>The decision boundary is a boundary between positive and negative predictions. Let’s say that we have taken our data and trained our linear classifier and every word has zero weight except for two of them. Awesome has weight 1.0 and awful has weight -1.5. That means that the score of any sentence is 1.0 times the number of the word awesome minus 1.5 times the number of times the word awful shows up. We can plot that into a graph which depends on every sentence the number of awesome and the number of awful. So for example, for a sentence,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*DkmAgN63Ro_esKJocq7doA.png" /></figure><p>We’re going to plot that into space where we’re going to have two awesome and one awful. So it gets plotted in the (2,1) point. And then for every sentence that we might have in our training data set say, three awful and one awesome, three awesome and no awful and so on we will have different points and if we plot the dataset we find</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*38dMJFZHoYe7W_lY.png" /></figure><p>The classifier that we’ve trained with the coefficients 1.0 and -1.5 will have a decision boundary that corresponds to a line plotted above, where 1.0 times awesome minus 1.5 times the number of awful is equal to zero. Everything below that line has a score greater than zero and any points above that line are going to have scored less than zero. So there’s that line, everything below the line is positive, everything above the line’s negative a linear decision boundary. That is what makes it a linear classifier.</p><h4>Linear Classifiers Model</h4><p>in our previous example that we had with just two features with no zero coefficients, awesome and awful and we have calculated the score as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*hbzyfKea8q9TEkeFU7-TJg.png" /></figure><p>where w₀ was 0 in our example. Now suppose that we had a third feature with no zero coefficient. Let’s say that the word great. So the score function then will be</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*vleY3JjIxSDRNb6c2ETVKA.png" /></figure><p>So, the general form of our linear classifier model will be :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*DRcVp0qNbg72LZHGQpiBbw.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*MbsuKigcqkAmMVqzLUy6Hw.png" /></figure><p>Theses notations that we’ve used so far are without features associated with it. So we’re going to have these functions hᵢ where i is 1 through D. They’ve defined some features we might extract from the data and we are going to encode the constant function that is h₀. So the more generically our model will be looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*_WxpHG2YYzRpw4bQ8J3ETg.png" /></figure><p>where</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*b__5Xpdr5VzbH7C2zM5zPg.png" /></figure><p>So this is our generic linear classifier model with multiple features.</p><p>Linear classifiers are a pretty abstract concept. Logistic regression is a specific case of that, where we use what’s called the logistic function to squeeze minus infinity to plus infinity into the interval (0, 1) so we can predict probabilities for every class. Next, we will discuss Logistic Regression.</p><p><em>Originally published at </em><a href="https://gadictos.com/linear-classifiers/"><em>Gadictos</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=786fe27eef83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/linear-classifiers-an-introduction-to-classification-786fe27eef83">Linear Classifiers: An Introduction to Classification</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Linear Regression: An Introduction to Regression from scratch]]></title>
            <link>https://medium.com/gadictos/simple-linear-regression-an-introduction-to-regression-from-scratch-180297b3784d?source=rss----2ec62e967886---4</link>
            <guid isPermaLink="false">https://medium.com/p/180297b3784d</guid>
            <category><![CDATA[regression]]></category>
            <category><![CDATA[regresssion]]></category>
            <category><![CDATA[simple-linear-regression]]></category>
            <dc:creator><![CDATA[Imdadul Haque Milon]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 04:12:50 GMT</pubDate>
            <atom:updated>2021-05-30T10:08:59.325Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_mkeAM1KflOWFGgd.png" /></figure><p>Regression is a very fundamental concept in statistics, machine learning, and <a href="https://gadictos.com/neural-network-pt1/">Neural networks</a>. Imagine plotting the correlation between rainfall frequency and agriculture production in high school. Increase in rainfall generally increases agriculture production. Fitting a line to those points enables us to predict the production rate under different rain conditions. It was actually the very simplest form of linear regression.</p><p>In simple words, regression is a study of how to best fit a curve to summarize a collection of data. It’s one of the most powerful and well-studied types of supervised learning algorithms. In regression, we try to understand the data points by discovering the curve that might have generated them. In doing so, we seek an explanation for why the given data is scattered the way it is. The best-fit curve gives us a model for explaining how the dataset might have been produced. There are many types of regression e.g. simple linear regression, polynomial regression, <a href="https://medium.com/gadictos/multiple-regression-from-scratch-in-python-f75bce4184b6"><strong>multivariate regression</strong></a>. In this post, we will discuss simple linear regression only, and later we will discuss the rest. We will also provide the python code from scratch at the end of the post</p><p>Simple regression, as the name implies, it’s just a very simple form of regression, where we only work on one input and we’ll try to fit a straight line.</p><h4>Data Set</h4><p>Consider a data set containing age and the number of homicide deaths in the US in the year 2015:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*XDOJLkED1r09zCnwn7Z-7g.png" /></figure><p>We have shown a chunk of the whole dataset above and if we plot the dataset with the line best fit to it we see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*fmJKmyWv5DAoFBZMuPUFXQ.png" /></figure><p>When we are talking about regression, our goal is to predict a continuous variable output given some input variables. For simple regression, we only have one input variable <strong><em>x</em></strong> which is the age in our case, and our desired output <strong><em>y</em></strong> which is num of homicide deaths for each age. Our dataset then consists of many examples of <strong><em>x</em></strong> and <em>y</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*pwZWmeEl76WwmvvRYnZyow.png" /></figure><p>where <em>N</em> is the number of examples in the data set and for our homicide death data set, it will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*N3iyzRwI7dr_ua2cjx9BJA.png" /></figure><h4>Model</h4><p>Now, how can we mathematically model single linear regression? Since the goal is to find the perfect line, let’s start by defining the <strong>model</strong> (the mathematical description of how predictions will be created) as a line. We’re assuming we have just one input, which in this case is the age of people and one output which is the number of homicide deaths. Our goal is to fit a line and we know the equation of a line is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/152/1*t7J2NyTH6zjntW3Wctejlg.png" /></figure><figure><img alt="Fitted linear regression line of the Data Set.

" src="https://cdn-images-1.medium.com/max/900/0*6RzACJ4moDKwAtk-.png" /></figure><p>what this regression model then specifies is that each one of our observations <strong><em>yᵢ</em></strong> is simply that function evaluated at xᵢ, so that’s w₀ plus w₁ *x₁ plus the error term which we call εᵢ. So this is our regression model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*m_sM3lRRsntYlgGRFI9uIg.png" /></figure><p>and to be clear, this error, εᵢ is the distance from our specific observation back down to the line. The parameters of this model are w₀ and w₁ are intercept and slope and we call these the regression coefficients.</p><h4>Quality Metric</h4><p>We have chosen our model with two regression coefficients w₀ and w₁. For our data set, there can be infinitely many choices of these parameters. So our task is to find the best choice of parameters and we have to know how to measure the quality of the parameters or measure the quality of the fit. So in particular, we define a loss function (also called a cost function), which measures how good or bad a particular choice of w₀ and w₁ is. Values of w₀ and w₁ that seem poor should result in a large value of the loss function, whereas good values of w₀ and w₁ should result in small values of the loss function. So what’s the cost of using a specific line? It has many forms. But the one we’re gonna talk about here is Residual Sum of Squares (RSS):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*uUS3V3nl3oulwB46R_Jq4A.png" /></figure><p>what the Residual sum of squares assumes is that we’re just gonna add up the errors we made between what we believe the relationship is or what we’ve estimated the relationship to be between x and y and what the actual observation y is. And, we talked about the error as the εᵢ.</p><h4>Model Optimization</h4><p>Our cost was to find the residual sum of squares, and for any given line, we can compute the cost of that line. So for example, we have two different lines for two different residual sums of squares. How do we know which choice of parameters is better? Ones with the minimum RSS.</p><figure><img alt="Two different fitted line of the data set for comparison. One is from Linear Regression and another is from polynomial regression." src="https://cdn-images-1.medium.com/max/945/0*1mcgDi4eyJ859agd.png" /></figure><p>Our goal is to minimize overall possible w₀ and w₁ intercepts and slopes respectively, but a question is, how are we going to do this? The mathematical notation for this minimization over all possible w₀, w₁ is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*jgyEvjNV3qyykIcifFzzLA.png" /></figure><p>So we want to find the specific value of w₀ and w₁ we’ll call that ŵ₀ and ŵ₁ respectively that minimize this residual sum of squares.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T_P4bUSgBn32mc7t.png" /></figure><p>The red dot marked below on the above plot shows where the desired minimum is. We need an algorithm to find this minimum. We will discuss two approaches e.g. <strong>Closed-form Solution</strong> and <strong>Gradient Descent</strong>.</p><h4>Closed-form Solution for Linear Regression</h4><p>From calculus, we know that at the minimum the derivatives will be 0. So, if we compute the gradient of our RSS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*L_fH1TvK4Wr1h_V3gZv2pg.png" /></figure><p>Take this gradient, set it equal to zero, and find the estimates for w₀, w₁. Those are gonna be the estimates of our two parameters of our model that define our fitted line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/176/1*MOzmOoyWIIpcvvLRofSDNw.png" /></figure><p>implies,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*Bymb-09ZxqwADeDU65OudA.png" /></figure><p>Solving for w₀ and w₁ we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*wH0avoChWTBzHzEWXaXyaw.png" /></figure><p>Now that we have the solutions, we just have to compute ŵ₁ and then plug that in and compute ŵ₀. To compute ŵ₁ we need to compute a couple of terms e.g. sum over all of our observations ∑yᵢ and sum over all of our inputs ∑xᵢ and then a few other terms that are multipliers of our input and output ∑yᵢxᵢ and ∑xᵢ². Plug them into these equations and we get out what our optimal ŵ₀ and ŵ₁ are, that minimize our residual sum of squares.</p><h4>Gradient Descent for Linear Regression</h4><p>The other approach that we will discuss is Gradient descent where we’re walking down this surface of residual sum of squares trying to get to the minimum. Of course, we might overshoot it and go back and forth but that’s a general idea that we’re doing this iterative procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*IymuIBwSLUqSvIcJGEMHtw.png" /></figure><p>Then our gradient descent algorithm will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*AWa96G4ffcQvqbpZZziIuA.png" /></figure><p>So gradient descent does this, we’re going to repeatedly update our weights. So set W to W minus η times the derivative, where W is the vector. We will repeatedly do that until the algorithm converges. η here is the learning rate and controls how big a step we take on each iteration of gradient descent and the derivative quantity is basically the update or the change we want to make to the parameters W.</p><h4>Prediction for Linear Regression</h4><p>After all the hard work now we need to test our machine learning model. The dataset we work on, generally split into two parts. One part is called training data where we do all the training and another is called the test data where we test our network. We have developed equations for training and using them we have got a calibrated set of weights. We will then use this set of weights to predict the result for our new data using the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*-X2ku-iCxZ_CcbZrasTOWQ.png" /></figure><p>where ŵ₀ and ŵ₁ are the optimized set weights.</p><p>Now that we have finished the theoretical part of the tutorial now you can see the <a href="https://github.com/milon101/Regression/blob/master/Simple%20Regression/SLR_blog.ipynb">code</a> and try to understand different blocks of the code.</p><p><em>Originally published at </em><a href="https://gadictos.com/slr/"><em>Gadictos</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=180297b3784d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gadictos/simple-linear-regression-an-introduction-to-regression-from-scratch-180297b3784d">Simple Linear Regression: An Introduction to Regression from scratch</a> was originally published in <a href="https://medium.com/gadictos">Gadictos</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>