<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lorraine Li on Medium]]></title>
        <description><![CDATA[Stories by Lorraine Li on Medium]]></description>
        <link>https://medium.com/@lorrli?source=rss-37b1fe31b4bf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*rj0GqfxkiMnqv8dKRLEogw.jpeg</url>
            <title>Stories by Lorraine Li on Medium</title>
            <link>https://medium.com/@lorrli?source=rss-37b1fe31b4bf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 13 Nov 2026 18:17:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lorrli/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Cleaning and Transforming Data with SQL]]></title>
            <link>https://medium.com/data-science/cleaning-and-transforming-data-with-sql-f93c4de0d2fc?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93c4de0d2fc</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 02:29:26 GMT</pubDate>
            <atom:updated>2019-12-10T02:29:26.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kxCao4v89siPVk80zd3T0w.jpeg" /></figure><h4>Learn how to use SQL queries to prepare, clean, and transform data for analysis!</h4><p>One of the first tasks performed when doing data analytics is to create clean the dataset you’re working with. The insights you draw from your data are only as good as the data itself, so it’s no surprise that an estimated 80% of the time spent by analytics professionals involves preparing data for use in analysis.</p><p>SQL can help expedite this important task. In this tutorial, we will discuss different functions commonly used to clean, transform, and remove duplicate data from query outputs that may not be in the form we would like. This means you’ll learn about:</p><ul><li>CASE WHEN</li><li>COALESCE</li><li>NULLIF</li><li>LEAST / GREATEST</li><li>Casting</li><li>DISTINCT</li></ul><p>We will be using the following sample table, employees, throughout this tutorial to illustrate how our functions work:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*rX8qvj0CtX8V3aDO3cRo3Q.png" /><figcaption>Our sample table, `employees`</figcaption></figure><p>This data is preloaded into a Next Tech sandbox for you to experiment and test the below queries. Connect to the database <a href="https://nt.dev/s/13bc3fa3dda1">here</a> for free!</p><p>Let’s get started!</p><blockquote>This tutorial is adapted from Next Tech’s full <strong>SQL for Data Analysis</strong> course, which includes an in-browser sandboxed environment and interactive activities and challenges using real datasets. You can get started with this course <a href="https://c.next.tech/2YDy9JV">here</a>!</blockquote><h3>CASE WHEN</h3><p>CASE WHEN is a function that allows a query to map various values in a column to other values. The general format of a CASE WHEN statement is:</p><pre>CASE<br>    WHEN condition1 THEN value1<br>    WHEN condition2 THEN value2<br>    ...<br>    WHEN conditionX THEN valueX<br>    ELSE else_value<br>END</pre><p>Here, condition1 and condition2, through conditionX, are Boolean conditions; value1 and value2, through valueX, are values to map the Boolean conditions; and else_value is the value that is mapped if none of the Boolean conditions are met.</p><p>For each row, the program starts at the top of the CASE WHEN statement and evaluates the first Boolean condition. The program then runs through each Boolean condition from the first one. For the first condition from the start of the statement that evaluates as true, the statement will return the value associated with that condition. If none of the statements evaluate as true, then the value associated with the ELSE statement will be returned.</p><p>As an example, let’s say you wanted to return all rows for employees from the employees table. Additionally, you would like to add a column that labels an employee as being an New employee if they were hired after 2019-01-01. Otherwise, it will mark the employee as a Standard employee. This column will be called employee_type. We can create this table by using a CASE WHEN statement as follows:</p><pre>SELECT<br>    *,<br>    CASE<br>        WHEN hire_date &gt;= &#39;2019-01-01&#39; THEN &#39;New&#39;<br>        ELSE &#39;Standard&#39;<br>    END AS employee_type<br>FROM<br>    employees;</pre><p>This query will give the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*tMoclPDtdqDE5fT0KGQaJg.png" /><figcaption>Output from query using `CASE WHEN`</figcaption></figure><p>The CASE WHEN statement effectively mapped a hire date to a string describing the employee type. Using a CASE WHEN statement, you can map values in any way you please.</p><h3>COALESCE</h3><p>Another useful technique is to replace NULL values with a standard value. This can be accomplished easily by means of the COALESCE function. COALESCE allows you to list any number of columns and scalar values, and, if the first value in the list is NULL, it will try to fill it in with the second value. The COALESCE function will keep continuing down the list of values until it hits a non-NULL value. If all values in the COALESCE function are NULL, then the function returns NULL.</p><p>To illustrate a simple usage of the COALESCE function, let&#39;s say we want a list of the names and titles of our employees. However, for those with no title, we want to instead write the value &#39;NO TITLE&#39;. We can accomplish this request with COALESCE:</p><pre>SELECT<br>    first_name,<br>    last_name,<br>    COALESCE(title, &#39;NO TITLE&#39;) AS title<br>FROM<br>    employees;</pre><p>This query produces the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*VsB_mcqKUH_7BbNjMHOUiw.png" /><figcaption>Output from query using `COALESCE`</figcaption></figure><p>When dealing with creating default values and avoiding NULL, COALESCE will always be helpful.</p><h3>NULLIF</h3><p>NULLIF is, in a sense, the opposite of COALESCE. NULLIF is a two-value function and will return NULL if the first value equals the second value.</p><p>As an example, imagine that we want a list of the names and titles of our employees. However, this time, we want to replace the title &#39;Honorable&#39; with NULL. This could be done with the following query:</p><pre>SELECT<br>    first_name,<br>    last_name,<br>    NULLIF(title, &#39;Honorable&#39;) AS title<br>FROM<br>    employees;</pre><p>This will blot out all mentions of &#39;Honorable&#39; from the title column and give the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*3ePmgMsKZMpg0Lq1D_HDzg.png" /><figcaption>Output from query using `NULLIF`</figcaption></figure><h3>LEAST / GREATEST</h3><p>Two functions often come in handy for data preparation are the LEAST and GREATEST functions. Each function takes any number of values and returns the least or the greatest of the values, respectively.</p><p>A simple use of this variable would be to replace the value if it’s too high or low. For example, say the minimum wage increased to $15/hour and we need to change the wages of any employee earning less than that. We can create this using the following query:</p><pre>SELECT<br>    id,<br>    first_name,<br>    last_name,<br>    title,<br>    age,<br>    GREATEST(15, wage) as wage,<br>    hire_date<br>FROM<br>    employees;</pre><p>This query will give the following output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*q00fSV9e-CB9cVV7eIp7mQ.png" /><figcaption>Output from query using `GREATEST`</figcaption></figure><p>As you can see, Bill Sadat’s wage has increased from $12 to $15.</p><h3>Casting</h3><p>Another useful data transformation is to change the data type of a column within a query. This is usually done to use a function only available to one data type, such as text, while working with a column that is in a different data type, such as a numeric.</p><p>To change the data type of a column, you simply need to use the column::datatype format, where column is the column name, and datatype is the data type you want to change the column to. For example, to change the age in the employees table to a text column in a query, use the following query:</p><pre>SELECT<br>    first_name,<br>    last_name,<br>    age::TEXT<br>FROM<br>    employees;</pre><p>This will convert the age column from an integer to text. You can now apply text functions to this transformed column. There is one final catch; not every data type can be cast to a specific data type. For instance, datetime cannot be cast to float types. Your SQL client will throw an error if you ever make an unexpected strange conversion.</p><h3>DISTINCT</h3><p>Often, when looking through a dataset, you may be interested in determining the unique values in a column or group of columns. This is the primary use case of the DISTINCT keyword. For example, if you wanted to know all the unique first names in the employees table, you could use the following query:</p><pre>SELECT<br>    DISTINCT first_name<br>FROM<br>    employees;</pre><p>This gives the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*ISOkXFzLdN2yZPxYtYaYUQ.png" /><figcaption>Output from query using `DISTINCT`</figcaption></figure><p>You can also use DISTINCT with multiple columns to get all distinct column combinations present.</p><p>I hope you enjoyed this tutorial on data cleaning and transformation with SQL. This is just the beginning of what you can use SQL for in data analysis. If you’d like to learn more, Next Tech’s <strong>SQL for Data Analysis</strong> course covers:</p><ul><li>More functions used for data preparation and cleaning</li><li>Aggregate functions and window functions</li><li>Importing and exporting data</li><li>Analytics using complex data types</li><li>Writing performant queries</li></ul><p>You can get started for free <a href="https://c.next.tech/2YDy9JV">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93c4de0d2fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/cleaning-and-transforming-data-with-sql-f93c4de0d2fc">Cleaning and Transforming Data with SQL</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Learning Basics: A Crash Course]]></title>
            <link>https://medium.com/data-science/deep-learning-basics-a-crash-course-3213aa9e477c?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/3213aa9e477c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Thu, 21 Nov 2019 03:18:21 GMT</pubDate>
            <atom:updated>2019-11-21T03:18:21.888Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn what deep learning is and how deep learning algorithms are used in real-world applications!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*XqTIb8oW4_x4FoKOWCjW9w.jpeg" /></figure><p><strong>Machine learning</strong> (ML) and <strong>deep learning</strong> (DL) techniques are being applied in a variety of fields, and data scientists are being sought after in many different industries.</p><p>With machine learning, we identify the processes through which we gain knowledge that is not readily apparent from data in order to make decisions. Applications of machine learning techniques may vary greatly, and are found in disciplines as diverse as medicine, finance, and advertising.</p><p>Deep learning makes use of more advanced neural networks than those used during the 1980s. This is not only a result of recent developments in the theory, but also advancements in computer hardware.</p><p>In this crash course, we will learn about deep learning and <strong>deep neural networks</strong> (DNNs), that is, neural networks with multiple hidden layers. We will cover the following topics:</p><ul><li>Introduction to deep learning</li><li>Deep learning algorithms</li><li>Applications of deep learning</li></ul><p>Let’s get started!</p><blockquote>This crash course is adapted from Next Tech’s <strong>Python Deep Learning Projects (Part 1: The Fundamentals)</strong> course, which explores the basics of deep learning, setting up a DL environment, and building an MLP. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed. You can get started <a href="https://c.next.tech/2ra6R1e">here</a>!</blockquote><h3>Introduction to Deep Learning</h3><p>Given the <a href="https://en.wikipedia.org/wiki/Universal_approximation_theorem">universal approximation theorem</a>, you may wonder what the point of using more than one hidden layer is. This is in no way a naive question, and for a long time neural networks were used in this way.</p><p>One reason for multiple hidden layers is that approximating a complex function might require a huge number of neurons in the hidden layer, making it impractical to use. A more important reason for using deep networks, which is not directly related to the number of hidden layers but to the level of learning, is that a deep network does not simply learn to predict output Y given input X: it also understands basic features of the input.</p><p>Let’s take a look at an example.</p><p>In <em>Proceedings of the International Conference on Machine Learning</em> (<em>ICML</em>) (2009) by H. Lee, R. Grosse, R. Ranganath, and A. Ng, the authors train a neural network with pictures of different categories of either objects or animals. In the following image we can see how the different layers of the network learn different characteristics of the input data. In the first layer the network learns to detect some basic features, such as lines and edges, which are common to all images in all categories:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/290/1*Q0BaTofDoXucclgRhGwVXw.png" /><figcaption>The first layer weights (top) and the second layer weights (bottom) after training</figcaption></figure><p>In the next layers, shown in the image below, it combines those lines and edges to compose more complex features that are specific to each category:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*1p_k6js6qHNgACFnUD4rSA.png" /><figcaption>Columns 1–4 represent the second layer (top) and third layer (bottom) weights learned for a specific object category (class). Column 5 represents the weights learned for a mixture of four object categories (faces, cars, airplanes, and motobikes)</figcaption></figure><p>In the top row, we can see how the network detects different features of each category. Eyes, noses, and mouths for human faces, doors and wheels for cars, and so on. These features are <strong>abstract</strong>. That is, the network has learned the generic shape of a feature, such as a mouth or a nose, and can detect this feature in the input data despite variations it might have.</p><p>In the second row of the preceding image, we can see how the deeper layers of the network combine these features into even more complex ones, such as faces and whole cars. A strength of deep neural networks is that they can learn these high-level abstract representations themselves by deducing them from the training data.</p><h3>Deep Learning Algorithms</h3><p>We could define deep learning as a class of machine learning techniques where information is processed in hierarchical layers to understand representations and features from data in increasing levels of complexity. In practice, all deep learning algorithms are neural networks, which share some common basic properties. They all consist of interconnected neurons that are organized in layers. Where they differ is network architecture (the way neurons are organized in the network), and sometimes the way they are trained.</p><p>With that in mind, let’s look at the main classes of neural networks. The following list is not exhaustive, but it represents the vast majority of algorithms in use today.</p><h4>Multi-Layer Perceptrons (MLPs)</h4><p>A neural network with feedforward propagation, fully-connected layers, and at least one hidden layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*OtbHDRhvKWGoa307Ifl1iQ.png" /></figure><p>The diagram demonstrates a 3-layer fully connected neural network with two hidden layers. The input layer has <em>k</em> input neurons, the first hidden layer has <em>n</em> hidden neurons, and the second hidden layer has <em>m</em> hidden neurons. The output, in this example, is the two classes <em>y</em>₁ and <em>y</em>₂. On top is the always-on bias neuron. A unit from one-layer is connected to all units from the previous and following layers (hence fully connected).</p><h4>Convolutional Neural Networks (CNNs)</h4><p>A CNN is a feedforward neural network with several types of special layers. For example, convolutional layers apply a filter to the input image (or sound) by sliding that filter all across the incoming signal, to produce an <em>n</em>-dimensional activation map. There is some evidence that neurons in CNNs are organized similarly to how biological cells are organized in the visual cortex of the brain. Today, they outperform all other ML algorithms on a large number of computer vision and natural language processing tasks.</p><h4>Recurrent Neural Networks (RNNs)</h4><p>This type of network has an internal state (or memory), which is based on all or part of the input data already fed to the network. The output of a recurrent network is a combination of its internal state (memory of previous inputs) and the latest input sample. At the same time, the internal state changes, to incorporate newly input data. Because of these properties, recurrent networks are good candidates for tasks that work on sequential data, such as text or time-series data.</p><h4>Autoencoders</h4><p>A class of unsupervised learning algorithms, in which the output shape is the same as the input, that allows the network to better learn basic representations. It consists of an input, hidden (or bottleneck), and output layers. Although it’s a single network, we can think of it as a virtual composition of two components:</p><ul><li><strong>Encoder</strong>: Maps the input data to the network’s internal representation.</li><li><strong>Decoder</strong>: Tries to reconstruct the input from the network’s internal data representation.</li></ul><h4>Reinforcement Learning (RL)</h4><p>Reinforcement algorithms learn how to achieve a complex objective over many steps by using penalties when they make a wrong decision and rewards when they make a correct decision. It is a method often used to teach a machine how to interact with an environment, similar to the way human behaviour is shaped by negative and positive feedback. RL is often used in building computer games and autonomous vehicles.</p><h3>Applications of Deep Learning</h3><p>Machine learning, particularly deep learning, is producing more and more astonishing results in terms of the quality of predictions, feature detection, and classification. Many of these recent results have even made the news! Here are just a few of the ways that these techniques can be applied today or in the near future:</p><h4>Autonomous Vehicles</h4><p>Nowadays, new cars have a suite of safety and convenience features that aim to make the driving experience safer and less stressful. One such feature is automated emergency braking if the car sees an obstacle. Another one is lane-keeping assist, which allows the vehicle to stay in its current lane without the driver needing to make corrections with the steering wheel. To recognize lane markings, other vehicles, pedestrians, and cyclists, these systems use a forward-facing camera. We can speculate that future autonomous vehicles will also use deep networks for computer vision.</p><h4>Image and Text Recognition</h4><p>Both <a href="https://cloud.google.com/solutions/image-search-app-with-cloud-vision">Google’s Vision API</a> and <a href="https://aws.amazon.com/rekognition/faqs/">Amazon’s Rekognition</a> services use deep learning models to provide various computer vision capabilities. These include recognizing and detecting objects and scenes in images, text recognition, face recognition, and so on.</p><h4>Medical Imaging</h4><p>Medical imaging is an umbrella term for various non-invasive methods of creating visual representations of the inside of the body. Some of these include <strong>Magnetic Resonance Images </strong>(<strong>MRIs</strong>), ultrasound, <strong>Computed Axial Tomography</strong> (<strong>CAT</strong>) scans, X-rays, and histology images. Typically, such an image is analyzed by a medical professional to determine the patient’s condition. Machine learning, computer vision, in particular, is enabling computer-aided diagnosis which can help specialists by detecting and highlighting important features of images.</p><p>For example, to determine the degree of malignancy of colon cancer a pathologist would have to analyze the morphology of the glands using histology imaging. This is a challenging task because morphology can vary greatly. A deep neural network could segment the glands from the image automatically, leaving the pathologist to verify the results. This would reduce the time needed for analysis, making it cheaper and more accessible.</p><h4>Medical History Analysis</h4><p>Another medical area that could benefit from deep learning is the analysis of medical history records. Before a doctor diagnoses a condition and prescribes treatment they consult the patient’s medical history for additional insight. A deep learning algorithm could extract the most relevant and important information from those extensive records, even if they are handwritten. In this way, the doctor’s job can be made easier while also reducing the risk of errors.</p><h4>Language Translation</h4><p><a href="https://arxiv.org/abs/1611.04558">Google’s Neural Machine Translation</a> API uses — you guessed it — deep neural networks for machine translation.</p><h4>Speech Recognition and Generation</h4><p>Google Duplex is another impressive real-world demonstration of deep learning. It’s a new system that can carry out natural conversations over the phone. For example, it can make restaurant reservations on a user’s behalf. It uses deep neural networks to both to understand the conversation and to generate realistic, human-like replies.</p><p><a href="https://machinelearning.apple.com/2017/10/01/hey-siri.html">Siri</a>, Google Assistant, and <a href="https://aws.amazon.com/deep-learning/">Amazon Alexa</a> also rely on deep networks for speech recognition.</p><h4>Gaming</h4><p>Finally, AlphaGo is an <strong>artificial intelligence</strong> (<strong>AI</strong>) machine based on deep learning, that made the news in March 2016 for beating the world Go champion, Lee Sedol. AlphaGo had already made the news in January 2016, when it beat the European champion, Fan Hui. Although, at the time, it seemed unlikely that it could go on to beat the world champion. Fast-forward a couple of months and AlphaGo was able to achieve this remarkable feat by sweeping its opponent in a 4–1 victory series.</p><p>This was an important milestone because Go has many more possible game variations than other games, such as chess, and it’s impossible to consider every possible move in advance. Also, unlike chess, in Go it’s very difficult to even judge the current position or value of a single stone on the board. In 2017, DeepMind released an updated version of AlphaGo called <a href="https://arxiv.org/abs/1712.01815">AlphaZero</a>.</p><p>In this crash course, we explained what deep learning is and how it’s related to deep neural networks. We discussed the different types of networks and some real-world applications of deep learning.</p><p>This is only the beginning — if you’d like to learn more about deep learning, Next Tech has a <strong>Python Deep Learning Projects</strong> series that explores real-world deep learning projects across computer vision, natural language processing (NLP), and image processing. <em>Part 1</em> of the series covers the fundamental concepts of DL, how to set up a DL environment, and how to build an MLP. You can get started <a href="https://c.next.tech/2ra6R1e">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3213aa9e477c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-learning-basics-a-crash-course-3213aa9e477c">Deep Learning Basics: A Crash Course</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Immutable vs Mutable Data Types in Python]]></title>
            <link>https://medium.com/data-science/immutable-vs-mutable-data-types-in-python-e8a9a6fcfbdc?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8a9a6fcfbdc</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[crash-course]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Thu, 17 Oct 2019 19:45:48 GMT</pubDate>
            <atom:updated>2019-10-18T00:24:18.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*gLNMeKAxC4dPjZwbbT303w.png" /></figure><h4><em>Learn the difference between mutable and immutable data types and how to find out which is which!</em></h4><p>By now you may have heard the phrase “everything in Python is an object”. <strong>Objects</strong> are abstraction for data, and Python has an amazing variety of data structures that you can use to represent data, or combine them to create your own custom data.</p><p>A first fundamental distinction that Python makes on data is about whether or not the value of an object changes. If the value can change, the object is called <strong>mutable</strong>, while if the value cannot change, the object is called <strong>immutable</strong>.</p><p>In this crash course, we will explore:</p><ul><li>The difference between mutable and immutable types</li><li>Different data types and how to find out whether they are mutable or immutable</li></ul><p>It is very important that you understand the distinction between mutable and immutable because it affects the code you write.</p><p>Let’s get started!</p><blockquote>This crash course is adapted from Next Tech’s <strong>Learn Python Programming</strong> course that uses a mix of theory and practicals to explore Python and its features, and progresses from beginner to being skilled in Python. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed. You can get started for free <a href="https://c.next.tech/2OYvckb">here</a>!</blockquote><h3>Mutable vs Immutable</h3><p>To get started, it’s important to understand that every object in Python has an ID (or identity), a type, and a value, as shown in the following snippet:</p><pre>age = 42<br>print(id(age))    # id<br>print(type(age))  # type<br>print(age)        # value<br></pre><pre>[Out:]<br>10966208<br>&lt;class ‘int’&gt;<br>42</pre><p>Once created, the ID of an object never changes. It is a unique identifier for it, and it is used behind the scenes by Python to retrieve the object when we want to use it.</p><p>The type also never changes. The type tells what operations are supported by the object and the possible values that can be assigned to it.</p><p>The value can either change or not. If it can, the object is said to be mutable, while when it cannot, the object is said to be immutable.</p><p>Let’s take a look at an example:</p><pre>age = 42<br>print(id(age))<br>print(type(age))<br>print(age)</pre><pre>age = 43<br>print(age)<br>print(id(age))<br></pre><pre>[Out:]<br>10966208<br>&lt;class ‘int’&gt;<br>42<br>43<br>10966240</pre><p>Has the value of age changed? Well, no. 42 is an integer number, of the type int, which is immutable. So, what happened is really that on the first line, age is a name that is set to point to an int object, whose value is 42.</p><p>When we type age = 43, what happens is that another object is created, of the type int and value 43 (also, the id will be different), and the name age is set to point to it. So, we didn’t change that 42 to 43. We actually just pointed age to a different location.</p><p>As you can see from printing id(age) before and after the second object named age was created, they are different.</p><p>Now, let’s see the same example using a mutable object.</p><pre>x = [1, 2, 3]<br>print(x)<br>print(id(x))</pre><pre>x.pop()<br>print(x)<br>print(id(x))<br></pre><pre>[Out:]<br>[1, 2, 3]<br>139912816421064<br>[1, 2]<br>139912816421064</pre><p>For this example, we created a list named m that contains 3 integers, 1, 2, and 3. After we change m by “popping” off the last value 3, the ID of m stays the same!</p><p>So, objects of type int are immutable and objects of type list are mutable. Now let’s discuss other immutable and mutable data types!</p><h3>Mutable Data Types</h3><p>Mutable sequences can be changed after creation. Some of Python’s mutable data types are: <strong>lists</strong>, <strong>byte arrays</strong>, <strong>sets</strong>, and <strong>dictionaries</strong>.</p><h4>Lists</h4><p>As you saw earlier, lists are mutable. Here’s another example using the append() method:</p><pre>a = list((&#39;apple&#39;, &#39;banana&#39;, &#39;clementine&#39;))<br>print(id(a))</pre><pre>a.append(&#39;dates&#39;)<br>print(id(a))</pre><pre><br>[Out:]<br>140372445629448<br>140372445629448</pre><h4>Byte Arrays</h4><p>Byte arrays represent the mutable version of bytes objects. They expose most of the usual methods of mutable sequences as well as most of the methods of the bytes type. Items are integers in the range [0, 256).</p><p>Let’s see a quick example with the bytearray type to show that it is mutable:</p><pre>b = bytearray(b&#39;python&#39;)<br>print(id(b))</pre><pre>b.replace(b&#39;p&#39;, b&#39;P&#39;)<br>print(id(b))</pre><pre><br>[Out:]<br>139963525979808<br>139963525979808</pre><h4>Sets</h4><p>Python provides two set types, set and frozenset. They are unordered collections of immutable objects.</p><pre>c = set((‘San Francisco’, ‘Sydney’, ‘Sapporo’))<br>print(id(c))<br>c.pop()<br>print(id(c))<br></pre><pre>[Out:]<br>140494031990344<br>140494031990344</pre><p>As you can see, sets are indeed mutable. Later, in the <strong>Immutable Data Types</strong> section, we will see that frozensets are immutable.</p><h4>Dictionaries</h4><pre>d = {<br>    &#39;a&#39;: &#39;alpha&#39;,<br>    &#39;b&#39;: &#39;bravo&#39;,<br>    &#39;c&#39;: &#39;charlie&#39;,<br>    &#39;d&#39;: &#39;delta&#39;,<br>    &#39;e&#39;: &#39;echo&#39;<br>}<br>print(id(d))</pre><pre>d.update({<br>    &#39;f&#39;: &#39;foxtrot&#39;<br>})<br>print(id(d))</pre><pre><br>[Out:]<br>14007111431940<br>14007111431940</pre><h3>Immutable Data Types</h3><p>Immutable data types differ from their mutable counterparts in that they can not be changed after creation. Some immutable types include <strong>numeric data types</strong>, <strong>strings</strong>, <strong>bytes</strong>, <strong>frozen sets</strong>, and <strong>tuples</strong>.</p><h4>Numeric Data Types</h4><p>You have already seen that integers are immutable; similarly, Python’s other built-in numeric data types such as booleans, floats, complex numbers, fractions, and decimals are also immutable!</p><h4>Strings and Bytes</h4><p>Textual data in Python is handled with str objects, more commonly known as <strong>strings</strong>. They are immutable sequences of <strong>Unicode code points</strong>. Unicode code points can represent a character.</p><p>When it comes to storing textual data though, or sending it on the network, you may want to encode it, using an appropriate encoding for the medium you’re using. The result of an encoding produces a bytes object, whose syntax and behavior is similar to that of strings.</p><p>Both strings and bytes are immutable, as shown in the following snippet:</p><pre># string<br>e = &#39;Hello, World!&#39;<br>print(id(e))</pre><pre>e = &#39;Hello, Mars!&#39;<br>print(id(e))</pre><pre><br>[Out:]<br>140595675113648<br>140595675113776</pre><pre># bytes<br>unicode = &#39;This is üŋíc0de&#39;  # unicode string: code points<br>print(type(unicode))<br>f = unicode.encode(&#39;utf-8&#39;)  # utf-8 encoded version<br>print(type(f))<br>print(id(f))</pre><pre>f = b&#39;A bytes object&#39;        # a bytes object<br>print(id(f))</pre><pre><br>[Out:]<br>&lt;class &#39;str&#39;&gt;<br>&lt;class &#39;bytes&#39;&gt;<br>140595675068152<br>140595675461360</pre><p>In the bytes section, we first defined f as an encoded version of our unicode string. As you can see from print(type(f)) this is a bytes type. We then create another bytes object named f whose value is b&#39;A bytes object&#39;. The two f objects have different IDs, which shows that bytes are immutable.</p><h4>Frozen Sets</h4><p>As discussed in the previous section, frozensets are similar to sets. However, frozenset objects are quite limited in respect of their mutable counterpart since they cannot be changed. Nevertheless, they still prove very effective for membership test, union, intersection, and difference operations, and for performance reasons.</p><h4>Tuples</h4><p>The last immutable sequence type we’re going to see is the tuple. A tuple is a sequence of arbitrary Python objects. In a tuple, items are separated by commas. These, too, are immutable, as shown in the following example:</p><pre>g = (1, 3, 5)<br>print(id(g))</pre><pre>g = (42, )<br>print(id(g))</pre><pre><br>[Out:]<br>139952252343784<br>139952253457184</pre><p>I hope you enjoyed this crash course on the difference between immutable and mutable objects and how to find out which an object is! Now that you understand this fundamental concept of Python programming, you can now explore the methods you can use for each data type.</p><p><em>If you’d like to learn about this and continue to advance your Python skills, Next Tech has a full </em><strong><em>Learn Python Programming</em></strong><em> course that covers:</em></p><ul><li><em>Functions</em></li><li><em>Conditional programming</em></li><li><em>Comprehensions and generators</em></li><li><em>Decorators, object-oriented programming, and iterators</em></li><li><em>File data persistence</em></li><li><em>Testing, including a brief introduction to test-driven development</em></li><li><em>Exception handling</em></li><li><em>Profiling and performances</em></li></ul><p><em>You can get started </em><a href="https://c.next.tech/2OYvckb"><em>here</em></a><em> for free!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8a9a6fcfbdc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/immutable-vs-mutable-data-types-in-python-e8a9a6fcfbdc">Immutable vs Mutable Data Types in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Normalization Explained]]></title>
            <link>https://medium.com/data-science/database-normalization-explained-53e60a494495?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e60a494495</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Tue, 02 Jul 2019 13:15:46 GMT</pubDate>
            <atom:updated>2019-07-02T16:35:26.000Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn about database normalization by designing and modifying an example database schema!</h4><p>Normalization is a technique for organizing data in a database. It is important that a database is normalized to minimize redundancy (duplicate data) and to ensure only related data is stored in each table. It also prevents any issues stemming from database modifications such as insertions, deletions, and updates.</p><p>The stages of organization are called <strong>normal forms</strong>. In this tutorial we will be redesigning a database for a construction company and ensuring that it satisfies the three normal forms:</p><h4><strong>First Normal Form</strong> (<strong>1NF</strong>):</h4><ul><li>Data is stored in tables with rows uniquely identified by a primary key</li><li>Data within each table is stored in individual columns in its most reduced form</li><li>There are no repeating groups</li></ul><h4>Second Normal Form (<strong>2NF</strong>):</h4><ul><li>Everything from 1NF</li><li>Only data that relates to a table’s primary key is stored in each table</li></ul><h4>Third Normal Form (3NF):</h4><ul><li>Everything from 2NF</li><li>There are no in-table dependencies between the columns in each table</li></ul><p>Note that there are actually six levels of normalization; however, the third normal form is considered the highest level necessary for most applications so we will only be discussing the first three forms.</p><p>Let’s get started!</p><blockquote>This tutorial is adapted from Next Tech’s <strong>Database Fundamentals</strong> course which comes with an in-browser MySQL database and interactive tasks and projects to complete. You can get started <a href="https://c.next.tech/2LwLAXB">here</a> for free!</blockquote><h3>Our Database: Codey’s Construction</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPv4DOE-6Vaa4IyNVpF3JA.png" /><figcaption><em>Codey’s Construction’s database schema with a new table that causes the database to violate the rules of normalization.</em></figcaption></figure><p>The database we will be working with in this tutorial is for Codey’s Construction company (Codey is a helpful coding bot that works with you in the course mentioned earlier). As you can see from the schema above, the database contains the tables projects, job_orders, employees, and project_employees. Recently, the customers table was added to store customer data.</p><p>Unfortunately, this table has not designed in a way that satisfies the three forms of normalization… Let’s fix that!</p><h3>First Normal Form</h3><p>First normal form relates to the duplication and over-grouping of data in tables and columns.</p><p>Codey’s Construction’s table customers violates all three rules of 1NF.</p><ol><li>There is no primary key! A user of the database would be forced to look up companies by their name, which is not guaranteed to be unique (since unique company names are registered on a state-by-state basis).</li><li>The data is not in its most reduced form. The column contact_person_and_role can be further divided into two columns, such as contact_person and contact_role.</li><li>There are two repeating groups of columns — (project1_id, project1_feedback) and (project2_id, project2_feedback).</li></ol><p>The following SQL statement was used to create the customers table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17c1774409b570da15b2b107f73d55bc/href">https://medium.com/media/17c1774409b570da15b2b107f73d55bc/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgiLgPzzxck4kFqhClz7bQ.png" /><figcaption>Example data for `customers` table.</figcaption></figure><p>By modifying some columns, we can help redesign this table so that it satisfies 1NF.</p><p>First, we need to add a primary key column called id with data type INT(6):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a4b6116d83dfe37cde6d89d4b220e03/href">https://medium.com/media/9a4b6116d83dfe37cde6d89d4b220e03/href</a></iframe><p>With this statement, we added an automatically incrementing primary key as the first column in the table.</p><p>To satisfy the second condition, we need to split the contact_person_and_role column:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fd13ee4333dc126a63394ccd418b633/href">https://medium.com/media/9fd13ee4333dc126a63394ccd418b633/href</a></iframe><p>Here, we simply renamed it as contact_person, and added a column contact_person_role immediately after it.</p><p>To satisfy the third condition, we need to move the columns containing project IDs and project feedback to a new table called project_feedbacks. First, let’s drop these columns from the customers table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c79689336905de3f46d7e4e6b0cccd8/href">https://medium.com/media/0c79689336905de3f46d7e4e6b0cccd8/href</a></iframe><p>And then create the project_feedbacks table:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bea7b1cc74ebe51a719c782c7be73077/href">https://medium.com/media/bea7b1cc74ebe51a719c782c7be73077/href</a></iframe><p>Here’s what the database schema looks like now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwDESbncE3kV-T2NznKxHA.png" /><figcaption>Modified schema that now satisfies 1NF.</figcaption></figure><p>As you can see, there are no more repeating groups in either the project_feedbacks table or the customers table. We still know which customer said what since project_feedbacks.customer_id refers back to the customers table.</p><p>Now our customers table satisfies 1NF! Let’s move on to second normal form.</p><h3>Second Normal Form</h3><p>To achieve second normal form, a database must first satisfy all the conditions for 1NF. After this, satisfying 2NF requires that all data in each table relates directly to the record that the primary key of the table identifies.</p><p>We are in violation of 2NF because the contact_person, contact_person_role and phone_number columns track data that relate to the contact person, not the customer. If the contact person for a customer changes, we would have to edit all of these columns, running the risk that we will change the values in one of the columns but forget to change another.</p><p>To help Codey’s Construction fix this table to satisfy 2NF, these columns should be moved to a table containing data on the contact person. First, let’s remove the columns in `customers` that are not related to our primary key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65485406c956dceaf668a30d511826db/href">https://medium.com/media/65485406c956dceaf668a30d511826db/href</a></iframe><p>Note that we kept the contact_person_id so we still know who to contact. Now, let’s create our new table contact_persons so we have somewhere to store data about each contact.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9ec005b8a58dee534010b57f1df3b9f/href">https://medium.com/media/c9ec005b8a58dee534010b57f1df3b9f/href</a></iframe><p>Codey’s Construction’s database schema now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RjlKqCICWWRCC1UmspW0yw.png" /><figcaption>Modified schema that now satisfies 2NF.</figcaption></figure><p>Now, if the contact person for a customer changes, the construction company just has to insert a record into the contact_persons table and change the contact_person_id in the customers table.</p><h3>Third Normal Form</h3><p>For a database to be in third normal form, it must first satisfy all the criteria for 2NF (and therefore, also 1NF).</p><p>Then, each column must be <strong>non-transitively dependent</strong> on the table’s primary key. This means that all columns in a table should rely on the primary key and no other column. If column_a relies on the primary key and also on column_b then column_a is transitively dependent on the primary key so the table does not satisfy 3NF.</p><p>Does your brain hurt from reading that? Don’t worry! It’s explained more below.</p><p>This is how the customers table looks after we have satisfied 1NF and 2NF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*qkpTWCxRKXrfxoJz9HbcBw.png" /><figcaption>Example data for modified `customers` table.</figcaption></figure><p>The table currently has transitively dependent columns. The transitively dependent relationship is between city and zip. The city in which a customer is located relies on the customer, so this satisfies 2NF; however, the city also depends on the zip code. If a customer relocates, there may be a chance we update one column but not the other. Because this relationship exists, the database is not in 3NF.</p><p>To fix our database to satisfy 3NF, we need to drop the city column from customers, and create a new table zips to store this data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a8c98faefc52bcd4d7ddd3962fd4931/href">https://medium.com/media/8a8c98faefc52bcd4d7ddd3962fd4931/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fah4_3AsV-TZFNJY_q0a3Q.png" /><figcaption>Modified schema that now satisfies 3NF.</figcaption></figure><p>That’s it! Finding issues that violate 3NF can be difficult, but it’s worth it to ensure that your database is resilient to errors caused by only partially updating data.</p><p>I hope you enjoyed this tutorial on database normalization! Codey’s Construction’s database now satisfies the three forms of normalization.</p><p><em>If you’d like to continue learning about databases, Next Tech’s </em><strong><em>Database Fundamentals</em></strong><em> course covers all you need to know to get started with databases and SQL. By helping an interactive coding bot named Codey, you will learn how to create and design databases, modify data, and write SQL queries to answer business questions. You can get started for free </em><a href="https://c.next.tech/2LwLAXB"><em>here</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e60a494495" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/database-normalization-explained-53e60a494495">Database Normalization Explained</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Multilayer Neural Networks with TensorFlow’s Keras API]]></title>
            <link>https://medium.com/data-science/introduction-to-multilayer-neural-networks-with-tensorflows-keras-api-abf4f813959?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf4f813959</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Tue, 11 Jun 2019 23:09:02 GMT</pubDate>
            <atom:updated>2019-06-11T23:09:02.026Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LkKz4wtZNBo5i-Vc8DWhTA.png" /></figure><p>Learn how to build and train a multilayer perceptron using TensorFlow’s high-level API Keras!</p><p>The development of Keras started in early 2015. As of today, it has evolved into one of the most popular and widely used libraries built on top of Theano and TensorFlow. One of its prominent features is that it has a very intuitive and user-friendly API, which allows us to implement neural networks in only a few lines of code.</p><p>Keras is also integrated into TensorFlow from version 1.1.0. It is part of the contrib module (which contains packages developed by contributors to TensorFlow and is considered experimental code).</p><p>In this tutorial we will look at this high-level TensorFlow API by walking through:</p><ul><li>The basics of feedforward neural networks</li><li>Loading and preparing the popular MNIST dataset</li><li>Building an image classifier</li><li>Train a neural network and evaluate its accuracy</li></ul><p>Let’s get started!</p><blockquote><em>This tutorial is adapted from </em>Part 4<em> of Next Tech’s </em><strong><em>Python Machine Learning</em></strong><em> series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free </em><a href="https://c.next.tech/2YrZOMz"><strong><em>here</em></strong></a><em>!</em></blockquote><h3>Multilayer Perceptrons</h3><p>Multilayer feedforward neural networks are a special type of <em>fully connected</em> network with multiple single neurons. They are also called <strong>Multilayer Perceptrons</strong> (<strong>MLP</strong>). The following figure illustrates the concept of an MLP consisting of three layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*vWRGnasRs2zo3GhTHlmIfg.jpeg" /></figure><p>The MLP depicted in the preceding figure has one input layer, one hidden layer, and one output layer. The units in the hidden layer are fully connected to the input layer, and the output layer is fully connected to the hidden layer. If such a network has more than one hidden layer, we also call it a <strong>deep artificial neural network</strong>.</p><p>We can add an arbitrary number of hidden layers to the MLP to create deeper network architectures. Practically, we can think of the number of layers and units in a neural network as additional hyperparameters that we want to optimize for a given problem task.</p><p>As shown in the preceding figure, we denote the <em>i</em>th activation unit in the <em>i</em>th layer as <em>a_i^(l). </em>To make the math and code implementations a bit more intuitive, we will use the <em>in</em> superscript for the input layer, the <em>h</em> superscript for the hidden layer, and the <em>o</em> superscript for the output layer.</p><p>For instance, <em>a_i^(in)</em>​ refers to the <em>i</em>th value in the input layer, <em>a_i^(h)</em>​ refers to the <em>i</em>th unit in the hidden layer, and <em>a_i^(out)</em>​ refers to the <em>i</em>th unit in the output layer. Here, the activation units <em>a_0^(in)</em> and <em>a_0^(out)</em>​ are the <strong>bias units</strong>, which we set equal to <em>1</em>. The activation of the units in the input layer is just its input plus the bias unit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*utpugbLTvJmLH1Y6JB8ppQ.png" /></figure><p>Each unit in layer <em>l</em> is connected to all units in layer <em>l + 1</em> via a weight coefficient. For example, the connection between the <em>k</em>th unit in layer <em>l</em> to the <em>j</em>th unit in layer <em>l + 1</em> will be written as <em>w_{k, j}^(l)</em>​. Referring back to the previous figure, we denote the weight matrix that connects the input to the hidden layer as <em>W^(h)</em>​, and we write the matrix that connects the hidden layer to the output layer as <em>W^(out)</em>​.</p><p>We summarize the weights that connect the input and hidden layers by a matrix:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/85/1*sxd64uqvQTp6SeyE-PCHug.png" /></figure><p>where <em>d</em> is the number of hidden units and <em>m</em> is the number of input units including the bias unit. Since it is important to internalize this notation to follow the concepts later in this tutorial, let’s summarize what we have just learned in a descriptive illustration of a simplified 3–4–3 multilayer perceptron:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*9Cfkv8E7r0pWN_EPB1BbKA.jpeg" /></figure><h3>The MNIST dataset</h3><p>To see what neural network training via the tensorflow.keras (tf.keras) high-level API looks like, let&#39;s implement a multilayer perceptron to classify the handwritten digits from the popular Mixed National Institute of Standards and Technology (<strong>MNIST</strong>) dataset that serves as a popular benchmark dataset for machine learning algorithm.</p><p>To follow along with the code snippets in this tutorial, you can use this Next Tech <a href="https://c.next.tech/2YUIiAQ">sandbox</a>, which has the MNIST dataset and all necessary packages installed. Otherwise, you can use your local environment and download the dataset <a href="http://yann.lecun.com/exdb/mnist/">here</a>.</p><p>The MNIST dataset in four parts, as listed here:</p><ul><li><strong>Training set images</strong>: train-images-idx3-ubyte.gz — 60,000 samples</li><li><strong>Training set labels</strong>: train-labels-idx1-ubyte.gz — 60,000 labels</li><li><strong>Test set images</strong>: t10k-images-idx3-ubyte.gz — 10,000 samples</li><li><strong>Test set labels</strong>: t10k-labels-idx1-ubyte.gz — 10,000 labels</li></ul><p>The training set consists of handwritten digits from 250 different people (50% high school students, 50% employees from the Census Bureau). The test set contains handwritten digits from different people.</p><p>Note that TensorFlow also provides the same dataset as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03165b08f656180ff4b46334b5e2b809/href">https://medium.com/media/03165b08f656180ff4b46334b5e2b809/href</a></iframe><p>However, we will work with the MNIST dataset as an external dataset to learn all the steps of data preprocessing separately. This way, you learn what you need to do with your own dataset.</p><p>The first step is to unzip the four parts of the MNIST dataset by running the following commands in your Terminal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f04e94443815709584b503f89662f1f/href">https://medium.com/media/0f04e94443815709584b503f89662f1f/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bddb19f3df2f561d47b1a1090b92c838/href">https://medium.com/media/bddb19f3df2f561d47b1a1090b92c838/href</a></iframe><p>The load_mnist function returns two arrays, the first being an <em>n x m</em> dimensional NumPy array (images), where <em>n</em> is the number of samples and <em>m</em> is the number of features (here, pixels). The images in the MNIST dataset consist of 28 x 28 pixels, and each pixel is represented by a gray scale intensity value. Here, we unroll the 28 x 28 pixels into one-dimensional row vectors, which represent the rows in our images array (784 per row or image). The second array (labels) returned by the load_mnist function contains the corresponding target variable, the class labels (integers 0-9) of the handwritten digits.</p><p>Then, the dataset is loaded and prepared as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1f4d79bb036a8760617cd32de7c8b32/href">https://medium.com/media/a1f4d79bb036a8760617cd32de7c8b32/href</a></iframe><pre>[Out:]<br> Rows: 60000,  Columns: 784<br> Rows: 10000,  Columns: 784<br> (60000, 784) (60000,)<br> (10000, 784) (10000,)</pre><p>To get an idea of how those images in MNIST look, let’s visualize examples of the digits 0–9 via Matplotlib’s imshowfunction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2249f32e5c1b579ea064cc63a1659de/href">https://medium.com/media/c2249f32e5c1b579ea064cc63a1659de/href</a></iframe><p>We should now see a plot of the 2 x 5 subfigures showing a representative image of each unique digit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FzRxkCQ72duZnzClZf-Vdg.png" /></figure><p>Now let’s start building our model!</p><h3>Building an MLP using TensorFlow’s Keras API</h3><p>First, let’s set the random seed for NumPy and TensorFlow so that we get consistent results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5339de294617fd96eaad13d004134285/href">https://medium.com/media/5339de294617fd96eaad13d004134285/href</a></iframe><p>To continue with the preparation of the training data, we need to convert the class labels (integers 0–9) into the one-hot format. Fortunately, Keras provides a convenient tool for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/641d9c472ed2f63cf3b213ca330f1fba/href">https://medium.com/media/641d9c472ed2f63cf3b213ca330f1fba/href</a></iframe><pre>First 3 labels:  [5 0 4]</pre><pre>First 3 labels (one-hot):<br> [[0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]<br> [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]<br> [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]]</pre><p>Now, let’s implement our neural network! Briefly, we will have three layers, where the first two layers (the input and hidden layers) each have 50 units with the tanh activation function and the last layer (the output layer) has 10 layers for the 10 class labels and uses softmax to give the probability of each class. Keras makes these tasks very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b139f8e19abe561e70db8f850217cd50/href">https://medium.com/media/b139f8e19abe561e70db8f850217cd50/href</a></iframe><p>First, we initialize a new model using the Sequential class to implement a feedforward neural network. Then, we can add as many layers to it as we like. However, since the first layer that we add is the input layer, we have to make sure that the input_dim attribute matches the number of features (columns) in the training set (784 features or pixels in the neural network implementation).</p><p>Also, we have to make sure that the number of output units (units) and input units (input_dim) of two consecutive layers match. Our first two layers have 50 units plus one bias unit each. The number of units in the output layer should be equal to the number of unique class labels — the number of columns in the one-hot-encoded class label array.</p><p>Note that we used glorot_uniform to as the initialization algorithm for weight matrices. <a href="https://keras.io/initializers/#glorot_uniform"><strong>Glorot initialization</strong></a> is a more robust way of initialization for deep neural networks. The biases are initialized to zero, which is more common, and in fact the default setting in Keras.</p><p>Before we can compile our model, we also have to define an optimizer. We chose a <strong>stochastic gradient descent</strong> optimization. Furthermore, we can set values for the weight decay constant and momentum learning to adjust the learning rate at each epoch. Lastly, we set the cost (or loss) function to categorical_crossentropy.</p><p>The binary cross-entropy is just a technical term for the cost function in the logistic regression, and the categorical cross-entropy is its generalization for multiclass predictions via <a href="%5Bhttps://en.wikipedia.org/wiki/Softmax_function%5D(https://en.wikipedia.org/wiki/Softmax_function)">softmax</a>.</p><p>After compiling the model, we can now train it by calling the fit method. Here, we are using mini-batch stochastic gradient with a batch size of 64 training samples per batch. We train the MLP over 50 epochs, and we can follow the optimization of the cost function during training by setting verbose=1.</p><p>The validation_split parameter is especially handy since it will reserve 10% of the training data (here, 6,000 samples) for validation after each epoch so that we can monitor whether the model is overfitting during training:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/880577c8a37b7e5c7bfe865f34b043ac/href">https://medium.com/media/880577c8a37b7e5c7bfe865f34b043ac/href</a></iframe><p>Printing the value of the cost function is extremely useful during training to quickly spot whether the cost is decreasing during training and stop the algorithm earlier. Otherwise, hyperparameter values will need to be tuned.</p><p>To predict the class labels, we can then use the predict_classes method to return the class labels directly as integers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83ea1455ec2dee9237ff08fea8c5680c/href">https://medium.com/media/83ea1455ec2dee9237ff08fea8c5680c/href</a></iframe><pre>First 3 predictions: [5 0 4]</pre><p>Finally, let’s print the model accuracy on training and test sets:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ffeb3a5e309ba73873431f38e25814f/href">https://medium.com/media/9ffeb3a5e309ba73873431f38e25814f/href</a></iframe><pre>Training accuracy: 98.81<br>Test accuracy: 96.27</pre><p>I hope you enjoyed this tutorial on using TensorFlow&#39;s keras API to build and train a multilayered neural network for image classification! Note that this is just a very simple neural network without optimized tuning parameters.</p><p>In practice you need to know how to optimize the model by tweaking learning rate, momentum, weight decay, and number of hidden units. You also need to learn how to deal with the vanishing gradient problem, wherein error gradients become increasingly small as more layers are added to a network.</p><p><em>We cover these topics in Next Tech’s </em><strong><em>Python Machine Learning (Part 4)</em></strong><em> course, as well as:</em></p><ul><li><em>Breaking down the mechanics of </em><em>TensorFlow, such as tensors, activation functions computation graphs, variables, and placeholders</em></li><li><em>Low-level </em><em>TensorFlow and another high-level API, </em><em>Layers</em></li><li><em>Modeling sequential data using </em><strong><em>recurrent neural networks</em></strong><em> (RNN) and </em><strong><em>long short-term memory</em></strong><em> (LSTM) networks</em></li><li><em>Classifying images with deep </em><strong><em>convolutional neural networks</em></strong><em> (CNN).</em></li></ul><p><em>You can get started </em><a href="https://c.next.tech/2YrZOMz"><em>here</em></a><em> for free!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abf4f813959" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-multilayer-neural-networks-with-tensorflows-keras-api-abf4f813959">Introduction to Multilayer Neural Networks with TensorFlow’s Keras API</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Clustering with scikit-learn]]></title>
            <link>https://medium.com/data-science/k-means-clustering-with-scikit-learn-6b47a369a83c?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b47a369a83c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Fri, 31 May 2019 02:04:19 GMT</pubDate>
            <atom:updated>2019-06-04T01:48:50.990Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn the fundamentals and mathematics behind the popular k-means clustering algorithm and how to implement it in scikit-learn!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*0DDt5Xp9z6ecj5eL6FNAfQ.png" /></figure><p><strong>Clustering</strong> (or <strong>cluster analysis</strong>) is a technique that allows us to find groups of similar objects, objects that are more related to each other than to objects in other groups. Examples of business-oriented applications of clustering include the grouping of documents, music, and movies by different topics, or finding customers that share similar interests based on common purchase behaviors as a basis for recommendation engines.</p><p>In this tutorial, we will learn about one of the most popular clustering algorithms, <strong>k-means</strong>, which is widely used in academia as well as in industry. We will cover:</p><ul><li>The basic concepts of k-means clustering</li><li>The mathematics behind the k-means algorithm</li><li>The advantages and disadvantages of k-means</li><li>How to implement the algorithm on a sample dataset using scikit-learn</li><li>How to visualize clusters</li><li>How to choose the optimal <em>k</em> using the elbow method</li></ul><p>Let’s get started!</p><blockquote><em>This tutorial is adapted from </em>Part 3<em> of Next Tech’s </em><strong><em>Python Machine Learning </em></strong><em>series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free </em><a href="https://c.next.tech/2VsyVXb"><em>here</em></a><em>!</em></blockquote><h3>Fundamentals of K-Means Clustering</h3><p>As we will see, the k-means algorithm is extremely easy to implement and is also computationally very efficient compared to other clustering algorithms, which might explain its popularity. The k-means algorithm belongs to the category of <strong>prototype-based clustering</strong>.</p><p>Prototype-based clustering means that each cluster is represented by a prototype, which can either be the <strong>centroid</strong> (<em>average</em>) of similar points with continuous features, or the <strong>medoid</strong> (the most <em>representative</em> or most frequently occurring point) in the case of categorical features.</p><p>While k-means is very good at identifying clusters with a spherical shape, one of the drawbacks of this clustering algorithm is that we have to specify the number of clusters, <em>k</em>, a priori. An inappropriate choice for <em>k</em> can result in poor clustering performance — we will discuss later in this tutorial how to choose <em>k</em>.</p><p>Although k-means clustering can be applied to data in higher dimensions, we will walk through the following examples using a simple two-dimensional dataset for the purpose of visualization.</p><p>You can follow along with the code in this tutorial by using a Next Tech <a href="https://c.next.tech/2HLYRt2">sandbox</a>, which has all the necessary libraries pre-installed, or if you’d prefer, you can run the snippets in your own local environment.</p><p>Once your sandbox loads, let’s import the toy dataset from scikit-learn and visualize the datapoints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b261c5c9a161204998061448595705e/href">https://medium.com/media/9b261c5c9a161204998061448595705e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*0Qtlh02GkKleLQPWO3wghQ.png" /></figure><p>The dataset that we just created consists of 150 randomly generated points that are roughly grouped into three regions with higher density, which is visualized via a two-dimensional scatterplot.</p><p>In real-world applications of clustering, we do not have any ground truth category information (information provided as empirical evidence as opposed to inference) about those samples; otherwise, it would fall into the category of supervised learning. Thus, our goal is to group the samples based on their feature similarities, which can be achieved using the k-means algorithm that can be summarized by the following four steps:</p><ol><li>Randomly pick <em>k</em> centroids from the sample points as initial cluster centers.</li><li>Assign each sample to the nearest centroid <em>μ^(j), j ∈ {1, …, k}.</em></li><li>Move the centroids to the center of the samples that were assigned to it.</li><li>Repeat steps 2 and 3 until the cluster assignments do not change or a user-defined tolerance or maximum number of iterations is reached.</li></ol><p>Now, the next question is <em>how do we measure similarity between objects</em>? We can define similarity as the opposite of distance, and a commonly used distance for clustering samples with continuous features is the <strong>squared Euclidean distance</strong> between two points <strong><em>x </em></strong>and <strong><em>y</em></strong> in <em>m</em>-dimensional space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*Lr1Xw4nkONoNz1dmBlYjfA.png" /></figure><p>Note that in the preceding equation, the index <em>j</em> refers to the <em>j</em>th dimension (feature column) of the sample points <strong><em>x</em></strong> and <strong><em>y</em></strong>. We will use the superscripts <em>i</em> and <em>j</em> to refer to the sample index and cluster index, respectively.</p><p>Based on this Euclidean distance metric, we can describe the k-means algorithm as a simple optimization problem, an iterative approach for minimizing the within-cluster <strong>Sum of Squared Errors</strong>(<strong>SSE</strong>), which is sometimes also called <strong>cluster</strong> <strong>inertia</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*kFwKdOb2ko1SaqnOVBApow.png" /></figure><p>Here,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*Gj4quhatOb6NJfFwyhUpwA.png" /></figure><p>and</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*HGnGIS92CJ0cu1SiukGPCA.png" /></figure><p>Note that when we are applying k-means to real-world data using a Euclidean distance metric, we want to make sure that the features are measured on the same scale and apply <em>z</em>-score standardization or min-max scaling if necessary.</p><h3>K-means clustering using scikit-learn</h3><p>Now that we have learned how the k-means algorithm works, let’s apply it to our sample dataset using the KMeans class from scikit-learn&#39;s cluster module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71a9e6da8b3b583b7ad47507dc188014/href">https://medium.com/media/71a9e6da8b3b583b7ad47507dc188014/href</a></iframe><p>Using the preceding code, we set the number of desired clusters to 3. We set n_init=10 to run the k-means clustering algorithms 10 times independently with different random centroids to choose the final model as the one with the lowest SSE. Via the max_iter parameter, we specify the maximum number of iterations for each single run (here, 300).</p><p>Note that the k-means implementation in scikit-learn stops early if it converges before the maximum number of iterations is reached. However, it is possible that k-means does not reach convergence for a particular run, which can be problematic (computationally expensive) if we choose relatively large values for max_iter.</p><p>One way to deal with convergence problems is to choose larger values for tol, which is a parameter that controls the tolerance with regard to the changes in the within-cluster sum-squared-error to declare convergence. In the preceding code, we chose a tolerance of 1e-04 (= 0.0001).</p><p>A problem with k-means is that one or more clusters can be empty. However, this problem is accounted for in the current k-means implementation in scikit-learn. If a cluster is empty, the algorithm will search for the sample that is farthest away from the centroid of the empty cluster. Then it will reassign the centroid to be this farthest point.</p><p>Now that we have predicted the cluster labels y_km, let’s visualize the clusters that k-means identified in the dataset together with the cluster centroids. These are stored under the cluster_centers_ attribute of the fitted KMeans object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db4d15c3654b2ba9c99cd98d3aa84a04/href">https://medium.com/media/db4d15c3654b2ba9c99cd98d3aa84a04/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*TEYPlUQfggUVnqu26QiQ3g.png" /></figure><p>In the resulting scatterplot, we can see that k-means placed the three centroids at the center of each sphere, which looks like a reasonable grouping given this dataset.</p><h3>The Elbow Method</h3><p>Although k-means worked well on this toy dataset, it is important to reiterate that a drawback of k-means is that we have to specify the number of clusters, <em>k</em>, before we know what the optimal <em>k</em> is. The number of clusters to choose may not always be so obvious in real-world applications, especially if we are working with a higher dimensional dataset that cannot be visualized.</p><p>The <strong>elbow method</strong> is a useful graphical tool to estimate the optimal number of clusters <em>k</em> for a given task. Intuitively, we can say that, if <em>k</em> increases, the within-cluster SSE (“<strong>distortion</strong>”) will decrease. This is because the samples will be closer to the centroids they are assigned to.</p><p>The idea behind the elbow method is to identify the value of <em>k </em>where the distortion begins to decrease most rapidly, which will become clearer if we plot the distortion for different values of <em>k</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/623882ca8aab1d890664bd57ca49411b/href">https://medium.com/media/623882ca8aab1d890664bd57ca49411b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*Q9OzABjrHuY1uFIcEe8tlg.png" /></figure><p>As we can see in the resulting plot, the elbow is located at <em>k</em> = 3, which is evidence that <em>k</em> = 3 is indeed a good choice for this dataset.</p><p>I hope you enjoyed this tutorial on the k-means algorithm! We explored the basic concepts and mathematics behind the k-means algorithm, how to implement k-means, and how to select an optimal number of clusters, <em>k</em>.</p><p>If you’d like to learn more, Next Tech’s <strong>Python Machine Learning (Part 3)</strong> course further explores clustering algorithms and techniques such as:</p><ul><li><strong>Silhouette plots</strong>, another method used to select the optimal <em>k</em></li><li><strong>k-means++</strong>, a variant of k-means, that improves clustering results through more clever seeding of the initial cluster centers.</li><li>Other categories of clustering algorithms, such as <strong>hierarchical </strong>and <strong>density-based clustering</strong>, that do not require us to specify the number of clusters upfront or assume spherical structures in our dataset.</li></ul><p>The course also explores regression analysis, sentiment analysis, and how to deploy a dynamic machine learning model to a web application. You can get started <a href="https://c.next.tech/2VsyVXb">here</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b47a369a83c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/k-means-clustering-with-scikit-learn-6b47a369a83c">K-Means Clustering with scikit-learn</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Principal Component Analysis for Dimensionality Reduction]]></title>
            <link>https://medium.com/data-science/principal-component-analysis-for-dimensionality-reduction-115a3d157bad?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/115a3d157bad</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Fri, 24 May 2019 21:46:36 GMT</pubDate>
            <atom:updated>2019-05-27T17:24:34.853Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to perform PCA by learning the mathematics behind the algorithm and executing it step-by-step with Python!</h4><p>In the modern age of technology, increasing amounts of data are produced and collected. In machine learning, however, too much data can be a bad thing. At a certain point, more features or dimensions can decrease a model’s accuracy since there is more data that needs to be generalized — this is known as the <strong>curse of dimensionality</strong>.</p><p><strong>Dimensionality reduction</strong> is way to reduce the complexity of a model and avoid overfitting. There are two main categories of dimensionality reduction: feature selection and feature extraction. Via feature selection, we select a subset of the original features, whereas in feature extraction, we derive information from the feature set to construct a new feature subspace.</p><p>In this tutorial we will explore feature extraction. In practice, feature extraction is not only used to improve storage space or the computational efficiency of the learning algorithm, but can also improve the predictive performance by reducing the curse of dimensionality — especially if we are working with non-regularized models.</p><p>Specifically, we will discuss the <strong>Principal Component Analysis</strong> (<strong>PCA</strong>) algorithm used to compress a dataset onto a lower-dimensional feature subspace with the goal of maintaining most of the relevant information. We will explore:</p><ul><li>The concepts and mathematics behind PCA</li><li>How to execute PCA step-by-step from scratch using Python</li><li>How to execute PCA using the Python library scikit-learn</li></ul><p>Let’s get started!</p><blockquote><em>This tutorial is adapted from </em>Part 2<em> of Next Tech’s </em><strong><em>Python Machine Learning</em></strong><em> series, which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started for free </em><a href="https://c.next.tech/2vZveOh"><em>here</em></a><em>!</em></blockquote><h3>Introduction to Principal Component Analysis</h3><p><strong>Principal Component Analysis</strong> (<strong>PCA</strong>) is an unsupervised linear transformation technique that is widely used across different fields, most prominently for feature extraction and dimensionality reduction. Other popular applications of PCA include exploratory data analyses and de-noising of signals in stock market trading, and the analysis of genome data and gene expression levels in the field of bioinformatics.</p><p>PCA helps us to identify patterns in data based on the correlation between features. In a nutshell, PCA aims to find the directions of maximum variance in high-dimensional data and projects it onto a new subspace with equal or fewer dimensions than the original one.</p><p>The orthogonal axes (<strong>principal components</strong>) of the new subspace can be interpreted as the directions of maximum variance given the constraint that the new feature axes are orthogonal to each other, as illustrated in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*zh1GxZ4BPCOPFmTxreVFdw.jpeg" /></figure><p>In the preceding figure, <em>x1</em> and <em>x2</em> are the original feature axes, and <strong>PC1</strong> and <strong>PC2</strong> are the principal components.</p><p>If we use PCA for dimensionality reduction, we construct a <em>d</em> x <em>k</em>–dimensional transformation matrix <strong><em>W</em></strong> that allows us to map a sample vector <strong><em>x</em></strong> onto a new <em>k</em>–dimensional feature subspace that has fewer dimensions than the original <em>d</em>–dimensional feature space:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*ytEHO-Wjos_ugY2LffXEyg.png" /></figure><p>As a result of transforming the original <em>d</em>-dimensional data onto this new <em>k</em>-dimensional subspace (typically <em>k</em> ≪ <em>d</em>), the first principal component will have the largest possible variance, and all consequent principal components will have the largest variance given the constraint that these components are uncorrelated (orthogonal) to the other principal components — even if the input features are correlated, the resulting principal components will be mutually orthogonal (uncorrelated).</p><p>Note that the PCA directions are highly sensitive to data scaling, and we need to standardize the features <em>prior</em> to PCA if the features were measured on different scales and we want to assign equal importance to all features.</p><p>Before looking at the PCA algorithm for dimensionality reduction in more detail, let’s summarize the approach in a few simple steps:</p><ol><li>Standardize the <em>d</em>-dimensional dataset.</li><li>Construct the covariance matrix.</li><li>Decompose the covariance matrix into its eigenvectors and eigenvalues.</li><li>Sort the eigenvalues by decreasing order to rank the corresponding eigenvectors.</li><li>Select <em>k</em> eigenvectors which correspond to the <em>k</em> largest eigenvalues, where <em>k</em> is the dimensionality of the new feature subspace (<em>k</em> ≤ <em>d</em>).</li><li>Construct a projection matrix <strong><em>W</em></strong> from the “top” <em>k</em> eigenvectors.</li><li>Transform the <em>d</em>-dimensional input dataset <strong><em>X</em></strong> using the projection matrix <strong><em>W</em></strong> to obtain the new <em>k</em>-dimensional feature subspace.</li></ol><p>Let’s perform a PCA step by step, using Python as a learning exercise. Then, we will see how to perform a PCA more conveniently using scikit-learn.</p><h3>Extracting the Principal Components Step By Step</h3><p>We will be using the <em>Wine</em> dataset from The UCI Machine Learning Repository in our example. This dataset consists of 178 wine samples with 13 features describing their different chemical properties. You can find out more <a href="https://archive.ics.uci.edu/ml/datasets/wine">here</a>.</p><p>In this section we will tackle the first four steps of a PCA; later we will go over the last three. You can follow along with the code in this tutorial by using a Next Tech <a href="https://c.next.tech/30EzSiV">sandbox</a>, which has all the necessary libraries pre-installed, or if you’d prefer, you can run the snippets in your own local environment.</p><p>Once your sandbox loads, we will start by loading the <em>Wine</em> dataset directly from the repository:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80eaa0a88272f4f1160c0cbdb246fe01/href">https://medium.com/media/80eaa0a88272f4f1160c0cbdb246fe01/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*4qDPuAo1N_SCV44YATKDFA.png" /></figure><p>Next, we will process the <em>Wine</em> data into separate training and test sets — using a 70:30 split — and standardize it to unit variance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eaad2b967b2d260dcf6e2b769a734be/href">https://medium.com/media/1eaad2b967b2d260dcf6e2b769a734be/href</a></iframe><p>After completing the mandatory preprocessing, let’s advance to the second step: constructing the covariance matrix. The symmetric <em>d</em> x <em>d</em>-dimensional covariance matrix, where <em>d</em> is the number of dimensions in the dataset, stores the pairwise covariances between the different features. For example, the covariance between two features <em>x_j</em> and <em>x_k</em> on the population level can be calculated via the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*zsJQIL5ZnHRxxqxz0OxntQ.png" /></figure><p>Here, <em>μ_j</em> and <em>μ_k</em> are the sample means of features <em>j</em> and <em>k</em>, respectively.</p><p>Note that the sample means are zero if we standardized the dataset. A positive covariance between two features indicates that the features increase or decrease together, whereas a negative covariance indicates that the features vary in opposite directions. For example, the covariance matrix of three features can then be written as follows (note that <strong>Σ</strong> stands for the Greek uppercase letter <strong>sigma</strong>, which is not to be confused with the <strong>sum</strong> symbol):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*vyx57OmdL9HXraN-AkBSEw.png" /></figure><p>The eigenvectors of the covariance matrix represent the principal components (the directions of maximum variance), whereas the corresponding eigenvalues will define their magnitude. In the case of the <em>Wine</em> dataset, we would obtain 13 eigenvectors and eigenvalues from the 13 x 13-dimensional covariance matrix.</p><p>Now, for our third step, let’s obtain the eigenpairs of the covariance matrix. An eigenvector <strong><em>v</em></strong> satisfies the following condition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/68/1*noDBksvur0Y3mi0zeyy9dg.png" /></figure><p>Here, <strong>λ</strong> is a scalar: the eigenvalue. Since the manual computation of eigenvectors and eigenvalues is a somewhat tedious and elaborate task, we will use the linalg.eig function from NumPy to obtain the eigenpairs of the <em>Wine</em> covariance matrix:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fef250a980eee8c5051669949cf9af4/href">https://medium.com/media/2fef250a980eee8c5051669949cf9af4/href</a></iframe><p>Using the numpy.cov function, we computed the covariance matrix of the standardized training dataset. Using the linalg.eig function, we performed the eigendecomposition, which yielded a vector (eigen_vals) consisting of 13 eigenvalues and the corresponding eigenvectors stored as columns in a 13 x 13-dimensional matrix (eigen_vecs).</p><h3>Total and Explained Variance</h3><p>Since we want to reduce the dimensionality of our dataset by compressing it onto a new feature subspace, we only select the subset of the eigenvectors (principal components) that contains most of the information (variance). The eigenvalues define the magnitude of the eigenvectors, so we have to sort the eigenvalues by decreasing magnitude; we are interested in the top <em>k</em> eigenvectors based on the values of their corresponding eigenvalues.</p><p>But before we collect those <em>k</em> most informative eigenvectors, let’s plot the <strong>variance explained ratios</strong> of the eigenvalues. The variance explained ratio of an eigenvalue <em>λ_j</em> is simply the fraction of an eigenvalue <em>λ_j</em> and the total sum of the eigenvalues:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/63/1*e3Ud73T1QZaock4MBb-lMw.png" /></figure><p>Using the NumPy cumsum function, we can then calculate the cumulative sum of explained variances, which we will then plot via matplotlib’s step function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f443a322ddb5e6ab5f49cddd12aa4ead/href">https://medium.com/media/f443a322ddb5e6ab5f49cddd12aa4ead/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*buXqasMp7vA6aPqdMkp2XA.png" /></figure><p>The resulting plot indicates that the first principal component alone accounts for approximately 40% of the variance. Also, we can see that the first two principal components combined explain almost 60% of the variance in the dataset.</p><h3>Feature Transformation</h3><p>After we have successfully decomposed the covariance matrix into eigenpairs, let’s now proceed with the last three steps of PCA to transform the <em>Wine</em> dataset onto the new principal component axes.</p><p>We will sort the eigenpairs by descending order of the eigenvalues, construct a projection matrix from the selected eigenvectors, and use the projection matrix to transform the data onto the lower-dimensional subspace.</p><p>We start by sorting the eigenpairs by decreasing order of the eigenvalues:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee7a540b8c894b680e48de4229400dad/href">https://medium.com/media/ee7a540b8c894b680e48de4229400dad/href</a></iframe><p>Next, we collect the two eigenvectors that correspond to the two largest eigenvalues, to capture about 60% of the variance in this dataset. Note that we only chose two eigenvectors for the purpose of illustration, since we are going to plot the data via a two-dimensional scatter plot later in this subsection. In practice, the number of principal components has to be determined by a trade-off between computational efficiency and the performance of the classifier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36d02f52ab46b460b4b9ef29fbaa8e23/href">https://medium.com/media/36d02f52ab46b460b4b9ef29fbaa8e23/href</a></iframe><pre>[Out:]<br>Matrix W:<br> [[-0.13724218  0.50303478]<br> [ 0.24724326  0.16487119]<br> [-0.02545159  0.24456476]<br> [ 0.20694508 -0.11352904]<br> [-0.15436582  0.28974518]<br> [-0.39376952  0.05080104]<br> [-0.41735106 -0.02287338]<br> [ 0.30572896  0.09048885]<br> [-0.30668347  0.00835233]<br> [ 0.07554066  0.54977581]<br> [-0.32613263 -0.20716433]<br> [-0.36861022 -0.24902536]<br> [-0.29669651  0.38022942]]</pre><p>By executing the preceding code, we have created a 13 x 2-dimensional projection matrix <strong><em>W</em></strong> from the top two eigenvectors.</p><p>Using the projection matrix, we can now transform a sample <strong><em>x</em></strong> (represented as a 1 x 13-dimensional row vector) onto the PCA subspace (the principal components one and two) obtaining <strong><em>x′</em></strong>, now a two-dimensional sample vector consisting of two new features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/76/1*nuYZrTF8trabAfJq-3wVcA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/839008ca37aa04d4538d2acef173407f/href">https://medium.com/media/839008ca37aa04d4538d2acef173407f/href</a></iframe><p>Similarly, we can transform the entire 124 x 13-dimensional training dataset onto the two principal components by calculating the matrix dot product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*Lo1e06UOCLsKPjJaeiNcDQ.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/feb00d2823fed13d658c398283aee0e3/href">https://medium.com/media/feb00d2823fed13d658c398283aee0e3/href</a></iframe><p>Lastly, let’s visualize the transformed <em>Wine</em> training set, now stored as an 124 x 2-dimensional matrix, in a two-dimensional scatterplot:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8ac54065d72379910a72115c1b67304/href">https://medium.com/media/c8ac54065d72379910a72115c1b67304/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*3mAQhYWFt5vcsa_bE9qYqw.png" /></figure><p>As we can see in the resulting plot, the data is more spread along the <em>x</em>-axis — the first principal component — than the second principal component (<em>y</em>-axis), which is consistent with the explained variance ratio plot that we created previously. However, we can intuitively see that a linear classifier will likely be able to separate the classes well.</p><p>Although we encoded the class label information for the purpose of illustration in the preceding scatter plot, we have to keep in mind that PCA is an unsupervised technique that does not use any class label information.</p><h3>PCA in scikit-learn</h3><p>Although the verbose approach in the previous subsection helped us to follow the inner workings of PCA, we will now discuss how to use the PCA class implemented in scikit-learn. The PCA class is another one of scikit-learn’s transformer classes, where we first fit the model using the training data before we transform both the training data and the test dataset using the same model parameters.</p><p>Let’s use the PCA class on the <em>Wine</em> training dataset, classify the transformed samples via logistic regression:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de1bf012d594ca14e285bb559ab58696/href">https://medium.com/media/de1bf012d594ca14e285bb559ab58696/href</a></iframe><p>Now, using a custom plot_decision_regions function, we will visualize the decision regions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89595e0b2c567777fc174f241122e6cd/href">https://medium.com/media/89595e0b2c567777fc174f241122e6cd/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*lIFV-5PzduL3aoqCb85gcw.png" /></figure><p>By executing the preceding code, we should now see the decision regions for the training data reduced to two principal component axes.</p><p>For the sake of completeness, let’s plot the decision regions of the logistic regression on the transformed test dataset as well to see if it can separate the classes well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2af48b8e04a01ab631825640dc1f35aa/href">https://medium.com/media/2af48b8e04a01ab631825640dc1f35aa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*WotGez5Twhp0SP1B8c4OAg.png" /></figure><p>After we plotted the decision regions for the test set by executing the preceding code, we can see that logistic regression performs quite well on this small two-dimensional feature subspace and only misclassifies very few samples in the test dataset.</p><p>If we are interested in the explained variance ratios of the different principal components, we can simply initialize the PCA class with the n_components parameter set to None, so all principal components are kept and the explained variance ratio can then be accessed via the explained_variance_ratio_ attribute:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32a67ec6d5309190227d63fe46574a1e/href">https://medium.com/media/32a67ec6d5309190227d63fe46574a1e/href</a></iframe><p>Note that we set n_components=None when we initialized the PCA class so that it will return all principal components in a sorted order instead of performing a dimensionality reduction.</p><p>I hope you enjoyed this tutorial on principal component analysis for dimensionality reduction! We covered the mathematics behind the PCA algorithm, how to perform PCA step-by-step with Python, and how to implement PCA using scikit-learn. Other techniques for dimensionality reduction are <strong>Linear Discriminant Analysis</strong> (LDA) and <strong>Kernel PCA</strong> (used for non-linearly separable data).</p><p><em>These other techniques and more topics to improve model performance, such as data preprocessing, model evaluation, hyperparameter tuning, and ensemble learning techniques are covered in Next Tech’s </em><strong><em>Python Machine Learning (Part 2)</em></strong><em> course.</em></p><p><em>You can get started </em><a href="https://c.next.tech/2vZveOh"><em>here</em></a><em> for free!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=115a3d157bad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/principal-component-analysis-for-dimensionality-reduction-115a3d157bad">Principal Component Analysis for Dimensionality Reduction</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classification and Regression Analysis with Decision Trees]]></title>
            <link>https://medium.com/data-science/https-medium-com-lorrli-classification-and-regression-analysis-with-decision-trees-c43cdbc58054?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c43cdbc58054</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[decision-tree]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Wed, 15 May 2019 20:35:22 GMT</pubDate>
            <atom:updated>2019-05-16T18:24:17.968Z</atom:updated>
            <content:encoded><![CDATA[<h4>By understanding the fundamental concepts and mathematics behind decision trees, learn to build classification and regression decision trees!</h4><p>A <strong>decision tree</strong> is a supervised machine learning model used to predict a target by learning decision rules from features. As the name suggests, we can think of this model as breaking down our data by making a decision based on asking a series of questions.</p><p>Let&#39;s consider the following example in which we use a decision tree to decide upon an activity on a particular day:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WerHJ14JQAd3j8ASaVjAhw.jpeg" /></figure><p>Based on the features in our training set, the decision tree model learns a series of questions to infer the class labels of the samples. As we can see, decision trees are attractive models if we care about interpretability.</p><p>Although the preceding figure illustrates the concept of a decision tree based on categorical targets (<strong>classification</strong>), the same concept applies if our targets are real numbers (<strong>regression</strong>).</p><p>In this tutorial, we will discuss how to build a decision tree model with Python’s scikit-learn library. We will cover:</p><ul><li>The fundamental concepts of decision trees</li><li>The mathematics behind the decision tree learning algorithm</li><li>Information gain and impurity measures</li><li>Classification trees</li><li>Regression trees</li></ul><p>Let’s get started!</p><blockquote>This tutorial is adapted from Next Tech’s <strong>Python Machine Learning</strong> series which takes you through machine learning and deep learning algorithms with Python from 0 to 100. It includes an in-browser sandboxed environment with all the necessary software and libraries pre-installed, and projects using public datasets. You can get started <a href="https://c.next.tech/2E7k6Dy">here</a>!</blockquote><h3>The Fundamentals of Decision Trees</h3><p>A decision tree is constructed by <strong>recursive partitioning</strong> — starting from the root node (known as the first <strong>parent</strong>), each node can be split into left and right <strong>child</strong> nodes. These nodes can then be further split and they themselves become parent nodes of their resulting children nodes.</p><p>For example, looking at the image above, the root node is Work to do? and splits into the child nodes Stay in and Outlook based on whether or not there is work to do. The Outlook node further splits into three child nodes.</p><p>So, how do we know what the optimal splitting point is at each node?</p><p>Starting from the root, the data is split on the feature that results in the largest <strong>Information Gain</strong> (<strong>IG</strong>) (explained in more detail below). In an iterative process, we then repeat this splitting procedure at each <strong>child node</strong> until the leaves are pure — i.e. samples at each node all belong to the same class.</p><p>In practice, this can result in a very deep tree with many nodes, which can easily lead to overfitting. Thus, we typically want to <strong>prune</strong> the tree by setting a limit for the maximal depth of the tree.</p><h3>Maximizing Information Gain</h3><p>In order to split the nodes at the most informative features, we need to define an objective function that we want to optimize via the tree learning algorithm. Here, our objective function is to maximize the information gain at each split, which we define as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*CHsongM23EQUzvzzcWa2Pg.png" /></figure><p>Here, <em>f</em> is the feature to perform the split, <em>Dp</em>, <em>Dleft</em>, and <em>Dright</em> are the datasets of the parent and child nodes, <em>I</em> is the <strong>impurity measure</strong>, <em>Np</em> is the total number of samples at the parent node, and <em>Nleft</em> and <em>Nright</em> are the number of samples in the child nodes.</p><p>We will discuss impurity measures for classification and regression decision trees in more detail in our examples below. But for now, just understand that information gain is simply the difference between the impurity of the parent node and the sum of the child node impurities — the lower the impurity of the child nodes, the larger the information gain.</p><p>Note that the above equation is for binary decision trees — each parent node is split into two child nodes only. If you have a decision tree with multiple nodes, you would simply sum the impurity of all nodes.</p><h3>Classification Trees</h3><p>We will start by talking about classification decision trees (also known as <strong>classification trees</strong>). For this example, we will be using the <a href="https://archive.ics.uci.edu/ml/datasets/iris"><em>Iris</em></a> dataset, a classic in the field of machine learning. It contains the measurements of 150 <em>Iris</em> flowers from three different species — <em>Setosa</em>, <em>Versicolor</em>, and <em>Virginica</em>. These will be our <strong>targets</strong>. Our goal is to predict which category an <em>Iris</em> flower belongs to. The petal length and width in centimeters are stored as columns, which we also call the <strong>features</strong> of the dataset.</p><p>Let’s first import the dataset and assign the features as X and the target as y:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f77242c5a49727a518ff221dfed6510/href">https://medium.com/media/7f77242c5a49727a518ff221dfed6510/href</a></iframe><p>Using scikit-learn, we will now train a decision tree with a maximum depth of 4. The code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/455a4c3c285809157ba263597d904383/href">https://medium.com/media/455a4c3c285809157ba263597d904383/href</a></iframe><p>Notice that we set the criterion as ‘<strong>entropy</strong>’. This criterion is known as the impurity measure (mentioned in the previous section). In classification, entropy is the most common impurity measure or splitting criteria. It is defined by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/1*TrGRS0Y7nokqAggvbdEClA.png" /></figure><p>Here, <em>p(i|t)</em> is the proportion of the samples that belong to class <em>c</em> for a particular node <em>t</em>. The entropy is therefore 0 if all samples at a node belong to the same class, and the entropy is maximal if we have a uniform class distribution.</p><p>For a more visual understanding of entropy, let’s plot the impurity index for the probability range [0, 1] for class 1. The code is as follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e649800c677389df9b1726d04a02bce9/href">https://medium.com/media/e649800c677389df9b1726d04a02bce9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*8BIEFvLcFv6e2WDC_P8gMA.png" /></figure><p>As you can see, entropy is 0 if ​<em>p(i=1|t) = 1</em>. If the classes are distributed uniformly with <em>p(i=1|t) = 0.5</em>​, entropy is 1.</p><p>Now, returning to our <em>Iris</em> example, we will visualize our trained classification tree and see how entropy decides each split.</p><p>A nice feature in scikit-learn is that it allows us to export the decision tree as a .dot file after training, which we can visualize using <a href="http://www.graphviz.org/">GraphViz</a>, for example. In addition to GraphViz, we will use a Python library called pydotplus, which has capabilities similar to GraphViz and allows us to convert .dot data files into a decision tree image file.</p><p>You can install pydotplus and graphviz by executing the following commands in your Terminal:</p><pre>pip3 install pydotplus<br>apt install graphviz</pre><p>The following code will create an image of our decision tree in PNG format:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1401fadd26ef9d604586d5fba532a773/href">https://medium.com/media/1401fadd26ef9d604586d5fba532a773/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*z4zWVweDtHJzq4Ky5eOAHg.png" /><figcaption>tree.png</figcaption></figure><p>Looking at the resulting decision tree figure saved in the image file tree.png, we can now nicely trace back the splits that the decision tree determined from our training dataset. We started with 150 samples at the root and split them into two child nodes with 50 and 100 samples, using the <strong>petal width</strong> cut-off ≤ 1.75 cm. After the first split, we can see that the left child node is already pure and only contains samples from the setosa class (entropy = 0). The further splits on the right are then used to separate the samples from the versicolor and virginica class.</p><p>Looking at the final entropy we see that the decision tree with a depth of 4 does a very good job of separating the flower classes.</p><h3>Regression Trees</h3><p>We will be using the <a href="https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html"><em>Boston Housing</em></a> dataset for our regression example. This is another very popular dataset which contains information about houses in the suburbs of Boston. There are 506 samples and 14 attributes. For simplicity and visualization purposes, we will only use two — MEDV (median value of owner-occupied homes in $1000s) as the target and LSTAT (percentage of lower status of the population) as the feature.</p><p>Let’s first import the necessary attributes from scikit-learn into a pandas DataFrame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eed429243423542bf58aeec14c9857c/href">https://medium.com/media/2eed429243423542bf58aeec14c9857c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*1pSpTGA6A1rY4WCgIBUm0g.png" /></figure><p>Let’s use the DecisionTreeRegressor implemented in scikit-learn to train a regression tree:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cbee93f418a5f1271f12b189403fa57/href">https://medium.com/media/8cbee93f418a5f1271f12b189403fa57/href</a></iframe><p>Notice that our criterion is different from the one we used for our classification tree. Entropy as a measure of impurity is a useful criteria for classification. To use a decision tree for regression, however, we need an impurity metric that is suitable for continuous variables, so we define the impurity measure using the <strong>weighted mean squared error</strong> (<strong>MSE</strong>) of the children nodes instead:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/260/1*6wRtInhGhxoX_Y7W9OR14Q.png" /></figure><p>Here, <em>Nt</em> is the number of training samples at node <em>t</em>, <em>Dt</em> is the training subset at node <em>t</em>, <em>y(i) </em>is the true target value, and <em>ŷt</em>​ is the predicted target value (sample mean):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/141/1*DylF2sjY6k3Cw7HE8vtYrA.png" /></figure><p>Now, let’s model the relationship between MEDV and LSTAT to see what the line fit of a regression tree looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ed5e1ee29173448140326c1ce9ec52c/href">https://medium.com/media/1ed5e1ee29173448140326c1ce9ec52c/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*Edq1ZIOo26Iqp3CuUTWotA.png" /></figure><p>As we can see in the resulting plot, the decision tree of depth 3 captures the general trend in the data.</p><p>I hope you enjoyed this tutorial on decision trees! We discussed the fundamental concepts of decision trees, the algorithms for minimizing impurity, and how to build decision trees for both classification and regression.</p><p>In practice, it is important to know how to choose an appropriate value for a depth of a tree to not overfit or underfit the data. Knowing how to combine decision trees to form an ensemble <strong>random forest</strong> is also useful as it usually has a better generalization performance than an individual decision tree due to randomness, which helps to decrease the model’s variance. It is also less sensitive to outliers in the dataset and doesn’t require much parameter tuning.</p><p><em>We cover these techniques in our </em><strong><em>Python Machine Learning</em></strong><em> series, as well as diving into other machine learning models such as perceptrons, Adaline, linear and polynomial regression, logistic regression, SVMs, kernel SVMs, k-nearest-neighbors, models for sentiment analysis, k-means clustering, DBSCAN, convolutional neural networks, and recurrent neural networks.</em></p><p><em>We also look at other topics such as regularization, data processing, feature selection and extraction, dimensionality reduction, model evaluation, ensemble learning techniques, and deploying a machine learning model.</em></p><p><em>You can get started </em><a href="https://c.next.tech/2E7k6Dy"><em>here</em></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c43cdbc58054" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/https-medium-com-lorrli-classification-and-regression-analysis-with-decision-trees-c43cdbc58054">Classification and Regression Analysis with Decision Trees</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Perform Exploratory Data Analysis with Seaborn]]></title>
            <link>https://medium.com/data-science/how-to-perform-exploratory-data-analysis-with-seaborn-97e3413e841d?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e3413e841d</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Tue, 19 Feb 2019 07:36:48 GMT</pubDate>
            <atom:updated>2019-02-19T07:36:48.622Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Exploratory Data Analysis</strong> (<strong>EDA</strong>) is an approach to analyzing datasets to summarize their main characteristics. It is used to understand data, get some context regarding it, understand the variables and the relationships between them, and formulate hypotheses that could be useful when building predictive models.</p><p>All data analysis must be guided by some key questions or objectives. Before starting any data analysis tasks, you should have a clear goal in mind. When your goal allows you to understand your data and the problem, you will be in a good position to get meaningful results out of your analysis!</p><p>In this tutorial, we will learn how to perform EDA using <strong>data visualization.</strong> Specifically, we will focus on <strong>seaborn</strong>, a Python library that is built on top of matplotlib and has support for NumPy and pandas.</p><p>seaborn allows us to make attractive and informative statistical graphics. Although matplotlib makes it possible to visualize essentially anything, it is often difficult and tedious to make the plots visually attractive. seaborn is often used to make default matplotlib plots look nicer, and also introduces some additional plot types.</p><p>We will cover how to visually analyze:</p><ul><li>Numerical variables with histograms,</li><li>Categorical variables with count plots,</li><li>Relationships between numerical variables with scatter plots, joint plots, and pair plots, and</li><li>Relationships between numerical and categorical variables with box-and-whisker plots and complex conditional plots.</li></ul><p>By effectively visualizing a dataset’s variables and their relationships, a data analyst or data scientist is able to quickly understand trends, outliers, and patterns. This understanding can then be used to tell a story, drive decisions, and create predictive models.</p><h4>This brief tutorial is adapted from Next Tech’s full <a href="https://c.next.tech/2GbmOdL">Data Analysis with Python course</a>, which includes an in-browser sandboxed environment with Python, Jupyter Notebooks, and seaborn pre-installed. You can get started with this course for free!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6dEIMHU6c0CM9cBoNlNog.png" /><figcaption>Next Tech’s environment.</figcaption></figure><h3>Data Preparation</h3><blockquote>Data preparation is the first step of any data analysis to ensure data is cleaned and transformed in a form that can be analyzed.</blockquote><p>We will be performing EDA on the <a href="http://jse.amstat.org/v19n3/decock.pdf">Ames Housing dataset</a>. This dataset is popular among those beginning to learn data science and machine learning as it contains data about almost every characteristic of different houses that were sold Ames, Iowa. This data can then be used to try to predict sale prices.</p><p>This dataset is already cleaned and ready for analysis. All we will be doing is filtering some variables to simplify our task. Let’s begin by reading our data as a pandas DataFrame:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d25d534ab9abbd64c0529926b7b695e/href">https://medium.com/media/5d25d534ab9abbd64c0529926b7b695e/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*zALCMp8RV1CcNIFu9MjAGg.png" /><figcaption>This image only shows the info for the first five columns in the dataset.</figcaption></figure><p>If you run this code in Next Tech’s sandbox which already has the dataset imported, or in a Jupyter notebook, you can see that there are 1,460 observations and 81 columns. Each column represents a variable in the DataFrame. We can see from the data type of each column what type of variable it is.</p><p>We will only be working with some of the variables — let’s filter and store their names in two lists called numerical and categorical, then redefine our housing DataFrame to contain only these variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92575493bf0e1f03316c23bd06972319/href">https://medium.com/media/92575493bf0e1f03316c23bd06972319/href</a></iframe><pre>Out: (1460, 14)</pre><p>From housing.shape, we can see that our DataFrame now only has 14 columns. Let’s move onto some analysis!</p><h3>Analyzing Numerical Variables</h3><blockquote>Our EDA objective will be to understand how the variables in this dataset relate to the sale price of the house.</blockquote><p>Before we can do that, we need to first understand our variables. Let’s start with numerical variables, specifically our target variable, SalePrice.</p><p>Numerical variables are simply those for which the values are numbers. The first thing that we do when we have numerical variables is to understand what values the variable can take, as well as the distribution and dispersion. This can be achieved with a <strong>histogram</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d50c7e619a6ef5002410873be22a283/href">https://medium.com/media/9d50c7e619a6ef5002410873be22a283/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*be69RBODmS3f9b7r0RqO2g.png" /><figcaption>Distribution of the SalePrice variable.</figcaption></figure><p>Note that, due to <a href="https://stackoverflow.com/questions/41499857/seaborn-why-import-as-sns/44484758">an inside joke</a>, the seaborn library is imported as sns.</p><p>With just one method sns.set(), we are able to style our figure, change the color, increase font size for readability, and change the figure size.</p><p>We use distplot to plot histograms in seaborn. This by default plots a histogram with a kernel density estimation (KDE). You can try changing the parameter kde=True to see what this looks like.</p><p>Taking a look at the histogram, we can see that very few houses are priced below 100,000, most of the houses sold between 100,000 and 200,000, and very few houses sold for above 400,000.</p><p>If we want to create histograms for all of our numerical variables, pandas offers the simplest solution:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b4d924240ccae4afac77e78023d6da5/href">https://medium.com/media/2b4d924240ccae4afac77e78023d6da5/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nS4TqarCxNfIMrMUnQF3Wg.png" /><figcaption>Distributions for each of our numerical variables.</figcaption></figure><p>From this visualization, we get a lot of information. We can see that 1stFlrSF (square footage of the first floor) is heavily skewed right, most houses do not have a second floor, and have 3 BedroomAbvGr (bedrooms above ground). Most houses were sold at an OverallCond of 5 and an OverallQual of 5 or higher. The LotArea visual is more difficult to decipher — however we can tell that there is one or more outliers that may need to be removed before any modeling.</p><p>Note that the figure keeps the style that we set previously using seaborn.</p><h3>Analyzing Categorical Variables</h3><p>Categorical variables are those for which the values are labeled categories. The values, distribution, and dispersion of categorical variables are best understood with <strong>bar plots</strong>. Let’s analyze the SaleCondition variable. seaborn gives us a very simple method to show the counts of observations in each category: the countplot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8221004b2521e45f739fd3c56a531ea7/href">https://medium.com/media/8221004b2521e45f739fd3c56a531ea7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*Oif2VnHEu25O8Q3QKAzfgg.png" /><figcaption>The bars in this plot represent the number of houses for each condition of sale.</figcaption></figure><p>From the visualization, we can easily see that most houses were sold in Normal condition, and very few were sold in AjdLand (adjoining land purchase), Alloca (allocation: two linked properties with separate deeds), and Family (sale between family members) conditions.</p><p>In order to visualize all the categorical variables in our dataset, just as we did with the numerical variables, we can loop through pandas series to create subplots.</p><p>Using plt.subplots, we can create a figure with a grid of 2 rows and 4 columns. Then we iterate over every categorical variable to create a countplot with seaborn:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c0e09e5d9ffa9b38e4a3ba3a678cda8/href">https://medium.com/media/8c0e09e5d9ffa9b38e4a3ba3a678cda8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*cIOI1p56qlHaLAbb6MxrKg.png" /><figcaption>Countplots for each of our categorical variables.</figcaption></figure><p>The second for loop simply gets each <em>x</em>-tick label and rotates it 90 degrees to make the text fit on the plots better (you can remove these two lines if you want to know how the text looks without rotation).</p><p>As with our numerical variable histograms, we can gather lots of information from this visual — most houses have RL (Residential Low Density) zoning classification, have Regular lot shape, and have CentralAir. We can also see that houses were sold more frequently during the summer months, the most houses were sold in the NAmes (North Ames) neighborhood, and there was a dip in sale in 2010.</p><p>However, if we inspect the YrSold variable further, we can see that this “dip” is actually due to the fact that only data up to July was collected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37d357295243a2a92ac78ac0782fbfe7/href">https://medium.com/media/37d357295243a2a92ac78ac0782fbfe7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*AIPgzkZnIrXZzRA2m1vQRg.png" /></figure><p>As you can see, thorough exploration of variables and their values is incredibly important — if we built a model to predict sale prices under the assumption that there was a decrease in sales in 2010, this model would likely be very inaccurate.</p><p>Now that we have explored our numerical and categorical variables, let’s take a look at the relationship between these variables — more importantly, how these variables impact our target variable, SalePrice!</p><h3>Analyzing Relationships Between Numerical Variables</h3><blockquote>Plotting relationships between variables allows us to easily get a visual understanding of patterns and correlations.</blockquote><p>The <strong>scatter plot</strong> is often used for visualizing relationships between two numerical variables. The seaborn method to create a scatter plot is very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eed7050523c43e15652c5d72a09ea47/href">https://medium.com/media/3eed7050523c43e15652c5d72a09ea47/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*L1lvlbUkm-ylB4oQotZ_bQ.png" /><figcaption>Relationship between 1stFlrSF and SalePrice.</figcaption></figure><p>From the scatter plot, we see here that we have a positive relationship between the 1stFlrSF of the house and the SalePrice of the house. In other words, the larger the first floor of a house, the higher the likely sale price.</p><p>You can also see that the axis labels are added for us by default, and the markers are automatically outlined to make them clearer — this is opposed to matplotlib in which these are not the default.</p><p>seaborn also provides us with a nice function called jointplot which will give you a scatter plot showing the relationship between two variables along with histograms of each variable in the margins — also known as a <strong>marginal plot</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4a13f66bf2f5fad50a7b08b9e23bb67/href">https://medium.com/media/e4a13f66bf2f5fad50a7b08b9e23bb67/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*Irmw82_jLxiMq5lrvKDIpQ.png" /><figcaption>Jointplot showing relationship between 1stFlrSF and SalePrice and their individual distributions.</figcaption></figure><p>Not only can you see the relationships between the two variables, but also how they are distributed individually.</p><h3>Analyzing Relationships Between Numerical and Categorical Variables</h3><p>The <strong>box-and-whisker plot</strong> is commonly used for visualizing relationships between numerical variables and categorical variables, and <strong>complex conditional plots</strong> are used to visualize conditional relationships.</p><p>Let’s start by creating box-and-whisker plots with seaborn’s boxplot method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45e4a773b584f0db609d9eea634d91b9/href">https://medium.com/media/45e4a773b584f0db609d9eea634d91b9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*6M7VVIgi7rI3-QAkQ9_KpA.png" /><figcaption>Box-and-whisker plots for each of our categorical variables and their relationships with SalePrice.</figcaption></figure><p>Here, we have iterated through every subplot to produce the visualization between all categorical variables and the SalePrice.</p><p>We can see that houses with FV (Floating Village Residential) zoning classification have a higher average SalePrice than other zoning classifications, as do houses with CentralAir, and houses with a Partial (home not completed when last assessed) SaleCondition. We can also see that there is little variance in average SalePrice between houses with different LotShapes, or between MoSold and YrSold.</p><p>Let’s take a closer look at the Neighborhood variable. We see that there is definitely a different distribution for different neighborhoods, but the visualization is a bit difficult to decipher. Let’s sort our box plots by cheapest neighborhood to most expensive (by median price) using the additional argument order.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22a924184dc1b62c06ffec0a101fb858/href">https://medium.com/media/22a924184dc1b62c06ffec0a101fb858/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*dXH4YyPEHbUNl6Nuz8eBHA.png" /><figcaption>Sorted box-and-whisker plot showing relationship between Neighborhood and SalePrice.</figcaption></figure><p>In the above snippet, we sorted our neighborhoods by median price and stored this in sorted_nb. Then, we passed this list of neighborhood names into the order argument to create a sorted box plot.</p><p>This figure gives us a lot of information. We can see that in the cheapest neighborhoods houses sell for a median price of around $100,000, and in the most expensive neighborhoods houses sell for around $300,000. We can also see that for some neighborhoods, dispersion between the prices is very low, meaning that all the prices are close to each other. In the most expensive neighborhood NridgHt, however, we see a large box — there is large dispersion in the distribution of prices.</p><p>Finally, seaborn also allows us to create plots that show conditional relationships. For example, if we are conditioning on the Neighborhood, using the FacetGrid function we can visualize a scatter plot between the OverallQual and the SalePrice variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd44e7ff946ec6ce5c1540899127e5be/href">https://medium.com/media/dd44e7ff946ec6ce5c1540899127e5be/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*6i6Lt9njKRC7J5-Nhv1ymQ.png" /><figcaption>This image only shows the first 12 plots. There are actually 25 plots — one for each neighborhood.</figcaption></figure><p>For each individual neighborhood we can see the relationship between OverallQual and SalePrice.</p><p>We also added another categorical variable CentralAir to the (optional) hue parameter — the orange points correspond to houses that do not have CentralAir. As you can see, these houses tend to sell at a lower price.</p><p>The FacetGrid method makes it incredibly easy to produce complex visualizations and to get valuable information. It is good practice to produce these visualizations to get quick insights about variable relationships.</p><p>I hope you’ve enjoyed this brief tutorial on exploratory data analysis and data visualization with seaborn! I covered how to create histograms, count plots, scatter plots, marginal plots, box-and-whisker plots, and conditional plots.</p><p>During our exploration, we discovered outliers and trends within individual variables, and relationships between variables. This knowledge can be used to build a model to predict the SalePrice of houses in Ames. For example, since we found a correlation between SalePrice and the variables CentralAir, 1stFlrSf, SaleCondition, and Neighborhood, we can start with a simple model using these variables.</p><h4>If you are interesting in learning how to do this and more, we have a full <strong>Data Analysis with Python</strong> course available at Next Tech. Get started for free <a href="https://c.next.tech/2GbmOdL">here</a>!</h4><p>This course explores vectorizing operations with NumPy, EDA using pandas, data visualization with matplotlib, additional EDA and visualization techniques using seaborn, statistical computing with SciPy, and machine learning with scikit-learn.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e3413e841d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/how-to-perform-exploratory-data-analysis-with-seaborn-97e3413e841d">How to Perform Exploratory Data Analysis with Seaborn</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Linear Regression in Python]]></title>
            <link>https://medium.com/data-science/introduction-to-linear-regression-in-python-c12a072bedf0?source=rss-37b1fe31b4bf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c12a072bedf0</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Lorraine Li]]></dc:creator>
            <pubDate>Wed, 24 Oct 2018 19:51:49 GMT</pubDate>
            <atom:updated>2019-02-05T18:40:20.997Z</atom:updated>
            <content:encoded><![CDATA[<h4>A quick tutorial on how to implement linear regressions with the Python statsmodels &amp; scikit-learn libraries.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*G1Y_-X14q2xMVHlUuaUUdA.png" /><figcaption>Example linear regression model using simulated data</figcaption></figure><p><strong>Linear regression</strong> is a basic predictive analytics technique that uses historical data to predict an output variable. It is popular for predictive modelling because it is easily understood and can be explained using plain English.</p><p>Linear regression models have many real-world applications in an array of industries such as economics (e.g. predicting growth), business (e.g. predicting product sales, employee performance), social science (e.g. predicting political leanings from gender or race), healthcare (e.g. predicting blood pressure levels from weight, disease onset from biological factors), and more.</p><p>Understanding how to implement linear regression models can unearth stories in data to solve important problems. We’ll use Python as it is a robust tool to handle, process, and model data. It has an array of packages for linear regression modelling.</p><p>The basic idea is that if we can fit a linear regression model to observed data, we can then use the model to predict any future values. For example, let’s assume that we have found from historical data that the price (<strong><em>P</em></strong>) of a house is linearly dependent upon its size (<strong><em>S</em></strong>) — in fact, we found that a house’s price is exactly 90 times its size. The equation will look like this:</p><p><em>P = 90*S</em></p><p>With this model, we can then predict the cost of any house. If we have a house that is 1,500 square feet, we can calculate its price to be:</p><p><em>P = 90*1500 = $135,000</em></p><p>In this blog post, we cover:</p><ol><li>The basic concepts and mathematics behind the model</li><li>How to implement linear regression from scratch using simulated data</li><li>How to implement linear regression using statsmodels</li><li>How to implement linear regression using scikit-learn</li></ol><h4>This brief tutorial is adapted from the Next XYZ <a href="https://c.next.tech/2G9Hlzn">Linear Regression with Python</a> course, which includes an in-browser sandboxed environment, tasks to complete, and projects using public datasets.</h4><h3>Basic concepts and mathematics</h3><p>There are two kinds of variables in a linear regression model:</p><ul><li>The <strong>input</strong> or <strong>predictor variable</strong> is the variable(s) that help predict the value of the output variable. It is commonly referred to as <strong><em>X</em></strong>.</li><li>The <strong>output variable</strong> is the variable that we want to predict. It is commonly referred to as <strong><em>Y</em></strong>.</li></ul><p>To estimate <em>Y</em> using linear regression, we assume the equation:</p><blockquote><strong><em>Yₑ = α + β X</em></strong></blockquote><p>where <em>Y</em>ₑ is the estimated or predicted value of <em>Y</em> based on our linear equation.</p><p>Our goal is to find statistically significant values of the <strong>parameters <em>α</em></strong> and<strong> <em>β</em></strong> that minimise the difference between <em>Y</em> and <em>Y</em>ₑ.</p><p>If we are able to determine the optimum values of these two parameters, then we will have the <strong>line of best fit</strong> that we can use to predict the values of <em>Y</em>, given the value of <em>X</em>.</p><p>So, how do we estimate <em>α</em> and <em>β</em>? We can use a method called <a href="https://en.wikipedia.org/wiki/Ordinary_least_squares"><strong>ordinary least squares</strong></a>.</p><h4>Ordinary Least Squares</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*VVA0rF6MWXcw1JmRNFA87g.png" /><figcaption>Green lines show the difference between actual values Y and estimate values <em>Y</em>ₑ</figcaption></figure><p>The objective of the least squares method is to find values of <em>α</em> and <em>β</em> that minimise the sum of the squared difference between <em>Y</em> and <em>Y</em>ₑ. We will not go through the derivation here, but using calculus we can show that the values of the unknown parameters are as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*gR-W7RFar9ijxwAa" /></figure><p>where <em>X̄ </em>is the mean of <em>X</em> values and <em>Ȳ</em> is the mean of <em>Y</em> values.</p><p>If you are familiar with statistics, you may recognise <em>β</em> as simply <br><em>Cov(X, Y) / Var(X).</em></p><h3>Linear Regression From Scratch</h3><p>In this post, we’ll use two Python modules:</p><ul><li><a href="https://www.statsmodels.org/stable/index.html">statsmodels</a> — a module that provides classes and functions for the estimation of many different statistical models, as well as for conducting statistical tests, and statistical data exploration.</li><li><a href="http://scikit-learn.org/stable/">scikit-learn</a> — a module that provides simple and efficient tools for data mining and data analysis.</li></ul><p>Before we dive in, it is useful to understand how to implement the model from scratch. Knowing how the packages work behind the scenes is important so you are not just blindly implementing the models.</p><p>To get started, let’s simulate some data and look at how the predicted values (<em>Y</em>ₑ) differ from the actual value (<em>Y</em>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/712e6ebab40aa7b25ebc8d43a778d128/href">https://medium.com/media/712e6ebab40aa7b25ebc8d43a778d128/href</a></iframe><p>If the above code is run (e.g. in a Jupyter notebook), this would output something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*UEdpbXeIsCvxdg4tQvPjpA.png" /></figure><p>To estimate <em>y</em> using the OLS method, we need to calculate xmean and ymean, the covariance of <em>X</em> and <em>y</em> (xycov), and the variance of <em>X</em> (xvar) before we can determine the values for alpha and beta.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4d7d1e7f33e39974681c9707259a063/href">https://medium.com/media/f4d7d1e7f33e39974681c9707259a063/href</a></iframe><pre><strong>Out:</strong><br>alpha = 2.0031670124623426<br>beta = 0.32293968670927636</pre><p>Great, we now have an estimate for alpha and beta! Our model can be written as <em>Yₑ = 2.003 + 0.323 X,</em>​ and we can make predictions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e7baa85d6590b9a5f1d2423c38c965/href">https://medium.com/media/70e7baa85d6590b9a5f1d2423c38c965/href</a></iframe><pre><strong>Out:</strong><br>array([3.91178282, 2.81064315, 3.27775989, 4.29675991, 3.99534802,<br>       1.69857201, 3.25462968, 2.36537842, 2.40424288, 2.81907292,<br>       ...<br>       2.16207195, 3.47451661, 2.65572718, 3.2760653 , 2.77528867,<br>       3.05802784, 2.49605373, 3.92939769, 2.59003892, 2.81212234])</pre><p>Let’s plot our prediction ypred against the actual values of y, to get a better visual understanding of our model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/907fdd42e079f17d5604c80baba50c21/href">https://medium.com/media/907fdd42e079f17d5604c80baba50c21/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*Cf9q9CQ-SNuplvzuchk0mA.png" /></figure><p>The blue line is our line of best fit, <em>Yₑ = 2.003 + 0.323 X. </em>We can see from this graph that there is a positive linear relationship between <em>X</em> and <em>y</em>. Using our model, we can predict <em>y</em> from any values of <em>X</em>!</p><p>For example, if we had a value <em>X = 10</em>, we can predict that:<br><em>Yₑ = 2.003 + 0.323 (10) = 5.233.</em></p><h3>Linear Regression with statsmodels</h3><p>Now that we have learned how to implement a linear regression model from scratch, we will discuss how to use the ols method in the statsmodels library.</p><p>To demonstrate this method, we will be using a very popular advertising dataset about various costs incurred on advertising by different mediums and the sales for a particular product. You can download this dataset <a href="http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv">here</a>.</p><p>We will only be looking at the TV variable in this example — we will explore whether TV advertising spending can predict the number of sales for the product. Let’s start by importing this csv file as a pandas dataframe using read_csv():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f81708db5f1abf5c9c775a3177de98/href">https://medium.com/media/00f81708db5f1abf5c9c775a3177de98/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/310/1*TJVgeBufWNGVbvrJlI5DhQ.png" /></figure><p>First, we use statsmodels’ ols function to initialise our simple linear regression model. This takes the formula y ~ X, where X is the predictor variable (TV advertising costs) and y is the output variable (Sales). Then, we fit the model by calling the OLS object’s fit() method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c27422cd85b1a18d81901082409626/href">https://medium.com/media/71c27422cd85b1a18d81901082409626/href</a></iframe><p>We no longer have to calculate alpha and beta ourselves as this method does it automatically for us! Calling model.params will show us the model’s parameters:</p><pre><strong>Out:</strong><br>Intercept    7.032594<br>TV           0.047537<br>dtype: float64</pre><p>In the notation that we have been using, <em>α</em> is the intercept and <em>β</em> is the slope i.e. <em>α</em> = 7.032 and <em>β</em> = 0.047.</p><p>Thus, the equation for the model will be: <strong><em>Sales = 7.032 + 0.047*TV</em></strong></p><p>In plain English, this means that, on average, if we spent $100 on TV advertising, we should expect to sell 11.73 units.</p><p>Now that we’ve fit a simple regression model, we can try to predict the values of sales based on the equation we just derived using the .predict method.</p><p>We can also visualise our regression model by plotting sales_pred against the TV advertising costs to find the line of best fit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad902f160386c1b3e851816fdcff0aa/href">https://medium.com/media/cad902f160386c1b3e851816fdcff0aa/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*M9KtWbx17EDWabLS31-mlA.png" /></figure><p>We can see that there is a positive linear relationship between TV advertising costs and Sales — in other words, spending more on TV advertising predicts a higher number of sales!</p><p>With this model, we can predict sales from any amount spent on TV advertising. For example, if we increase TV advertising costs to $400, we can predict that sales will increase to 26 units:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6fe5afa2b6a386d390b3c13fecf4ea3/href">https://medium.com/media/d6fe5afa2b6a386d390b3c13fecf4ea3/href</a></iframe><pre><strong>Out:</strong><br>0    26.04725<br>dtype: float64</pre><h3>Linear Regression with scikit-learn</h3><p>We’ve learnt to implement linear regression models using statsmodels…now let’s learn to do it using scikit-learn!</p><p>For this model, we will continue to use the advertising dataset but this time we will use two predictor variables to create a <strong>multiple linear regression model</strong>. This is simply a linear regression model with more than one predictor, and is modelled by:</p><p><strong><em>Yₑ = α + β₁X₁ + β₂X₂ + … + βₚXₚ, </em></strong>where <em>p</em> is the number of predictors.</p><p>In our example, we will be predicting Sales using the variables TV and Radio i.e. our model can be written as:</p><p><em>Sales = α + β₁*TV + β₂*Radio.</em></p><p>First, we initialise our linear regression model, then fit the model to our predictors and output variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb877524ed2b2de34bf5bd5d2cd12208/href">https://medium.com/media/bb877524ed2b2de34bf5bd5d2cd12208/href</a></iframe><p>Again, there is no need to calculate the values for alpha and betas ourselves – we just have to call .intercept_ for alpha, and .coef_ for an array with our coefficients beta1 and beta2:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/21f67dfece27b4fbefbdd903365fdb1b/href">https://medium.com/media/21f67dfece27b4fbefbdd903365fdb1b/href</a></iframe><pre><strong>Out:</strong><br>alpha = 2.921099912405138<br>betas = [0.04575482 0.18799423]</pre><p>Therefore, our model can be written as:</p><p><em>Sales = 2.921 + 0.046*TV + 0.1880*Radio.</em></p><p>We can predict values by simply using .predict():</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2692401f510c1e9cb336309e30b8402/href">https://medium.com/media/f2692401f510c1e9cb336309e30b8402/href</a></iframe><pre><strong>Out:</strong><br>array([20.555464, 12.345362, 12.337017, 17.617115, 13.223908,<br>       12.512084, 11.718212, 12.105515,  3.709379, 12.551696,<br>       ...<br>       12.454977,  8.405926,  4.478859, 18.448760, 16.4631902,<br>        5.364512,  8.152375, 12.768048, 23.792922, 15.15754285])</pre><p>Now that we’ve fit a multiple linear regression model to our data, we can predict sales from any combination of TV and Radio advertising costs! For example, if we wanted to know how many sales we would make if we invested $300 in TV advertising and $200 in Radio advertising…all we have to do is plug in the values!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ddfee815a8a5cb7851255dfbffc8975/href">https://medium.com/media/9ddfee815a8a5cb7851255dfbffc8975/href</a></iframe><pre><strong>Out:</strong><br>[54.24638977]</pre><p>This means that if we spend $300 on TV advertising and $200 on Radio advertising, we should expect to see, on average, 54 units sold.</p><p>I hope you enjoyed this brief tutorial about the basics of linear regression!</p><p>We covered how to implement linear regression from scratch and by using statsmodels and scikit-learn in Python. In practice, you will have to know how to validate your model and measure efficacy, how to select significant variables for your model, how to handle categorical variables, and when and how to perform non-linear transformations.</p><h4>We have a full course covering all these topics (and more!) <a href="https://c.next.tech/2G9Hlzn">here</a> at Next XYZ if you’re interested in learning more about linear regression with Python!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c12a072bedf0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/introduction-to-linear-regression-in-python-c12a072bedf0">Introduction to Linear Regression in Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>