<?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 AI+ Port Harcourt on Medium]]></title>
        <description><![CDATA[Stories by AI+ Port Harcourt on Medium]]></description>
        <link>https://medium.com/@dsnph?source=rss-f197e2364a64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by AI+ Port Harcourt on Medium</title>
            <link>https://medium.com/@dsnph?source=rss-f197e2364a64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 01:10:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dsnph/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[Extracting Data From a Database]]></title>
            <link>https://medium.com/swlh/searching-through-a-database-52eaaf64f89c?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/52eaaf64f89c</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[filters]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sat, 12 Dec 2020 22:57:53 GMT</pubDate>
            <atom:updated>2022-04-25T07:04:51.049Z</atom:updated>
            <content:encoded><![CDATA[<p>Filtering Data with Queries</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*k3ktPyyr3fbKDGef" /><figcaption>Photo by <a href="https://unsplash.com/@nate_dumlao?utm_source=medium&amp;utm_medium=referral">Nathan Dumlao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>SQL or Sequel is the standard language for communicating with relational databases. Creating or modifying databases using queries is an important skill for data scientists or analysts as databases are one of the most common sources of data.</p><p>Any well meaning company or organization keeps its own data. This data may include consumer information, purchase or sale, inventory and so on. A database is simply a collection of related data. A database is made up of tables which in turn are made up of fields.</p><p>We will be working with a sample SALES database of an e-commerce company courtesy of my training with <a href="https://twitter.com/digitalxplorer">Digital Explorers</a>.</p><p>The database has 3 tables:</p><ul><li>BasketProducts</li><li>Products</li><li>Baskets</li></ul><h3>SQL Basics</h3><p>One of the main advantages of SQL is its simple syntax. These simple <em>clauses</em> can be combined in any number of ways to make complex queries. The basic SQL syntax is the SELECT statement. It is usually the first statement of an SQL query. The basic order of writing an SQL query is as follows:</p><pre>SELECT<br>FROM<br>WHERE<br>GROUP BY<br>HAVING<br>ORDER BY<br>LIMIT</pre><p>These are the basic SQL commands. They are executed in the following sequence:</p><pre>FROM<br>WHERE<br>GROUP BY<br>HAVING<br>SELECT<br>ORDER BY<br>LIMIT</pre><p>The SELECT statement indicates the data you want to be displayed. This can be a selection of columns or calculated fields.</p><p>The FROM clause indicates the table where SQL should search for the fields specified in the SELECT clause. If the column/field does not exist in the table, we get an error.</p><pre>SELECT * <br>FROM Baskets<br>LIMIT 5</pre><p>The above query will return the complete Baskets table — all rows and columns. The LIMIT command is used to select the top n rows.</p><pre>user_id    basket_id      event_time        abandond   discount<br>473613801   12878    2019-12-01 00:17:50        1        0.0<br>547853931   12879    2019-12-01 00:20:47        0        0.0<br>433063720   12880    2019-12-01 00:25:37        1        0.0<br>494077766   12881    2019-12-01 00:26:15        0        0.0<br>579950721   12882    2019-12-01 00:43:51        0        0.0</pre><p>To select specific columns, the column names are specified with the SELECT clause. The column names can also be saved under a different alias using AS with the SELECT statement.</p><pre>SELECT basket_id AS Customers, abandond<br>FROM Baskets<br>LIMIT 5</pre><pre><br><strong>OUTPUT:</strong></pre><pre>Customers abandond<br>12878        1<br>12879        0<br>12880        1<br>12881        0<br>12882        0</pre><p>Columns can also be computed in SQL. Below is the calculation of Profit expected from each item in the store in descending order. Simple calculations in SQL include MIN, MAX, COUNT, AVERAGE, SUM.</p><pre>SELECT price-cost AS Profit<br>FROM Products<br>ORDER BY Profit DESC<br>LIMIT 10</pre><pre>OUTPUT:</pre><pre>Profit<br>115.12<br>96.59<br>84.08<br>81.03<br>74.14<br>70.81<br>68.01<br>58.66<br>57.04<br>55.66</pre><h3>Filtering Data with SQL</h3><p>To filter through the records/rows in SQL, you need the WHERE clause. Using a combination of functions or characters with the WHERE clause allows us to select specific portions of our data. We will focus on the Baskets and Products table in our database.</p><h4>Using ‘=’</h4><p>To make exact matches across rows in our table, we use the equals sign. Below are examples for numeric and text data types. Note that we enclose text data in quotes when using the equals sign. The equals sign is case sensitive and text data must match exactly.</p><blockquote>To view customers who completed purchases (did not abandon cart)</blockquote><pre>SELECT *<br>FROM Baskets<br>WHERE abandond = 0;</pre><blockquote>To filter products of a particular brand</blockquote><pre>SELECT *<br>FROM Products<br>WHERE brand = &#39;runail&#39;;</pre><h4>Using Relational Expressions</h4><p>We can also combine the WHERE clause with relational expressions. These expressions include</p><ul><li>&gt; or&lt;: Selects rows with values greater than or less than a specified value</li><li>&gt;=: Selects rows with values greater than or equal to a given value</li><li>&lt;= : Selects rows with values less than or equal to a given value</li></ul><pre>-- Which customers had discount less than 25%</pre><pre>SELECT user_id, discount<br>FROM Baskets<br>WHERE discount &lt; 0.25</pre><p>The above query will return the columns<strong> <em>user_id</em></strong> and <strong><em>discount</em></strong> columns for customers who had discount less than 25%. We can include customers with 25% discount by using &lt;= .</p><p>To select only customers with 25% discount, we use== or =.</p><h4>Using Logical Expressions</h4><p>These logical expressions follow the same rules as in math. We specify condition(s) which we want to be <em>met</em>. With the <strong>AND</strong> operation, both conditions have to be <strong>TRUE</strong>, while with the <strong>OR</strong> operator, only one of the conditions has to be <strong>TRUE</strong>. The NOT operator negates the condition specified. Logical expressions include:</p><ul><li>AND <strong>&amp;</strong>: Used when two conditions must be strictly met</li><li>OR<strong> |</strong>: Only one of the specified conditions has to be met</li><li>NOT : Negates the condition specified</li></ul><pre>-- Number of customers who did not abandon their cart and had 25% discount</pre><pre>SELECT COUNT(user_id) as USERS<br>FROM Baskets<br>WHERE (abandond=0) &amp; (discount == 0.25)</pre><pre>OUTPUT:</pre><pre>USERS<br>966</pre><p>Another example:</p><pre>-- How many customers had discount of 25% or did not abandon their carts</pre><pre>SELECT count(user_id) as USERS<br>FROM Baskets<br>WHERE(abandond = 0) | (discount = 0.25);</pre><pre>OUTPUT:</pre><pre>USERS<br>20730</pre><p>Notice the change in the number of users because of a change in logical operator.</p><pre>-- How many users did not have 25% discount and did not complete their purchase</pre><pre>SELECT count(user_id) as USERS<br>FROM Baskets<br>WHERE NOT((abandond = 0) &amp; (discount == 0.25));</pre><pre>OUTPUT:</pre><pre>USERS<br>24642</pre><p>These operations can be combined to make complex queries if need be.</p><h4>WHERE … IN</h4><p>If you want to make a selection from a limited number of options, the WHERE… IN clause is just the thing for you.</p><pre>-- Which customers had discounts of either 15% or 50%</pre><pre>SELECT *<br>FROM Baskets<br>WHERE discount IN(0.15,0.5)<br>LIMIT 10</pre><p>Our Output:</p><pre><strong>user_id</strong>   <strong>basket_id</strong>       <strong>event_time</strong>      <strong>abandond</strong>   <strong>discount</strong><br>356011474   12889     2019-12-01 01:18:32     1         0.5<br>556337981   12892     2019-12-01 02:00:03     0         0.15<br>580026195   12917     2019-12-01 04:25:54     1         0.5<br>562396937   12921     2019-12-01 04:52:51     0         0.15<br>559344368   12938     2019-12-01 06:00:09     1         0.15<br>580100376   12974     2019-12-01 07:31:33     0         0.5<br>490632556   12976     2019-12-01 07:32:04     1         0.5<br>458855541   13006     2019-12-01 08:24:11     0         0.15<br>506885505   13030     2019-12-01 08:57:35     0         0.5<br>528539896   13039     2019-12-01 09:14:41     0         0.5</pre><p>We can also negate the WHERE...IN clause using WHERE...NOT IN . If we negate the example above, we will get all customers who did not get 15% or 50% discount.</p><h4>WHERE…BETWEEN</h4><p>To select data within a range, we can also use the WHERE…BETWEEN clause. What differentiates this clause from &lt; or &gt; is that this is inclusive of the boundaries. It is similar to &lt;= or &gt;= in this regard.</p><pre>-- Which customers have discounts between 15% and 50%</pre><pre>SELECT *<br>FROM Baskets<br>WHERE discount BETWEEN 0.15 AND 0.5<br>LIMIT 10;</pre><p>Output:</p><pre><strong>user_id    basket_id       event_time       abandond   discount</strong><br>356011474    12889    2019-12-01 01:18:32      1         0.5<br>556337981    12892    2019-12-01 02:00:03      0         0.15<br>580026195    12917    2019-12-01 04:25:54      1         0.5<br>562396937    12921    2019-12-01 04:52:51      0         0.15<br>559344368    12938    2019-12-01 06:00:09      1         0.15<br>571600331    12942    2019-12-01 06:25:50      0         0.25<br>557560536    12943    2019-12-01 06:26:22      0         0.25<br>534305618    12973    2019-12-01 07:26:17      0         0.25<br>580100376    12974    2019-12-01 07:31:33      0         0.5<br>490632556    12976    2019-12-01 07:32:04      1         0.5</pre><h4>WHERE…LIKE</h4><p>The WHERE…LIKE clause is used when the exact term to match is unknown. We can use this clause in conjunction with wildcards at the beginning or end of the match word.</p><p>If we want to search for a particular brand from the Products table but cannot remember the full name of the brand, we can make a query search using portions we know. Below is a query search for a brand that ends with ‘-nail’.</p><pre>SELECT *<br>FROM Products<br>WHERE brand LIKE &quot;%nail&quot;<br>LIMIT 10;</pre><p>OUTPUT:</p><pre>product_id    brand    price    cost<br>4554          runail   0.38     0.32<br>4600          runail   0.38     0.2<br>4607          runail   0.38     0.19<br>4640          runail   0.37     0.35<br>4689          runail   0.38     0.26<br>4768          runail   0.38     0.26<br>4820          runail   0.38     0.27<br>4870          runail   0.38     0.28<br>5887055      jessnail  1.1      0.88<br>5894905      jessnail  1.1      0.9</pre><p>The LIKE clause is not case sensitive, and therefore we get the same result as before when we run the query below:</p><pre>SELECT *<br>FROM Products<br>WHERE brand LIKE &quot;%NAIL&quot;<br>LIMIT 10;</pre><h3>General SQL Conventions</h3><p><strong>SQL is not case sensitive</strong>. Code can be written in capital or small letters. It is however, good practice to capitalize SQL commands such as SELECT, FROM, WHERE, ORDER BY, ALTER, DROP etc.</p><p><strong>The data stored in SQL tables are case sensitive</strong>. To match a data in SQL table, it must be in the same format. To get over this, use the LIKE command or its variation depending on the RDBMS.</p><p><strong>Avoid Spaces in Table and Variable names.</strong> In our queries above, we did not have to enclose column names in quotes even when we used the AS command. If these column names had spaces, we would need to specify these names in quotes so that SQL understands that it is one name.</p><p><strong>SQL ignores white space in code</strong>. The code below will run without errors.</p><pre>SELECT                        basket_id<br>FROM Baskets<br>LIMIT                5;</pre><p><strong>The arrangement of SQL is not strict</strong> and the command above can also be written in a single line.</p><pre>SELECT basket_id  FROM Baskets LIMIT  5;</pre><p>It is however good practice to write SQL across several lines with a different command clause. This improves readability and makes it easy to spot errors.</p><p><strong>Not all SQL requires you to end code with a semi-colon</strong>. So make sure to check this feature on your RDBMS.</p><p><strong>Use comments</strong>. This is a general rule when coding. Comments make our queries easier to read and understand. With comments, we are able to follow the thought process behind the program or in this case, query.</p><h3>CONCLUSION</h3><p>SQL is fairly simple to learn and write. While the SQL syntax is general across different RDBMS, small variations may exist. Be sure to check for this when switching to a new RDBMS.</p><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52eaaf64f89c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/searching-through-a-database-52eaaf64f89c">Extracting Data From a Database</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Natural Language Processing]]></title>
            <link>https://medium.com/swlh/introducing-natural-language-processing-ada16af343da?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada16af343da</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 19:46:50 GMT</pubDate>
            <atom:updated>2022-04-25T07:28:53.276Z</atom:updated>
            <content:encoded><![CDATA[<p>A beginner’s guide to NLP and extracting insight from text data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*S1t9ugkY7Nr8wdAG" /><figcaption>Photo by <a href="https://unsplash.com/@taypaigey?utm_source=medium&amp;utm_medium=referral">Taylor Wilcox</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Before we had computers, papers, ink or Lead to make pencils, human communication was oral. Languages evolved and with it, structure and semantics. Languages went from strictly oral form to oral and written form. NLP is the process of making machines understand human language — text or speech.</p><p>Natural Language Processing (NLP) has gained more popularity and advancement over the years. The ability to draw insight from text data has opened a world of opportunities. Text data is abundant, from books to tweets, movie or product review, transcripts, meeting proceedings and health records.</p><p>With Natural language Processing techniques, Machine Learning and Deep learning, we can turn this jumble of data into valuable insight.</p><p>While these text data are numerous, they pose a problem. They are largely unstructured and have to be converted into a format which algorithms can understand. Here we will go through the applications of NLP, data preprocessing for text data and extracting features from text data.</p><h3>Applications of NLP</h3><ul><li>Understanding consumer’s reaction to product or service also known as <strong>Sentiment Analysis</strong></li><li>Extract topics from text or document: Topic Modelling</li><li>Text classification, product classification</li><li>Chatbox and AI assistants</li><li>Search Engines</li><li>Text to Speech, Speech to Text</li><li>Language detection and translation</li><li>Text summarization</li><li>Predicting next sequence of words: Text generation</li><li>Speech recognition</li></ul><p>Python has become a leading programming language for NLP because of its simplicity and text processing ability. Python has an inbuilt text data structure known as the string. The string manipulations available in Python as well as its support for NLP libraries makes it a good start for processing text data.</p><p>Some important libraries when dealing with text data include:</p><ul><li>Regular Expressions or RegEx</li><li>Pandas</li><li>NLTK</li><li>Numpy</li><li>SpaCy</li><li>TextBlob</li><li>CoreNLP</li><li>Wordcloud</li></ul><h3><strong>Python Strings</strong></h3><p>The string data structure in python is a collection of characters enclosed in single or double quotes. A string is a body of text. Though it may contain numbers or other characters, once enclosed in quotes, those characters are classified as text data.</p><p>The python string has common operations that are handy when preprocessing text data. These operations include <em>lower()</em> which is used to standardized the format of all text by making all lowercase.</p><p><em>string.punctuation</em> is an inbuilt string constant that contains all punctuations. It is useful in removal of punctuations from text which is an important text preprocessing step.</p><p>Common string operations for text preprocessing are shown below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aef6a2c88a3bb073f8d52383fb67795/href">https://medium.com/media/4aef6a2c88a3bb073f8d52383fb67795/href</a></iframe><p>Read the Python string methods <a href="https://docs.python.org/3/library/stdtypes.html#string-methods">documentation</a> for more information.</p><h3><strong>Regular Expressions</strong></h3><p>Depending on the source of text data, our text may contain html tags, URLs, punctuations, emoticons, numbers or unwanted symbols.</p><p>Regular Expression is a sequence of characters used to matching or search for a pattern within a text. RegEx is used in text data preprocessing much like the python string. RegEx are special characters which can be used to match a pattern quickly, making it a useful tool for text preprocessing.</p><p>We will use some regular expressions later on. Read the Python regular expression <a href="https://docs.python.org/3/library/re.html">guide</a> to learn some of these expressions.</p><h3><strong>Steps in Text Preprocessing</strong></h3><p>Text preprocessing are the steps taken in order to transform our text data into a form understandable by algorithms.</p><p>These include:</p><h4>Making all text lowercase</h4><p>This is the most basic step in processing text data. Because Python like many programming languages is case sensitive, one word can be counted as different words if there is a difference in capitalization or casing. The word ‘Explore’ differs from the word ‘explore’ and ‘EXPLORE’.</p><p>During Exploratory Data Analysis of text data, one important feature of text is the number of unique words which form the vocabulary of the text. Therefore, it is important that all text are in the same format so a word does not appear more than once.</p><p>To be fair, capitalizing all text does the same but <em>lowercasing</em> is much more appealing to the eyes and has become the convention over time. This can be simply achieved by applying the Python string <em>lower() </em>method.</p><pre>s = &#39;Hello, I am new here and i am happy to meet you&#39;</pre><p>In the above string, the words<strong> <em>I</em></strong> and<strong> <em>i</em></strong> will be counted as two separate words.</p><pre>s.lower()<br>&gt;&gt; &#39;hello, i am new here and i am happy to meet you&#39;</pre><p>We can also apply the lower() method across data frames.</p><pre><strong>#This applies the <em>lower</em> method across a specified column</strong><br>df[&#39;text&#39;] = df[&#39;text&#39;].apply(lambda x: &quot;&quot;.join(x.lower() for x in x.split()))</pre><h4>Remove all punctuations</h4><p>Text data processing is quite unique. We have to remove characters and symbols that do not add any value or information including punctuations, URLs, emoticons etc. Regex offers us a simple way to achieve this in python. As shown above, the built-in python <em>string.punctuation</em> can also be used to remove punctuations<em>.</em></p><pre>#Using Regex<br>import re<br>string.sub(r&#39;[^\w\s]&#39;,&#39; &#39;,string)</pre><h4>Remove Stop Words</h4><p>Stop words are common words that have little or no meaning in a text. By removing stop words, we are able to focus our attention on words that add meaning or keywords.</p><p>During human speech or writing, there are words that occur frequently but do not in fact add to the general meaning or understanding of a sentence.</p><p>The NLTK library has a stop words corpus which contains frequent stop words. We can use this to remove stop words in text. You need to have the NLTK library installed and download NLTK corpus.</p><pre>#Let&#39;s take a look at nltk stop words</pre><pre>import nltk<br>nltk.download()<br>from nltk.corpus import stopwords</pre><pre>#remove stop words<br>stop = stopwords.words(&#39;english&#39;)<br>print(stop)</pre><p>This will print out the NLTK English stop words</p><pre>[&#39;i&#39;, &#39;me&#39;, &#39;my&#39;, &#39;myself&#39;, &#39;we&#39;, &#39;our&#39;, &#39;ours&#39;, &#39;ourselves&#39;, &#39;you&#39;, &quot;you&#39;re&quot;, &quot;you&#39;ve&quot;, &quot;you&#39;ll&quot;, &quot;you&#39;d&quot;, &#39;your&#39;, &#39;yours&#39;, &#39;yourself&#39;, &#39;yourselves&#39;, &#39;he&#39;, &#39;him&#39;, &#39;his&#39;, &#39;himself&#39;, &#39;she&#39;, &quot;she&#39;s&quot;, &#39;her&#39;, &#39;hers&#39;, &#39;herself&#39;, &#39;it&#39;, &quot;it&#39;s&quot;, &#39;its&#39;, &#39;itself&#39;, &#39;they&#39;, &#39;them&#39;, &#39;their&#39;, &#39;theirs&#39;, &#39;themselves&#39;, &#39;what&#39;, &#39;which&#39;, &#39;who&#39;, &#39;whom&#39;, &#39;this&#39;, &#39;that&#39;, &quot;that&#39;ll&quot;, &#39;these&#39;, &#39;those&#39;, &#39;am&#39;, &#39;is&#39;, &#39;are&#39;, &#39;was&#39;, &#39;were&#39;, &#39;be&#39;, &#39;been&#39;, &#39;being&#39;, &#39;have&#39;, &#39;has&#39;, &#39;had&#39;, &#39;having&#39;, &#39;do&#39;, &#39;does&#39;, &#39;did&#39;, &#39;doing&#39;, &#39;a&#39;, &#39;an&#39;, &#39;the&#39;, &#39;and&#39;, &#39;but&#39;, &#39;if&#39;, &#39;or&#39;, &#39;because&#39;, &#39;as&#39;, &#39;until&#39;, &#39;while&#39;, &#39;of&#39;, &#39;at&#39;, &#39;by&#39;, &#39;for&#39;, &#39;with&#39;, &#39;about&#39;, &#39;against&#39;, &#39;between&#39;, &#39;into&#39;, &#39;through&#39;, &#39;during&#39;, &#39;before&#39;, &#39;after&#39;, &#39;above&#39;, &#39;below&#39;, &#39;to&#39;, &#39;from&#39;, &#39;up&#39;, &#39;down&#39;, &#39;in&#39;, &#39;out&#39;, &#39;on&#39;, &#39;off&#39;, &#39;over&#39;, &#39;under&#39;, &#39;again&#39;, &#39;further&#39;, &#39;then&#39;, &#39;once&#39;, &#39;here&#39;, &#39;there&#39;, &#39;when&#39;, &#39;where&#39;, &#39;why&#39;, &#39;how&#39;, &#39;all&#39;, &#39;any&#39;, &#39;both&#39;, &#39;each&#39;, &#39;few&#39;, &#39;more&#39;, &#39;most&#39;, &#39;other&#39;, &#39;some&#39;, &#39;such&#39;, &#39;no&#39;, &#39;nor&#39;, &#39;not&#39;, &#39;only&#39;, &#39;own&#39;, &#39;same&#39;, &#39;so&#39;, &#39;than&#39;, &#39;too&#39;, &#39;very&#39;, &#39;s&#39;, &#39;t&#39;, &#39;can&#39;, &#39;will&#39;, &#39;just&#39;, &#39;don&#39;, &quot;don&#39;t&quot;, &#39;should&#39;, &quot;should&#39;ve&quot;, &#39;now&#39;, &#39;d&#39;, &#39;ll&#39;, &#39;m&#39;, &#39;o&#39;, &#39;re&#39;, &#39;ve&#39;, &#39;y&#39;, &#39;ain&#39;, &#39;aren&#39;, &quot;aren&#39;t&quot;, &#39;couldn&#39;, &quot;couldn&#39;t&quot;, &#39;didn&#39;, &quot;didn&#39;t&quot;, &#39;doesn&#39;, &quot;doesn&#39;t&quot;, &#39;hadn&#39;, &quot;hadn&#39;t&quot;, &#39;hasn&#39;, &quot;hasn&#39;t&quot;, &#39;haven&#39;, &quot;haven&#39;t&quot;, &#39;isn&#39;, &quot;isn&#39;t&quot;, &#39;ma&#39;, &#39;mightn&#39;, &quot;mightn&#39;t&quot;, &#39;mustn&#39;, &quot;mustn&#39;t&quot;, &#39;needn&#39;, &quot;needn&#39;t&quot;, &#39;shan&#39;, &quot;shan&#39;t&quot;, &#39;shouldn&#39;, &quot;shouldn&#39;t&quot;, &#39;wasn&#39;, &quot;wasn&#39;t&quot;, &#39;weren&#39;, &quot;weren&#39;t&quot;, &#39;won&#39;, &quot;won&#39;t&quot;, &#39;wouldn&#39;, &quot;wouldn&#39;t&quot;]</pre><p>To remove stop words from text data:</p><pre>import nltk<br>#nltk.download()<br>from nltk.corpus import stopwords<br>text = &#39;&#39;&#39;But soft what light through yonder window breaks<br>It is the east and Juliet is the sun<br>Arise fair sun and kill the envious moon<br>Who is already sick and pale with grief&#39;&#39;&#39;</pre><pre>#remove stop words<br>stop = stopwords.words(&#39;english&#39;)</pre><pre>new_text = &quot; &quot;.join(x for x in text.split() if x.lower() not in stop)<br>new_text</pre><p><strong>Output:</strong></p><pre>&#39;soft light yonder window breaks east Juliet sun Arise fair sun kill envious moon already sick pale grief&#39;</pre><h4>Tokenizing Text</h4><p>Tokens are small units of text, they may be sentence tokens but are commonly word tokens. You can call a token the basic unit of a text.</p><p>Tokenization is the process of converting text into these tokens. It is a basic process in NLP, be it traditional NLP or Deep Learning methods.</p><p>The Python <em>spilt</em> method is a basic way to split text into tokens. Libraries such as NLTK, SpaCy and TextBlob can also be used to generate tokens</p><h4>Stemming</h4><p>In linguistics, Stemming is the process of reducing words to their stem or root form. This also holds true in NLP. In stemming, we aim to reduce different forms of a word into a basic form and therefore, have them counted as one word rather than multiple words. Stemming reduces our text vocabulary making search and retrieval easy to carry out.</p><p>Stemming works by cutting off unnecessary prefixes or suffixes leaving a root word.</p><h4>Lemmatization</h4><p>Similar to stemming, lemmatization reduces words into their root word or lemma based on vocabulary. In lemmatization, several forms of a word are mapped into one word.</p><blockquote>One difference between stemming and lemmatization is that stemming looks crude. Stemming looks like all variations of a word were placed on top one another and then the excesses were hacked off with a saw leaving the root word behind.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bc224e79b6218b3338e8eb7a1c35983/href">https://medium.com/media/8bc224e79b6218b3338e8eb7a1c35983/href</a></iframe><h4>Exploring Text Data</h4><p>The Exploration of text data is similar to that of numeric data. Some common features to look out for in text data include:</p><ul><li>The number of words in the text</li><li>Frequency of all words, words that occur very frequently without adding any meaning to the text can also be added to Stop words</li><li>Mean word length</li><li>Number of unique words</li><li>Plotting a word cloud — Word clouds are plots used to visualize text data</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dqurMTYkOV011XQW9Gi5Pw.png" /><figcaption>Word Cloud showing words associated with Disaster and Non-disaster tweets from Kaggle Dataset</figcaption></figure><h3>Extracting Features from Text Data</h3><p>As earlier discussed, most algorithms cannot process text data as they are. Just as we convert categorical data into numerical features before fitting to a model, we have to convert text data into numerical features. One Hot Encoding, can be applied to text data. However, if you have a large amount of text data, you run the risk of having numerous columns created causing high dimensionality.</p><p>For text data, we will discuss two common text engineering practices: Count Vectorizer and Tf-Idf.</p><h3>Bag of Words</h3><p>In simple terms, Bag of words is a vector of all unique words in a text. This collection of unique words form the vocabulary of the text. It is referred to as Bag of Words because it is a collection of text disregarding word order and grammar.</p><h4>CountVectorizer</h4><p>The Count Vectorizer from sklearn is an easy way to create a Bag of Words vectors. The count vectorizer returns an array that consisting of the number of times each word from the vocabulary appears in each text. It can also be made into a data frame with feature names as columns.</p><p>Imagine looking through a dataset containing various random tweets. Fitting the data to count vectorizer extracts all unique words to form a vocabulary. An array is created with count values corresponding to the number of times a particular word appears in a single tweet. It does not matter what position this word occurs, only that it occurs. All words have the same unit weight and therefore, the same importance. If a word appears three times in a text, its count value is 3, likewise if it appears a thousand times in a tweet, it has a count value of 1000.</p><p>Read the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html">CountVectorizer </a>documentation for more details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6aa80fb1f0dff900ee90dab7ad2d3c1/href">https://medium.com/media/e6aa80fb1f0dff900ee90dab7ad2d3c1/href</a></iframe><h4>Tf-idf</h4><p>A good way to deal with frequently occurring words is using Term Frequency Inverse Document Frequency (Tf-idf).</p><p>The Tf-Idf vectorizer assigns weights to each of the words. Using our tweets example, words with higher frequency, appearing in all the tweets have lower weights and therefore, less importance. Words that appear less frequently are given high weight values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd6fe3e2116f2a33ccb29846e0cb6e06/href">https://medium.com/media/bd6fe3e2116f2a33ccb29846e0cb6e06/href</a></iframe><h3>Conclusion</h3><p>We have looked at some of the most basic processes in Natural Language Processing with practical examples. To truly master NLP, make sure to practice some projects of your own. You can find datasets for NLP on Kaggle, Zindi or any public data source.</p><p><a href="https://github.com/AIgbine/NLP-Disaster-Classifier.git">AIgbine/NLP-Disaster-Classifier</a></p><p>I have attached above a full repository on NLP tweets disaster classification so you can take a look. I also found <strong><em>Natural Language Processing Recipes: Unlocking Text Data with Machine Learning and Deep Learning using Python</em></strong><em> </em>an interesting help while learning NLP.</p><p>Other helpful resources for NLP include videos on YouTube of which I found a particular <a href="https://www.youtube.com/playlist?list=PL7qHbYUK0G0oKwpedmafwocmnZmheyxgI">playlist</a> and <a href="https://www.youtube.com/watch?v=xvqsFTUsOmc&amp;t=61s">video</a> helpful.</p><p>Good luck in your NLP journey. May the force be with you.</p><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada16af343da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/introducing-natural-language-processing-ada16af343da">Introducing Natural Language Processing</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Job Roles]]></title>
            <link>https://medium.com/swlh/data-science-job-roles-b82c22462645?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/b82c22462645</guid>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-visualization]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Mon, 09 Nov 2020 05:31:05 GMT</pubDate>
            <atom:updated>2022-04-25T07:27:51.679Z</atom:updated>
            <content:encoded><![CDATA[<p>Who are the data professionals and do we need them?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zwZIOyQ3Ie7WecUY" /><figcaption>Photo by <a href="https://unsplash.com/@alisvisuals?utm_source=medium&amp;utm_medium=referral">Ali Hajian</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data science is a broad field that combines domain knowledge, programming skills, mathematics and statistics in order to draw insight from data. As you may have guessed from the name — Data Science — the work done revolves around data, lots of data.</p><p>I have to admit, when I first heard about Data Science, I thought all individuals who worked in the field were <strong>data scientists</strong>. You can imagine my surprise when I found out that Data Science is not just a job role, but a field encompassing different skills and competencies.</p><blockquote><strong>But they are all Data Scientists right?</strong></blockquote><blockquote>Well, yes and no. They all work in the data science <strong>field</strong>. While indeed there are Data Scientists, there are also other sought after experts in the data world such as the data engineers, data analysts, machine learning engineer etc.</blockquote><blockquote><strong>Why? Don&#39;t they all work with data?</strong></blockquote><blockquote>Yes, they do in fact work with data, but there is a lot of work to be done with data. The position in the data workflow where they interface with data differ as well as the form of data they work with.</blockquote><blockquote>While a single person such as a data scientist can carry out all these functions in a small company, in a larger company with well defined structures, there is usually much more data and infrastructure to handle. Hence it becomes burdensome for one person to do all the work.</blockquote><blockquote>Also to improve efficiency in company operations, it is practicable that these data tasks are handled by professionals who have honed their skills in such areas such as Database management, Predictive analysis, Data visualization, Machine Learning and the like.</blockquote><p>The data science field is expanding as more companies have realized the importance of data. With these data science job roles are becoming more defined and certain skills and competencies are expected from <em>data professionals</em>. Although your duty may vary slightly from company to company, the basic job roles will remain the same. It is also common that some of the tasks of these professionals are intertwined with one another, so don’t be surprised if you see the same function appear more than one time.</p><p>We will go through the roles of the data analyst, data scientist, database administrator, machine learning engineer and data engineer taking note of their job descriptions, tools used and skills required for each role. It is also good to note that some of the skills and skills are similar.</p><h3><strong>Essential data science skills include:</strong></h3><h4>Data Collection and Preparation</h4><p>To work with data, we need data. The data collection process includes all processes and methods through which data is collected for analysis. While there are free datasets available in sites such as Kaggle or Google datasets.</p><p>There are many ways to acquire data sets too, a simple Google form or survey form is a basic source of data which can then be stored in databases. One can also acquire data through web scrapping though this should be done with caution.</p><p>When analyzing data, it is also common to access data in databases, making SQL an important skill for any data professional.</p><p>Data preparation is the process of making data suitable for use. We don’t always get structured data and even when we do, we can have missing data, unnamed columns and the likes. These issues are taken care of during data preparation.</p><h4>Data visualization</h4><p>Data visualization is an important aspect when working with data. From exploring data to discover trends and patterns to carrying out some basic statistics on the data and even reporting the findings from the data, Data visualization plays a key role in the data science process.</p><p>Data visualization can be carried out using business intelligence tools such as Tableau, Power BI, flourish and lots more. These tools are more than just visualizing tools as some basic analysis and operations can be carried out on data without having to code. Yes, you read that right. Although, some have plug-ins for popular languages such as R and Python.</p><p>These <em>Business Intelligence tools</em> as they are commonly called are also powerful. For example, you can connect Power BI to your database and edit queries if need be. You can check your BI software to see available data sources you can connect to.</p><h4>Programming</h4><p>Some level of programming is also required depending on your job role. It can be an added competitive advantage that sets you apart from other candidates.</p><p>While an in-depth knowledge of programming is not required, a sound knowledge of SQL is a good way to get your foot in the door. SQL which stands for Structured Query Language is the <em>database language</em>. As data professionals, working with databases is a part of everyday life by extension creating, reading, updating or deleting these databases. You should be careful with deleting though.</p><p>Data scientists are also well versed in R and/or Python, as well as some other programming languages that allow you work with data such as C, C++ and Java.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*519KROnuPhhvm3HxnEBtaw.png" /></figure><h3>Your Data Science Team</h3><h4>Data Analyst</h4><p>Data Analysts perform a number of tasks including collecting data, carrying out statistical analysis, building data models and reporting. It is the data analysts job to turn data into useful insight for the company.</p><p>They work closely with business managers to identify the company needs which will determine the data they work on and the analysis method carried out. The data analyst makes use of Spreadsheets, Databases, visualization and reporting tools.</p><p>The skill set required for Data analysts include:</p><ul><li>SQL</li><li>R</li><li>Python</li><li>JavaScript</li><li>HTML</li><li>C/C++</li><li>Database systems</li><li>Data visualization</li><li>Mathematics and statistics</li><li>Spreadsheet tools</li><li>Presentation skills</li><li>Communication tools</li><li>Machine Learning</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*up19K6rhaPGDB2AkYsin_Q.png" /></figure><h4>Data Scientist</h4><p>Probably the most common job role in data science (and <em>broadest</em>), the Data Scientist is one skilled in computer, statistics, analysis and mathematics.</p><p>The data scientist performs various tasks including exploratory data analysis and carrying out predictive analysis. The data scientist applies machine learning and deep learning techniques on data in order to detect patterns from previous data and use these to predict future events.</p><p>The data scientists uses tools such as MATLAB, Apache Spark, Databases.</p><p>The skill set of data scientists include:</p><p>Programming languages such as:</p><ul><li>SQL</li><li>Python</li><li>R</li><li>MATLAB</li><li>SAS</li></ul><p>A data scientist should also be skilled at:</p><ul><li>Data visualization and storytelling</li><li>Predictive modelling</li><li>Mathematics</li><li>Statistics</li><li>Machine learning</li><li>Data wrangling</li><li>Exploratory Data Analysis</li><li>Ability to use Big Data tools</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1c084_w1WOfU4tU7u1V4OA.png" /></figure><h4>Database Administrator</h4><p>The database administrator is responsible for the management of a companies database. The database administrator plays a key role in the selection of software and hardware components of a database. The also ensure the integrity of the data and ensure the database security. The database administrator essentially acts as the <em>Protector of the data</em>.</p><p>The role of the database administrator cannot be over emphasized. They ensure availability of data and prevent loss of data by implementing data backup and recovering and are in charge of the overall wellbeing of the database.</p><p>Common tools used by database administrators include: phpMyAdmin, MySQL Workbench, SQL Server Management Studio, SQL Web Data Administrator etc.</p><p>The database administrator should be skilled in:</p><ul><li>SQL</li><li>XML</li><li>Python</li><li>C#</li><li>Ruby</li><li>Database queries</li><li>Database design</li><li>Knowledge of Relational Database Management Systems</li><li>Data security</li><li>Data modeling</li><li>Data backup and recovery</li><li>Storage technologies</li><li>Operating systems</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q_RnopKz_RSHT7ALj89qMA.png" /></figure><h4>Data Engineer</h4><p>The insights you draw from data, can only be as good as the data available. The data engineer creates a pipeline or data feed that automates the data collection process to on-site or cloud storage systems. The data engineer makes data easily accessible to end users (such as the data scientists, data analysts), the data engineer is a team player, working hand-in-hand with data scientists and analysts to ensure that the required data is available in the right format for easy analysis.</p><p>The data engineer is in-charge of building and maintaining Extract Transform Load(ETL) pipelines:</p><ul><li>Data extraction from various sources</li><li>transforming the data</li><li>Loading data into destination(database, data warehouse)</li><li>Data synchronization</li></ul><p>The data engineer makes use of such tools as: MS SQL, Dbeaver, Azure, AWS, Spark, Hadoop.</p><p>The skill set of an intending data engineer includes:</p><ul><li>Statistical modeling and regression analysis</li><li>Programming (Python, C++, Java)</li><li>SQL</li><li>Database Systems</li><li>Data warehousing solutions</li><li>Machine Learning</li><li>Data modeling</li><li>Big Data tools — Hadoop</li><li>Data Visualization skills</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WpLySu_hKXUlR-Ga_K_Kbg.png" /></figure><h3>CONCLUSION</h3><p><a href="https://drive.google.com/file/d/1PZWW2ZMCjY_sYLrxtGoOJThksHnqS_BE/view?usp=sharing">Data Science Flashcards.mp4</a></p><p>You can also view <a href="https://www.datacamp.com/community/tutorials/data-science-industry-infographic">DataCamp</a>’s infographic titled, “The Data Science Industry: Who Does What” where some of these roles are outlined. You should check that too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FlzQIpimXD21YhG6OZobNw.png" /></figure><p>We have looked at some key roles in data science. This list is not exhaustive and I advise that you check Job Descriptions before applying for any job role to ensure you are well suited and competent for the role before applying.</p><p>Good luck with your applications!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZ2EkQpcef2dzCZ0UXeCtw.png" /></figure><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b82c22462645" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/data-science-job-roles-b82c22462645">Data Science Job Roles</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bias-Variance Tradeoff]]></title>
            <link>https://medium.com/swlh/the-bias-variance-tradeoff-f24253c0ab45?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/f24253c0ab45</guid>
            <category><![CDATA[bias]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[variance]]></category>
            <category><![CDATA[bias-variance-tradeoff]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 22:26:22 GMT</pubDate>
            <atom:updated>2022-04-25T07:25:05.047Z</atom:updated>
            <content:encoded><![CDATA[<p>How to reduce Bias and Variance error in your model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5S_ggR1vdHPvVQ2C" /><figcaption>Photo by <a href="https://unsplash.com/@cytonn_photography?utm_source=medium&amp;utm_medium=referral">Cytonn Photography</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the process of building a Predictive Machine learning model, we come across the Bias and Variance errors. The Bias-Variance Tradeoff is one of the most popular tradeoffs in Machine Learning. Here, we will go over what Bias error and Variance error are, sources of these errors and how you can work to reduce these errors in your model.</p><p><strong>How does Machine Learning differ from traditional programming?</strong></p><p>The high school definition of a program was simple. A <strong>program</strong> is a set of rules that tells the computer what to do and how to do it. This is one of the main difference between traditional programming and Machine Learning.</p><p>In traditional programming, the programmer defines the rules. The rules are usually well defined and a programmer often has to spend a good amount of time debugging code to ensure that the code runs <em>smoothly</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*5d_Fm1FKbKreaE7HuNA8HA.png" /></figure><p>In Machine Learning, while we still we still code, we do not define the rules. We build a model and feed it our expected results (supervised ML) or we allow the model come up with its own results (unsupervised ML). The main focus in Machine Learning is to improve the accuracy of the initial guess the model makes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*243N6Dajb1QlaFL7xdBlSw.png" /></figure><p>Due to the fact that there are no set rules and the model has to make guesses, Bias and Variance error creep in, depending on how simple or complex these guesses or assumptions are.</p><p>The types of errors in the prediction of a model are:</p><ul><li>Bias error</li><li>Variance error</li><li>Irreducible error</li></ul><p>The predictive error of a model can be calculated as seen below:</p><blockquote>Prediction error = Bias error + Variance error + Irreducible error</blockquote><p>We can work to improve our model by reducing the Bias and Variance error, but not the irreducible error.</p><h3>Bias — Variance Tradeoff</h3><p>The Bias-variance errors are indirectly proportionate. Increasing the Bias will decrease the Variance and vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*hb8F9jMk0UyYcS3jsyD8sg.png" /></figure><p>Can you guess which of the images has Bias error and which has Variance error?</p><p>If you guessed <strong>A</strong> has high Bias and <strong>B</strong> has high Variance, you’re right.</p><p>If our target value is Y and our features are denoted by x:</p><blockquote>Y= f(x) + e</blockquote><blockquote>where e is the error which is normally distributed.</blockquote><p>The error is the difference between the predicted value and the actual value. We square the errors so that negative errors do not cancel out positive errors i.e. the Sum of Squared Errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*EWyEsOeQ2s-UgheYGr8tkQ.png" /></figure><p>If we compare the errors for the <strong>training data</strong> for <strong>A &amp; B</strong> using sum of squared errors, <strong>A</strong> will have a higher error on the training data. <strong>B</strong> has zero error or very little as the line(model) fits too closes to the training data.</p><p>However, when we compare the errors for <strong>A</strong> &amp; <strong>B</strong>, this time on the <strong>testing data</strong>, the error of <strong>B</strong> increases drastically while the error of <strong>A</strong> remains fairly constant. Our ideal model is <strong>C</strong>. It represents the model just well enough without having too much variance or bias for both the training and testing data.</p><h3>Bias Error</h3><p>When a Machine Learning model is unable to capture the true relationship between the features and target of the data, we have an error called <strong>Bias</strong>.</p><p>The Machine Learning model makes assumption based on the available data. If the assumption is too simple, then the model may not be able to accurately account for the relationship between the features and target of the data thereby producing inaccurate predictions.</p><p>Mathematically, Bias can be defined as the difference between the Predicted values and the Expected values.</p><p>Linear models such as Linear Regression and Logistic Regression which make simple assumptions have high bias. While models such as Decision Trees and Support Vector Machines have low bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*1R4Btn9TRhksPuIwjZTZ0g.png" /><figcaption>Bias error in Model</figcaption></figure><p>When the model is too simplistic such that it does not consider even the important features of the training data, the model can be said to be <strong>underfitted</strong>.</p><p><strong>Underfitting</strong> occurs when the model cannot accurately fit the training data and therefore performs poorly on training data.</p><p>Underfitting occurs when the model has high bias but low variance, a result of an excessively simple model.</p><h4>Reducing Bias</h4><ol><li><strong>Change the model</strong>: One of the first stages to reducing Bias is to simply change the model. As stated above, some models have High bias while some do not. Do not use a Linear model if features and target of your data do not in fact have a Linear Relationship.</li><li><strong>Ensure the Data is truly Representative</strong>: Ensure that the training data is diverse and represents all possible groups or outcomes. In the event of an imbalanced dataset, use weighting or penalized models. There has been discussion on the poor accuracy of facial recognition models in identifying people of color. One possible source of such error is that the training dataset was not diverse and the model did not have enough training data to clearly identify persons of color.</li><li><strong>Parameter tuning</strong>: This requires an understanding of the model and model parameters. Algorithms documentations are a good place to start. Every model has a list of parameters which it takes as inputs. Tweaking these parameters may give you the desired results. You can also build your own algorithms from scratch.</li></ol><h3>Variance Error</h3><p>In a bid to avoid Bias error, be careful not to fall into another error called <strong>Variance</strong> error. The Bias error and Variance error are polar opposites.</p><p>While the Bias error is caused by simplified assumptions or the model being unable to account for effect of features on the target; Variance error is as a result of the model making too complex assumptions.</p><p>In other words, the model has fit too closely to the training data. While it may return a high accuracy on training data, it does not necessarily translate into a good predictive model. In fact, it may even result in higher errors.</p><p>The problem with the model fitting too closely to the training data is that it also captures noise or features which should in fact not be taken into consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*1AgXyjn2K1HBG9LQzqUUmg.png" /><figcaption>Variance Error in model</figcaption></figure><p>This can also result in a phenomenon known as <strong>Overfitting</strong>.</p><p>Overfitting occurs when a model has high variance and low bias. When a model fits too well with the training dataset such that it captures noise, it is said to have Overfit the training data. This will negatively impact the predictive power of the model.</p><p>The <strong>training data</strong> refers to the data which the model is built on. Remember, in machine learning we carry out a form of history matching. The model is trained on past data — labeled or unlabeled — and when our model is ready, we introduce new data to it.</p><p>For validation, we split the available data into training and testing set. The testing data is used to validate the performance of the model.</p><p>If our model returns a high accuracy on training data but performs poorly on testing data, we can denote that the model has fit too closely to the training data and can therefore not generalize on new data.</p><h4>Reducing Variance Error</h4><ol><li><strong>Ensemble Learning</strong>: A good way to tackle high variance is to train your data using multiple models. Ensemble learning is able to leverage on both weak and strong learners in order to improve model prediction. In fact, most winning solutions in Machine Learning competitions make use of Ensemble Learning.</li><li><strong>Train Model with More Data</strong>: This sounds tricky. Why add more data when the variance is high? More data increases the data to noise ratio which reduces the variance of the model. Also, when the model has more data, it is better able to come up with a general rule which will also apply to new data.</li></ol><h4>Conclusion</h4><p>Now we have come to an end. We have defined Bias and Variance errors, their sources and steps you can take to reduce these errors in your model.</p><p>Remember, in simple terms:</p><ul><li>Bias is as a result of over simplified model assumptions</li><li>Variance occurs when the assumptions are too complex</li></ul><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f24253c0ab45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-bias-variance-tradeoff-f24253c0ab45">The Bias-Variance Tradeoff</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Functions in Data Analysis]]></title>
            <link>https://medium.com/swlh/using-functions-in-data-analysis-990643f11495?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/990643f11495</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 02:14:55 GMT</pubDate>
            <atom:updated>2020-10-05T02:14:55.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Implementing functions in your data analysis process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIcjmz28Epv2oDGc" /><figcaption>Photo by <a href="https://unsplash.com/@john_visualz?utm_source=medium&amp;utm_medium=referral">John T</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Functions are not a new idea in programming. In fact, most programming languages have built-in functions that allow programmers carry out different tasks.</p><p>Functions are sequence of codes written together in blocks in order to perform an action or a series of actions.</p><p>Some in-built functions in Python include:</p><ul><li><strong>min()</strong></li><li><strong>max()</strong></li><li><strong>cos(x)</strong></li><li><strong>sin(x)</strong></li><li><strong>tan(x)</strong></li><li><strong>str()</strong></li><li><strong>float()</strong></li></ul><p>and many <a href="https://docs.python.org/3/library/functions.html#sum">more</a>.</p><p>We can also define our own functions. To define a function, we use the keyword <strong>def </strong>followed by a function name and parenthesis. Once a function is defined, it can be <strong>called</strong> several times throughout the program.</p><p>Function naming rules are similar to those of variables. The function name cannot begin with a number. However letters, numbers and punctuation marks can be used when naming a function. Avoid assigning the same name to two different functions and also do not have a variable with the same name as your function in the same program. Keywords should not be used as function names.</p><pre>def <strong>some_func2</strong>(): </pre><p>The empty parentheses indicates that the function above does not take any arguments. To define a function which takes arguments, we simply place parameters between the parenthesis.</p><pre>def <strong>some_func3</strong>(a, b):</pre><p>A function is made up of a header, which is the first line and a body which is indented and can contain any number of codes.</p><pre>def <strong>some_func-4</strong>(a,b):<br>    print(a,b)</pre><h3>Why Use Functions</h3><ul><li>Functions increases data science workflow efficiency by eliminating repetition and redundant lines of codes.</li><li>Making corrections to code is easier as you only have to debug the function and corrections are applied wherever the function is called.</li><li>Using functions makes the program smaller and compact.</li><li>Most importantly, functions are reusable and can be ‘called’ multiple times across the program.</li></ul><h4>Execution of Functions</h4><p>Python codes are executed line by line. When we define a function, python saves the function and is able to recall it whenever it comes across the function. In this way, we can use one function multiple times during our work flow without having to bother rewriting the code.</p><p>To call a function we simply write the function name followed by parentheses and any arguments if necessary.</p><p>Functions can be as simple as printing ‘Hello World’ or so complex that they make use of nested loops and other functions.</p><h3>Creating a Function</h3><p>To create a function in python, the <strong>def</strong> keyword is used followed by the function name and parenthesis.</p><pre>def new_func():<br>    print(&#39;Hello World&#39;)</pre><pre>new_func()<br>&gt;&gt; Hello World</pre><p>This simple function prints ‘Hello World’ whenever it is called.</p><h4>Function Arguments</h4><p>Functions can be defined such that they take arguments. Parameters serve as place holders and indicate that the function should be called with values within the parentheses.</p><pre>def func(name):<br>    print(&#39;Hello&#39;,name)</pre><pre>func(&#39;James&#39;)<br>&gt;&gt; Hello James<br>func(9)<br>&gt;&gt; Hello 9</pre><p>The function above will print ‘Hello’ + whatever argument is placed within the function when it is called.</p><p>The number of arguments put into the function matters.</p><pre>def add(a,b):<br>    total = a + b<br>    print(total)</pre><pre>add(1,3)<br>&gt;&gt; 4</pre><p>A Type Error is returned if a function receives fewer arguments than expected as specified during the function definition.</p><pre>add(2)<br>&gt;&gt; <strong>TypeError</strong>: summ() missing 1 required positional argument: &#39;b&#39;</pre><p>In the example above, an error occurs because the function expects two values but receives only one.</p><pre>add(1,3,4)<br>&gt;&gt; <strong>TypeError</strong>: summ() takes from 1 to 2 positional arguments but 3 were given</pre><p>Likewise an error will be returned if you pass in more arguments that required by the function.</p><p>If you are uncertain of the number of parameters that will be passed into the function, arbitrary arguments can be passed into the function. To make an arbitrary argument, simply pass an asterisk before the parameter name.</p><h3>Adding Functions to your Data Science workflow</h3><p>The aim of using functions is to make our work a little easier. Therefore, not everything needs a function. You should look out for task you have to carry out more than once or twice in your analysis process. Rather than having to copy and paste or rewrite the same block of code, you can easily make it into a function. Some of these tasks include:</p><h4>Filling Null Values</h4><p>No one wants to spend so much time going through each column to fill in missing values. What if you have a thousand columns (exaggeration, I know), you will find that this task is repetitive and can become quite cumbersome when you have a large dataset. These are the type of tasks you want to automate, creating a function helps you do just that.</p><pre>def fillvalues(data):<br>    for col in data.columns:<br>        data[col].fillna(-999, inplace=True)</pre><pre>fillvalues(df)</pre><p>The simple function above will iterate through all the columns in a data set and replace any missing numerical value with the number -999 or any specified number. This function reduces the need to run several lines of code filling every missing value in a column.</p><p>The function can be modified for dataset with categorical data by introducing an <strong>if/else</strong> statement and specifying the value to be filled.</p><blockquote>This function works efficiently with numerical columns because often times, the null values across different columns can be filled with the same value, an outlier such as -9999. For categorical columns, it is common practice to fill missing values with the most frequent value or the modal value. The code will look similar to the example below.</blockquote><pre>def fillvalues(data):<br>    for col in data.columns:<br>        if data[col].dtypes == float:<br>            data[col].fillna(-99999, inplace=True)<br>        else:<br>            mode_val = data[col].mode()[0]<br>            data[col].fillna(mode_val, inplace=True)</pre><pre>fillvalues(df)</pre><p>Here I have extracted the modal value of each column and saved it in the variable <strong>mode_val</strong>. This value will be obtained for each column and will replace missing values. You can fill missing categorical values with a constant value in which situation, you only have to specify the value. You can also replace missing numerical values with the median or mode value of the column. Have fun with it, you can take this sample code and try different datasets or scenarios.</p><p>This is a code I have used severally during my data analysis process. It makes it easier for me to loop through the columns and fill in the values <em>automatically</em>.</p><p>One precaution I always take is to view the data types of each column in the dataset. This can easily be done using the pandas dataframe <strong>info() </strong>function. The function returns the number of entries in a dataset (rows), the Columns in the dataset, Non-Null Count and Data type of each row.</p><p>With this information, I am able to modify my function to suit the dataset.</p><h4>Reading Text files</h4><pre>def filereader(file):<br>    f = open(file)<br>    count = 0<br>    for line in f:<br>        count +=1<br>        print(line)<br>    return count<br>        <br>filereader()</pre><p>The function above will open the specified text file, iterate through its content and print them out after which it returns the number of lines in the text file.</p><h4><strong>Helper Function</strong></h4><p>This is a code excerpt from Aifenaike’s Data Science Nigeria Bootcamp Qualification Hackathon on Loan default.</p><blockquote>Here, the cross validation loop and other processes are built for training and stacking that will be done throughout our workflow…</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee8a7dbb857d0f51ef15016b3eb013b3/href">https://medium.com/media/ee8a7dbb857d0f51ef15016b3eb013b3/href</a></iframe><p>This is a more complex function which is used to train stacked models. The full code can be viewed on his <a href="https://github.com/aifenaike/DSN_KOWOPE">GitHub</a> page.</p><h4>Final Thoughts</h4><p>Coding re-usable functions is one of our ‘<strong>9 Habits of Effective Data Scientists</strong>’. Another effective habit is the use of comments and documentation. Comments are important in functions. The more complex our function is, the more comments are needed to serve as a guide. Remember, comments are for your benefit as well as anyone who would seek to read or contribute to your work.</p><p><a href="https://medium.com/swlh/9-habits-of-effective-data-scientists-fdc7653fbb86">9 Habits of Effective Data Scientists</a></p><p>You can use single inline comments or multiple line comments. To write comments across multiple lines simply use three single or double quotation marks. The comments should have such information as what the purpose of the function (<em>function of the function, LOL</em>), function parameters and expected arguments.</p><pre>def total(a,b):<br>    &quot;&quot;&quot;<br>    This function calculates the sum of two arguments <br>    a is an int or float<br>    b is an int or float<br>    &quot;&quot;&quot;<br>    # Just adding an in-line comment for fun<br>    return a + b</pre><p>Writing a function is not the easiest thing to do and can take some debugging to get it right. Bear in mind that one good function can be used multiple times while you only have to debug one set of code.</p><p>If you have not been making use of functions, now is a good time to start. <strong>If you have been making use of functions, what tasks do you use them for and how has this improved your data science workflow?</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=990643f11495" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/using-functions-in-data-analysis-990643f11495">Using Functions in Data Analysis</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Toolkit]]></title>
            <link>https://dsnph.medium.com/data-science-toolkit-b691a99a8080?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/b691a99a8080</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sun, 20 Sep 2020 21:08:01 GMT</pubDate>
            <atom:updated>2022-04-25T07:23:16.866Z</atom:updated>
            <content:encoded><![CDATA[<p>Tools and skills you need in Data Science</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VmVeS-SBlgAsIAFd" /><figcaption>Photo by <a href="https://unsplash.com/@madebyvadim?utm_source=medium&amp;utm_medium=referral">Vadim Sherbakov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There has been a debate on whether Data Science is the ‘sexiest job of the 21st century’ or not. We will not be taking part of that debate — today. Rather, for those looking to get a start in data science and in extension, Machine Learning, or if you are just looking to get ahead in the field, we have curated tools you need as a data scientist.</p><p>These tools will be broken down into different categories for convenience — more mine than yours. We will also look at the basic skills a data scientist show possess and how to build an amazing Data Science portfolio.</p><p>That sounds like a lot, so let’s get started.</p><h3>DATABASES</h3><p>A database is a collection of data. Types of <a href="https://www.geeksforgeeks.org/types-of-databases/">Databases</a> include:</p><ul><li>Hierarchical database</li><li>Network database</li><li>Object oriented databases</li><li>Relational databases and</li><li>NoSQL databases.</li></ul><p>The most common database in use, and our focus is the Relational Database.</p><p>Structured Query Language (SQL) is the standard language for communicating with a database and the language used by Database Management Systems.</p><p>A Database Management System (DBMS) is used to interact with the database through <strong>queries</strong>. The DBMS can be used to create databases, access database, organize the database, modify the database and extract information from the database. Popular DBMS include MySQL, PostgreSQL, Microsoft SQL Server, Oracle etc.</p><p>SQL is fairly easy to learn once you understand its syntax and query format. It is also important to note that the syntax may differ across the various DBMS. The difference is usually very small though and transitioning across the various DBMS should not pose any serious problems.</p><h3>LANGUAGES</h3><p>I have seen articles and videos comparing R and Python, discussing which is better to use for data analysis or which a data scientist should start with. I understand that these questions come from a place of worry and the need to get things right. I would however like to state that I see these languages as tools — a means to an end. There are people who will swear and die by R and likewise for Python.</p><p>Whichever you choose, both R and Python have a large community which you can rely on for help. For me, that’s a huge factor — Getting help.</p><p>R programming language is very good for statistics and computational analysis, especially when you are working with large large datasets. It also has different data types such as scalars, vectors, matrices, data frames, arrays and lists. R has numerous packages for working with data from pre-processing to data analysis and machine learning.</p><p>Integrated Development Environments (IDEs) for running and editing R codes include:</p><ul><li>RStudio</li><li>Rattle</li><li>StatET for R</li><li>ESS etc</li></ul><p>Python on the other hand is a general purpose language. When I started learning python, it was not because of data science even though I cannot remember what it was for then (back then I just wanted to learn programming because it was the <strong>it</strong> thing and I heard python was easy to learn. I hope some of you can relate) and yes, it is easy to learn the basics of Python. Python also has libraries which are very useful when working with data and has gained much ground in machine learning and AI.</p><p>Python IDEs include:</p><ul><li>Jupyter Notebook</li><li>Spyder</li><li>Pycharm</li></ul><p>But do not be fooled by the back and forth between R and Python, there are other programming languages which can be used for data analysis. I’ve discussed this in a previous post and what factors you should consider when deciding with language you want to work with.</p><p><a href="https://medium.com/@dsn_ph/the-language-of-machines-f836d855f5e5">The Language of Machines</a></p><h3>BIG DATA TOOLS</h3><p>Due to the nature of ‘Big Data’, conventional databases are not enough, hence Big Data tools. The field of Big Data deals with large amounts of data that are difficult to process using traditional data analysis tools or techniques.</p><p>Big Data can be structured or unstructured and have different data types.</p><p>Big Data tools include:</p><ul><li>Hadoop</li><li>Data Lakes</li><li>Spark</li><li>Cassandra</li><li>MondoDB</li></ul><h3>CLOUD</h3><p>Cloud computing has gained ground over the years with the most popular ones being <strong>AWS, Google Cloud and Microsoft Azure</strong>. These cloud services provide on-demand computer resources such as data storage, servers, databases, networking and computing power reducing/totally removing the need for user management. The services are all run by the company and the user can access them at a price.</p><p>The three main types of cloud computing are</p><ul><li>Infrastructure as a Service</li><li>Platform as a service</li><li>Software as a service</li></ul><p>The advantage of using these cloud services is that users can work with large amounts of data without having to worry about the computational power of their devices and they also do not need to maintain their own servers.</p><p>Cloud computing services also offer little or no-code environments for deploying machine learning models.</p><p>These Cloud services promise:</p><ul><li>Scalability and flexibility</li><li>Data protection</li><li>Data accessibility at anytime from anywhere</li><li>Cost efficiency (check prices for cloud service of choice)</li><li>Networking capabilities</li></ul><h4>HOW TO ‘LEARN’ DATA SCIENCE</h4><p>How long does it take to become a data scientist?</p><p>It is not easy to say because individuals have different learning abilities. I will however give a timeline.</p><p>If you do choose to go down the Python path, this can take you any time between a week and a month. Python is quite easy be quite to learn especially because you are not expected to learn all <em>parts</em> of Python. The areas you should focus on are:</p><ul><li>Python Data Structures (integers, float, strings, list, dictionaries)</li><li>Using functions in Python</li><li>Accessing web data with Python</li><li>Python libraries such as Numpy, Pandas, Scipy that can be used to manipulate data</li></ul><p>If you dedicate 3–4 hours a week, you should be able to learn all these. I will not recommend any particular course because there are so many good ones available — paid and free.</p><p>Next you should learn SQL, SQL is quite easy. Like I said above once you get the syntax of SQL, you can spend between 2–3 weeks learning SQL. Even less. Remember, the syntax may vary for different DBMS but the structure remains the same.</p><p>Even more than learning all these, I would advise you to take a refresher course or two on statistics and Linear Algebra.</p><p>I find that a lot of times, people focus more on playing with the ‘big tools’ and don’t bother learning the basics. While there are libraries which can handle these aspects for us, it is still good to understand the basics.</p><p>This would work quite the same with R although R can prove daunting to beginners but once you get the hang of it. I believe it will be much easier.</p><p>Most importantly, I would advise you start working on projects as soon as possible. Working on projects will allow you put what you learn into practice. They say the best way to learn is by doing, right?</p><h3>Data Science Portfolio</h3><p>A Data Science Portfolio offers a quick way to show your skill set and expertise before, during and after an interview.</p><p>No, I do not expect you to have one of those clear folder bags filled with data science projects. The <strong>easiest</strong> way to build a portfolio as a data scientist is to have a blog or a GitHub account. They both offer different benefits but with a GitHub account, you do not have to bother yourself with maintaining a blog.</p><p>When uploading projects you should make sure to include a summary of the project or <strong>documentation</strong>. In GitHub, you upload a README explaining the use of your project, how it can be set up (if need be) and any extra work than can be done. Another easy way is to contribute to repositories. You can also set up your GitHub account so that so that it better reflects your work.</p><p>However you choose to showcase your work, here are some basic skills you should highlight in your work:</p><h4>Data cleaning ability</h4><p>Data in the real world is often messy and unstructured. You should highlight the fact that you are able to work with a wide variety of data. Here you can also show how you get your data be it web scrapping, reading the file from the web (using urllib and the like) or using data in your system.</p><p>Also you should show how you deal with missing data as missing data is often something we cannot avoid in datasets. Do you replace them or flat out remove them.</p><p><a href="https://medium.com/@dsn_ph/data-quality-issues-dealing-with-missing-data-84f404006458">Data Quality Issues: Dealing with Missing Data</a></p><h4>Ability to extract insight from data</h4><p>There is no particular way to do this. It is going to be a combination of different methods, Exploratory Data Analysis and good old intuition to make sense of the data.</p><p>Don’t try and do anything too complex to look like an ‘expert’. Remember to use comments in your code and <strong>when possible</strong>, use functions. Your codes should be simple and efficient.</p><p>You can carry out feature selection and engineering and the fit a model to the data.</p><h4>Data presentation/ Visualization</h4><p>Don’t forget to visualize your data using the appropriate charts. There are self visualization tools that do not require any coding such as Power BI or Tableau.</p><p>There are also visualization libraries in Python and R that you can use to visualize your data. For more tips on how to visualize your datasets, you can check our previous post: Simple Guide to Data Visualization.</p><p><a href="https://medium.com/swlh/simple-guide-to-data-visualization-6ef6fa726e38">Simple Guide to Data Visualization</a></p><h4>Predictive Analysis</h4><p>Much of the work done with data, is to draw insight from data. The insight drawn from data is then used to predict future events. To do this, we often have to build models with available data. These models can then be used to predict the future, all things beings equal. This aspect is usually known as Machine Learning. Machine Learning is a broad area and is divided into two major areas: Supervised and Unsupervised.</p><p><a href="https://medium.com/@dsn_ph/to-classify-or-to-regress-1dfd42ca607c">To Classify or To Regress</a></p><h4>Machine Learning Libraries</h4><ul><li>Sklearn</li><li>Tensorflow</li><li>Keras</li><li>Pytorch</li></ul><h3>Conclusion</h3><p>An end-to-end data science project will often begin from a business problem, obtaining data, exploring data and then building and deploying machine learning models with which to carry out predictive analysis.</p><p>We end on a good note. Know that there are many resources for learning data science and machine learning. Some of my best Python lessons were taken on YouTube.</p><p>If you do decide to join ‘the sexiest job of the 21st century’, you should do it right.</p><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b691a99a8080" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Guide to Data Visualization]]></title>
            <link>https://medium.com/swlh/simple-guide-to-data-visualization-6ef6fa726e38?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ef6fa726e38</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[exploratory-data-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-visualization-tools]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 17:34:02 GMT</pubDate>
            <atom:updated>2022-04-25T07:22:22.411Z</atom:updated>
            <content:encoded><![CDATA[<p>How do you get information across through visualization?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i3Laz-PpQvpJ3EYn" /><figcaption>Photo by <a href="https://unsplash.com/@mihaly_koles?utm_source=medium&amp;utm_medium=referral">Mihály Köles</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data visualization is the graphic representation of data and information. Data visualization makes use of charts, graphs, software or other visualization tools to provide a quick overview of data and show trends and relationships that exist.</p><p>Data visualization is not just about plotting charts or making colorful images, in data visualization, the goal is to pass information to the end users as well as:</p><ul><li>Visualize trend in dataset</li><li>Easily recognize outliers</li><li>Recognize data patterns</li><li>Understand relationship between data</li></ul><h4>Data Visualization for Data Scientists</h4><p>Data science has found application in various industries leading to the employment of data scientists, analysts and engineers across industries in varying capacities. This is why it is good to have an understanding of chart types for visualizations.</p><p>In finance, line charts are very useful as they show trends in prices and can also be used to forecast future trends. Gantt charts are used to keep track of project and event start and end times and have found useful application in project management.</p><p>In data science, Exploratory Data Analysis is an important process that often employs visual methods to summarize data in order to gain insight from data (the whole data science process is aimed at gaining insight from data).</p><p>Data visualization can be carried out via visualization tools as they are commonly called. These tools include websites and services that offer visualization, visualization software and visualization libraries in programming.</p><p>Data visualization tools include:</p><ol><li>Power BI</li><li>Tableau</li><li>Adaptive Insights</li><li>Plotly</li><li>Google Charts</li></ol><p>The above visualization tools do not require any coding experience.</p><h4>Exploratory Data Analysis</h4><p>Exploratory Data Analysis (EDA) is the process of summarizing the important aspects of data often using visualization. EDA is an important part of the Data Science process. EDA seeks to check assumptions and test hypothesis as well as discover patterns/trends in the data.</p><p>Popular programming languages for data visualization include:</p><ol><li>Python</li><li>R</li><li>MATLAB</li></ol><p>While popular, visualization libraries include:</p><ul><li>Matplotlib</li><li>Seaborn</li><li>Bokeh</li><li>ggplot</li></ul><p>I recall having to make a presentation during my internship, nothing difficult, my tools were simply Excel and PowerPoint. Before then I was familiar with both Excel and PowerPoint and I did not feel a presentation would be difficult. However, when I submitted my ‘finished work’ to my supervisor he made so many corrections I felt beat. My <em>good work</em> was not so good after all. Let me tell you some of the mistakes I made:</p><h4>I did not label my charts properly</h4><p>Rookie move, I know. Me of today, cannot believe I did that and I will simply rule it as an omission.</p><h4>Chart proportion did not match the presentation.</h4><p>Let me explain, you see, this was a presentation, I was going to use a projector and my charts were too <strong>big</strong>. I did not know that was even possible.</p><p>I had to learn how to proportion my charts with the rest of my presentation so that they look <strong>good</strong>.</p><p>Looks do matter when it comes to visualization because the eyes perceive the data before our mind even starts to process it. Now if you are carrying out Exploratory Data Analysis in a notebook environment that will never be published on any platform, you might not give this much thought. Also, notebooks are easier to navigate and often times, with little effort, your visualizations will look good.</p><h4>I used wrong plots to represent data.</h4><p>My data type was nominal— categorical — a plot of the quantity of some items (can’t remember what exactly), and I had used a line plot.</p><p>In my defense, I thought it looked really good and the colors, splendid. When my supervisor looked at it, he asked me what I was plotting, <strong>first strike</strong>. The whole point of visualizing data is to give a quick, easy to understand overview of the data. <em>Recall I did not even label my charts so I can only imagine my supervisor trying to make sense of it all.</em></p><p>If your visualization confuses the <em>audience</em>, you should probably — <strong>definitely </strong>— rethink your charts and plots.</p><p>Back to the story, when I told him what I wanted to plot, he simply turned it into a bar chart. He explained that to visualize quantity of items, bar charts are better for the job. Line charts should be used if you want to show relationship. You’ll see what I mean soon enough.</p><blockquote><strong>Some Important Lessons I learned:</strong></blockquote><blockquote>Bigger is not better</blockquote><blockquote>Your plot should be easy to understand</blockquote><blockquote>Label plots properly</blockquote><blockquote>Understand chart relationships</blockquote><blockquote>Take your data type into consideration when choosing charts</blockquote><p>The presentation medium also matters. Graphic designers are familiar with the RGB and CMYK color schemes. The RGB is the color we get from our screen, while CMYK is print color. Graphic designers often have to convert their work from RGB to CMYK so that they get a good look of how their work will look when in print.</p><p>With advancements in technology, this process may not be necessary and because most presentations are made on screens, you may not never have to worry about this, especially as a Data scientist.</p><h3><strong>Common Charts</strong></h3><p>Charts give quick summary of data and can be used to show the relationship between variables or features. Charts have two axes, the x-axis and the y-axis. The x-axis (horizontal) represents the independent variable while the y-axis (vertical) represents the dependent variable.</p><p>Below are some common charts, their application and information that can be derived from such charts. We will be using Python and <a href="https://matplotlib.org/users/index.html">Matplotlib</a> through out for consistency. However, I advise you to explore other visualization tools and libraries.</p><p>I also make use of the Titanic dataset. I refer to this data set frequently because it is very popular especially amongst beginners and can be accessed via <a href="https://www.kaggle.com/c/titanic">Kaggle</a>.</p><h4>Bar Chart</h4><p>The bar chart is used to represent categorical data. On one axis, we plot the nominal / discreet variables, while on the other axis, we have the dependent quantitative variables. The quantitative values may be discreet or continuous. The heights of the bar charts are proportional to their values. Bar charts may be <a href="https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barh.html">horizontal</a> or vertical (column charts), placed side-by-side or <a href="https://matplotlib.org/3.3.1/gallery/lines_bars_and_markers/bar_stacked.html">stacked</a>.</p><p>The following information can be obtained from bar charts:</p><ul><li>Highest and lowest values in a dataset</li><li>A type of bar chart, the Histogram, can also be used to display the distribution of data (normal, binomial etc)</li><li>The count or measure of each category</li><li>Compare categorical variables</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e406d30667bd3eb39c069ea1459e3ec/href">https://medium.com/media/0e406d30667bd3eb39c069ea1459e3ec/href</a></iframe><h4>LINE CHART</h4><p>The line chart is used to visualize the relationship between quantitative — independent and dependent — variables. With the line chart, it is easy to spot changes in data over time. The data points are represented by markers connected by lines or curves. The direction of the plot also denotes the type of relationship between the variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*HC_6TAGJYzDY39vb3nPcWQ.png" /></figure><p>The Line Chart can be used to:</p><ul><li>Display history trend of data</li><li>Forecast future trend</li><li>Track changes that occur over a period</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17644c9bc6d8dee408dcab30a99b8be8/href">https://medium.com/media/17644c9bc6d8dee408dcab30a99b8be8/href</a></iframe><p>Line Plot with a lot of data can be quite messy so take note of that. However, line plots are very useful tools for time-series data which is why it is useful in viewing stock prices and forex.</p><h4>SCATTER PLOT</h4><p>The scatter plot is similar to the line plot, without the lines. The scatter plot is a plot of two independent quantitative variables. The advantage of the scatter plot is that clusters can easily be identified.</p><p>Other information that can be obtained from scatter plots include:</p><ul><li>Relationship between the numerical variables</li></ul><p>Variables may be positively correlated, negatively correlated or not correlated at all. Variables can also be strongly or weakly correlated depending on how close the data points lie to the line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkoEKv4-Z_aPKyQ69pY8Kw.png" /></figure><ul><li>Delineates clusters</li><li>Easily spot outliers</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1f163fa4435d07673ceb15f274fa91c/href">https://medium.com/media/c1f163fa4435d07673ceb15f274fa91c/href</a></iframe><h4>GANTT CHART</h4><p>The <a href="https://www.geeksforgeeks.org/python-basic-gantt-chart-using-matplotlib/">Gantt</a> chart is a type of bar chart — Horizontal bar chart. Nominal data is plotted on the y-axis and quantitative data on its x-axis. The position and length of the Gantt chart are important features as Gantt charts are often used to show stages of projects and relationships between activities. It is therefore an important tool for project management.</p><p>From Gantt chart we are able to identify:</p><ul><li>Start and stop time of activity</li><li>Overlapping activities</li><li>Order of activities</li></ul><h4>PIE CHARTS</h4><p>Pie charts are circular charts used to illustrate numerical proportions of categorical variables. The <a href="https://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/pie_features.html">pie chart</a> proportions can be represented in degrees totaling up to 360 degrees or in percentage up to 100% or decimals up to 1. Each slice of the pie represents a part of a whole.</p><p>Pie charts are useful for:</p><ul><li>Comparison</li><li>Showing compositions of a whole</li><li>Proportions of classes</li><li>Quick summary of data</li></ul><h4>HISTOGRAMS</h4><p>Histograms are bar charts where the values are grouped into ranges called bins. A tall bar indicates that many values fall within that range while a short bar indicates the opposite. Histograms are especially useful for displaying distribution of the data — normal, binomial, Poisson etc.</p><p>Histograms are used to:</p><ul><li>Identify highest and lowest ranges</li><li>Used for statistical analysis (mean, median, mode etc.)</li><li>Denotes distribution of dataset</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/973c3326aeb1806de81f984c8c3b83cd/href">https://medium.com/media/973c3326aeb1806de81f984c8c3b83cd/href</a></iframe><h4>Conclusion</h4><p>Understanding the characteristics of charts and their application will help you make better visualizations. Knowing what to plot and how to make your plots, will enable you gain valuable insight from data.</p><p>While I focused on Matplotlib, there are other visualization libraries that can help you make simple plots.</p><p>Remember, your visualization should be clean, clutter-free and suitable for the data type you are visualizing. Don’t forget to label those charts!</p><h4>Reference</h4><ul><li><a href="https://www.coursera.org/learn/python-plotting/home/welcome">Coursera | Online Courses &amp; Credentials From Top Educators. Join for Free | Coursera</a></li><li><a href="https://www.coursera.org/learn/datavisualization/home/welcome">Coursera | Online Courses &amp; Credentials From Top Educators. Join for Free | Coursera</a></li></ul><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ef6fa726e38" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/simple-guide-to-data-visualization-6ef6fa726e38">Simple Guide to Data Visualization</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[9 Habits of Effective Data Scientists]]></title>
            <link>https://medium.com/swlh/9-habits-of-effective-data-scientists-fdc7653fbb86?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdc7653fbb86</guid>
            <category><![CDATA[habits]]></category>
            <category><![CDATA[effectiveness]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sun, 06 Sep 2020 11:50:41 GMT</pubDate>
            <atom:updated>2022-04-25T07:18:24.326Z</atom:updated>
            <content:encoded><![CDATA[<p>Working in the fast paced world of data science? Here are some habits that are bound to increase your productivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4TyoNJZu2zq8USfA" /><figcaption>Photo by <a href="https://unsplash.com/@heyerlein?utm_source=medium&amp;utm_medium=referral">h heyerlein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Data science is quite the trend right now. The pay is high and great opportunities abound. Its applications are numerous and many industries, tech or not, are beginning to see the importance of making sense of their data.</p><p>While it is a hot topic right now, here are 8 habits that will make you a better data scientist.</p><h4>Know the Job Roles</h4><p>Before you apply for any job, make sure you know what you are getting yourself into. There are many job roles/titles that exist and you need to be familiar with them and know just what you will be doing. It is also good to note that even with clearly defined roles, you can find yourself doing much more depending on the company you work for. So be ready.</p><p>Some of the job roles that exist include:</p><ul><li>Data scientist</li><li>Data analyst</li><li>Business analyst</li><li>Machine learning engineer</li><li>Database administrator</li></ul><p>… To name a few. While they all require the same basic skill set (Python, R, SQL) and knowledge with working with data, their requirements can differ. So before you apply for that job, check the job description and see if they align with your <strong>skill</strong> and ability.</p><p>Stress on skill because you’re going to need a lot of it.</p><h4>Time Conscious</h4><p>You need to be time conscious for various reasons. If you are working on a project and you can’t seem to get it right, you should know when to drop it. You can’t do the same thing and expect different results.</p><p>In my experience, when a project seems overwhelming I do one of the following:</p><ul><li><strong>Rest</strong>: Sometimes its just fatigue and you need to rest your head and come at the work with renewed vigor. You can use this time to engage in any activity really that makes you happy and relieves stress.</li><li>Search for similar problems and see how they were solved. A good place for this is Kaggle. You can go through notebooks on kaggle on different topics. You can also take a short course or go through examples in a data science textbook.</li><li><strong>Abandon ship</strong>: Yes, when work is pulling you under, you need to know when to let it go. It’s not easy especially when you feel like one more try will get you there. But, if you work in an office environment, they expect results and telling your boss you’ve been working on one project for a month with <strong>no solution in view</strong> can come off the wrong way. You don’t want that, trust me.</li></ul><h4>Ask for Help</h4><p>One thing I love about data science is the community. Its honestly amazing — online and offline. When I’m stuck on a problem, I’m very quick to call a friend or search online for solutions. The words <em>no one is an island</em> of knowledge really rings through here.</p><p>Platforms such as <a href="https://stackoverflow.com/questions">Stack Overflow</a>, <a href="http://www.kaggle.com/">Kaggle</a> and the rest are extremely useful. Another good source of help is <strong>Discussion Forums</strong>. I admit, I never saw the use of discussion forums at first and I always felt it was a distraction especially when taking a course. But I was wrong. The right discussion forum is one with people of <strong>like interest and goals</strong> such as discussion forums for competitions or courses or it could be you and your friends coming together to help each other out. It is also a good way to network, so keep that in mind.</p><p>Part of the mistakes I made when I started off was thinking I could do it all. I had no mentor or guidance and I just went off binge watching one tutorial after another. I got the skills alright but I also had many abandoned projects that I could not finish because I didn’t have any help when I was lost.</p><p>Even if you are a shy person, you can enjoy the anonymity of asking questions online or simply searching the web.</p><h4>Coding Re-usable functions</h4><p>Some of the process when dealing with data can be repetitive. Spare yourself the stress of having to write the same code over and over again.</p><p>An example of a process which you can <em>automate</em> through functions is filling missing data. You can write a function to loop through the columns and fill in the missing values. You should try that now if you haven’t.</p><p>If you started as a programmer before diving into data science, you will be familiar with the joy of functions. I’ve gone through a couple of data science courses and I haven’t heard them mention functions or how useful functions are even when I see them using functions.</p><p>Functions can save you a lot of time and increase your productivity.</p><h4>Comments and Documentation</h4><p>A simple ‘This code does this’ or ‘This function does that’ is enough. When I started learning how to program, I did not see the need for comments. I always felt well, I wrote the code, how can I not know what it does.</p><p>However, if you do happen to drop a project for sometime and return to it, things can get muddled up. For one, you may not remember the thought process that led you to do a particular activity. Maybe you multiplied a particular feature by a constant for some reason and now you’re looking at your work wondering why.</p><p>Comments and documentation are especially useful when working in teams. You don’t want your teammates getting lost neither do you want to keep answering the same question numerous times.</p><p>You also want to document any failed processes so you or your teammates don’t repeat the same mistakes.</p><p>Commenting and documenting increase productivity and is a good habit to develop. You can start by writing one line comment describing each part of your personal work and before you know it, you become an <em>expert documenter</em>.</p><h4>Self Development</h4><p>Being a data scientist is so savvy these days that people often dive head first into it and don’t come up for air. As a data scientist, you need a blend of soft and hard skills. Yes, you can deploy models and what not but so can a lot of people. You need something to set you aside from the pack. Soft skills.</p><p>Data scientist find themselves in different industries performing various tasks, under different titles such as Data engineer, ML engineer, software engineer, business analyst and so on. You need to have enough <strong>domain knowledge</strong> of the field you are working it. This will guide the techniques you employ and help you look at a problem <strong>critically</strong>. Having domain knowledge will also prevent you from going down rabbit holes. You have a clearer purpose and you can better allocate your resources to relevant problems</p><p>You also need to be a good communicator. After you have analyzed data and come up with your solution or next steps, your next job is to <strong>communicate</strong> your findings. The best way you can do this is through <strong>visualizations and storytelling</strong>. Your intricate models will not matter if you cannot effectively communicate your results and sell your idea to your company.</p><p>However if your company doesn’t take your recommendation, don’t feel bad. It might not be the right time just yet but your efforts would be appreciated.</p><p>So as you acquire technical skills, make effort to develop those immeasurable skills that will make you a true asset.</p><h4>Don’t be a perfectionist</h4><p>Yes, you read that right. The best way to become an expert data scientist is by doing projects. You’ve taken python courses, R, data science and machine learning but you’re still looking for another course to try because you don’t feel you’re quite there yet.</p><p>It could happen to anybody. I took a couple of python courses but still referred to myself as a beginner because although I took all those courses, I did not feel confident in my ability. I had not tried them on my own. What I essentially did was follow courses from beginning to end and then nothing. No personal projects, No practice.</p><p>If you do find yourself doing the same thing, here I am telling you to stop. Get some data and practice the basics you know. See what results you can get and then work to get better results.</p><p>The best way to learn data science is to do data science. The icing on the cake is that you get to build your portfolio at the same time. How awesome is that?!</p><h3>Review your work</h3><p>Make sure all parts of your project work. Remove any repetitive (use functions) or irrelevant sections.</p><p>Make sure you made the right assumptions, run unit tests on your model. <strong>Train, validate and test</strong>.</p><p>Tie the bow up nicely in your projects, no matter how small they are.</p><p>If you form this habit when working with small projects, you will easily do the same in major projects.</p><h4>CONCLUSION</h4><p>The path to becoming a data scientist is a fast one. It can take you some months, few weeks or even days. With the amazing tutorials and resources available online, you can learn anything you want to learn. You just need a little determination. These habits will spur you onwards and help you become your very best.</p><p><strong>What other habits do you feel make for an effective data scientist?</strong></p><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdc7653fbb86" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/9-habits-of-effective-data-scientists-fdc7653fbb86">9 Habits of Effective Data Scientists</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Churn Case Study]]></title>
            <link>https://dsnph.medium.com/customer-churn-case-study-300f2339de93?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/300f2339de93</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[classification]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sun, 30 Aug 2020 05:11:17 GMT</pubDate>
            <atom:updated>2022-04-25T07:17:45.094Z</atom:updated>
            <content:encoded><![CDATA[<h4>AI+ Tutorial</h4><h4>Using data to predict the probability of customer churn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x80C0vJ9RDsvE8Gn" /><figcaption>Photo by <a href="https://unsplash.com/@danielfazio?utm_source=medium&amp;utm_medium=referral">Daniel Fazio</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our last two posts, we have spent some time going through evaluation metrics for <a href="https://medium.com/swlh/evaluation-metrics-i-classification-a26476dd0146">classification models</a>.</p><p>In this post, we will go through a classification problem — Customer Churning. This dataset is part of a Data Science Nigeria (DSN) Pre-Bootcamp hackathon hosted on Zindi.</p><p>The goal is to predict customers that are likely to CHURN or stop using the network.</p><h4><strong>BACKGROUND</strong></h4><blockquote>Expresso is an African telecommunications company that provides customers with airtime and mobile data bundles. The objective of this challenge is to develop a machine learning model to predict the likelihood of each Expresso customer “churning,” i.e. becoming inactive and not making any transactions for 90 days.</blockquote><p>Customer Churn occurs when customers stop using the network. With this dataset we will <em>try</em> to understand customer behavior in order to accurately predict which customers are more likely to churn in the future.</p><h4>BUSINESS IMPLICATION</h4><p>These kinds of analyses are important to a service company. It equips companies to proper allocate resources in order to prevent customers leaving the company due to dissatisfaction or other reasons. For instance, the company may decide to give bonuses or reduce service charge altogether in order to keep customers.</p><p>In this dataset, the customers who churn are denoted by 1 and those who do not churn by 0. The trick is that the expected solution should not be in zeros or ones, the expected result is the <strong><em>probability</em></strong> of customers churning which can range from 0 to 1 inclusive. This information can be found in the <strong>Evaluation</strong> section which I advise you always go through before starting any competition so your hard work does not go down the drain.</p><p>If your results are not in probabilities, you will find yourself having high error values. Did I mention that the evaluation metric is <strong>Logarithmic Loss</strong>? If you went through our post <a href="https://medium.com/swlh/evaluation-metrics-i-classification-a26476dd0146">Evaluation Metrics I — Classification</a>, you should know that a good classifier has log loss values closer to 0.</p><p>This tutorial is beginner friendly is meant to provide a template to approach machine learning problems. We do not tackle processes such as Feature Engineering or go in-depth into feature selection. So don’t sweat it.</p><p>However, the winning codes for the competition will be linked below. While this is a straight forward tutorial, in competitions and real life applications, a lot of work is put into the data to draw meaningful insight — emphasis on <strong>meaningful</strong>. A method commonly used in competitions is <strong>ensemble learning. </strong>In Ensemble learning, multiple models are used to train the data and then combined through processes such as stacking or binning in order to improve the solution. <em>As they say, two good heads are better than one.</em></p><p>This solution is separated into the following parts:</p><ul><li>Import Libraries</li><li>Load Dataset</li><li>Data preparation and cleaning</li><li>Feature selection</li><li>Model training</li><li>Prediction</li><li>Model Evaluation</li></ul><h4><strong>DATA COLLECTION</strong></h4><p>One of the brighter sides of competitions is that we do not have to go through the hassle of obtaining our own data. In fact, it is against the rules to use data other than that strictly outlined for the competition. Data is the back bone of machine learning and as you might have guessed, very important. There are sites with free datasets, often in ready-to-use comma separated formats (csv) such as can be found on Kaggle or Zindi.</p><p>Data can be obtained from various sources, through various processes. One of these is data obtained from web pages through a process known as <strong>Web Scrapping</strong>. Be careful though, there are ethics surrounding scrapping websites especially pertaining private information.</p><h4><strong>IMPORT LIBRARIES</strong></h4><p>We will be using python for our data analysis. Python has libraries that are handy in reading data, visualizing data and manipulating data. The key libraries are:</p><p><strong>· Numpy</strong></p><p><strong>· Pandas</strong></p><p><strong>· Matplotlib and</strong></p><p><strong>· Seaborn</strong></p><p>We also have to import our model. We will be making use of the Logistic Regression model from scikit-learn.</p><p>To import libraries simply use the import function and the library name. For ease of use, longer names can be shortened using the <em>import … as… function </em>to import such models in a shorter alternative that is easy to use throughout the program.</p><p>Conventionally, numpy is imported as <strong>np</strong> and pandas as <strong>pd</strong>. So, wherever you see <strong>np</strong>, we are referring to numpy and likewise, <strong>pd</strong> is referring to pandas.</p><p>To import a particular module from a library, the <strong>from</strong> function is used. Importing a full library can be cumbersome and time consuming especially when we only need a little function or module. Hence instead of importing the full sklearn.linear_model package, we simply import what we need — <strong>LogisticRegression</strong>.</p><p>It is advisable to import all libraries at the beginning or top of the code. Nothing special, just neat coding.</p><h4><strong>DATA PREPARATION AND CLEANING</strong></h4><p>Data from different sources come in different formats. This can be structured or unstructured. If you carry out web scrapping, you are likely to have unstructured data. Lucky for us, our data is structured, we only have to worry about <a href="https://medium.com/@dsn_ph/data-quality-issues-dealing-with-missing-data-84f404006458">missing values</a>. Lucky for you, we have missing categorical and numerical values so you get to see us handle these missing values.</p><p>We will need to look at some information concerning the dataset to determine if there are null values. One way to check for null values is the <strong>df<em>.isnull().sum()</em></strong> function. <em>df</em> stands for <strong>dataframe</strong> which is the short term for the pandas dataframe the data is read into. The <em>.isnull()</em> function returns B<em>oolean</em> values. If a null value is found, the function returns <strong>True</strong>. With the <em>.sum()</em> function, we are able to sum all of the <strong>True</strong> instances to ascertain the total number of null values in a column.</p><p>A quicker way is to use the <strong>df.info()</strong> function which returns a quick summary of the data set. The <em>info()</em> function returns:</p><ul><li>The number of rows in a dataset</li><li>Number of columns</li><li>The data type of each column</li><li>The total non-null values of each column</li></ul><p>Of course, if the total number of non-null values do not equal the total number of entries in a column (rows), then we have missing values.</p><p>For the purpose of this tutorial we will try two approaches. For the REGION column, we will replace the null values with the mode value of the column while for the TOP_PACK column, we will replace the null values with a constant value.</p><p>For the numerical columns with missing data, we will use the <strong>fillna</strong> function to replace all null values with a constant value:<em> -99999.</em></p><h4><strong>DATA EXPLORATION</strong></h4><p>The purpose of data exploration is to gain key insight into the data — get to know your data better. Data exploration is the process of using visualizations to understand the relationship between features and target variables. Visualizations are fun! They turn a boring notebook into a beautiful one. Common visualization packages include:</p><ul><li>Matplotlib</li><li>Seaborn</li><li>Plotly</li><li>ggplot</li><li>Bokeh</li></ul><p>…and so much more. Even pandas can be used for basic visualizations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e539fb4ebd69b89eb6f41c65bcbdf8b5/href">https://medium.com/media/e539fb4ebd69b89eb6f41c65bcbdf8b5/href</a></iframe><h4><strong>FEATURE SELECTION</strong></h4><p>Features are the input to the model. The features are the columns in the dataset. They are also called attributes. Our work, is to determine which features provide more insight — quality over quantity. A large number of features does not equate to better model prediction.</p><p>Another step carried out on features is <strong>Feature Engineering. </strong>Feature Engineering is the process of extracting features from data. Available features are usually computed in order to form new ones that produce better results. This can be through a number of ways such as: Adding features together, averaging features; multiplication, division, subtraction or even scalar multiplication of the available features.</p><p>Feature Engineering is not within the scope of this tutorial, but feature engineering is an important technique in data analysis.</p><h4>MODEL TRAINING</h4><p>Time to get our hands dirty with our model. To train our model, we simply fit our model to the training features. This is the models first contact with the data. This is the easy part. We have picked our features (maybe even engineered new ones), all we have to do is to fit the algorithm to the data and voila! Model is trained. This shouldn’t take long but depending on your number of features, it can take a little longer.</p><p>Here we use the <strong>train_test_split</strong> function from <em>sklearn.model_selection</em> to split the train data. Why? The train data is the only part of the dataset that is labeled — supervised classification — and we are making use of the logistics regression algorithm, a supervised classification algorithm. So we train the model with one part and then test it with the <strong>test portion of the train data</strong>.</p><h4>PREDICTION</h4><p>If you thought model fitting was easy, this is way easier. After fitting our data, we can now make predictions using our data. There is a catch however, remember our output should be the probability that a customer churns and not a binary output of 0 or 1.</p><p>Here, we will make use of the <strong>predict_proba</strong> function to return the probability values instead.</p><h4>MODEL EVALUATION</h4><p>We are not done yet. Now we have to compare our predictions with our actual values to determine our model’s prediction performance.</p><p>The evaluation metric by which we gauge our model’s performance is Log loss. We can import the log loss metric from <em>sklearn.metrics</em> and use it to evaluate our model performance.</p><p>Our log_loss value is 0.30****. Not bad… But we can definitely do better. The winning solution had a log_loss value of 0.24.</p><p>The accuracy score of the model is 0.859, we can definitely do better.</p><h4>IMPROVING MODEL PERFORMANCE</h4><p>Moving on, we can tweak the model parameters. Maybe increase the number of max iterations or plug in some other model parameters. A visit to the sklearn Logarithmic Regression <a href="https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html">documentation</a> will help.</p><p>Another way the accuracy can be improved is through feature selection and engineering. Did we choose the right features in the first place, maybe we can take some out or bring back some that we dropped. The TENURE column can be worked on so that its values are integer. These are some starting points.</p><p>Tried the above options and your model is no better? Try Ensemble Learning. You may be surprised by how well your combined algorithms perform compared to one <em>good</em> algorithm.</p><p>You may have noticed we merged two datasets — the train and test — and then split them again. This is not necessary, but you must know that whatever operation you carry out on one dataset, you have to carry out on the other. Those are the assumptions we make and our model will only perform accordingly when those assumptions are made. If you keep them apart, you will have to carry out operations doubly.</p><h4>Winning Solutions:</h4><p>First Place <a href="https://github.com/marx-keyz/Winning-Solution-Expresso-Churn-Prediction-Challenge-by-DSN">Solution</a> by Maxprop</p><p>Second place <a href="https://github.com/KolatimiDave/Expresso-Customer-Churn-Prediction">Solution</a> by Kolatimi Dave</p><p><strong>Bonus:</strong></p><p><a href="https://github.com/aifenaike/DSN_PreBootcamp_Hackathon/blob/master/Aifenaike_DSNhackathon_solution.ipynb">Solution</a> by Aifenaike</p><h4>CONCLUSION</h4><p>In this tutorial, we have applied our knowledge of evaluation metrics. We have determined that although the model does a good job classifying labels, it can be further improved using some of the recommendations outlined above.</p><p>We have also looked at a practical example of applying machine learning to business problems. With this we round up our discussion on evaluation metrics for classification models.</p><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=300f2339de93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluation Metrics II: Classification Evaluation Curves]]></title>
            <link>https://dsnph.medium.com/evaluation-metrics-ii-classification-evaluation-curves-5988e02543f?source=rss-f197e2364a64------2</link>
            <guid isPermaLink="false">https://medium.com/p/5988e02543f</guid>
            <category><![CDATA[evaluation-metric]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dsnaiph]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[AI+ Port Harcourt]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 04:32:26 GMT</pubDate>
            <atom:updated>2022-04-25T07:17:00.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QF0G-ag9o5XzT04Z" /><figcaption>Photo by <a href="https://unsplash.com/@keilahoetzel?utm_source=medium&amp;utm_medium=referral">Keila Hötzel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In our previous post, we discussed the Evaluation Metrics for Classification models with emphasis on the Confusion matrix, accuracy, precision, recall and log loss metrics. You can read the post <a href="https://medium.com/@dsn_ph/evaluation-metrics-i-classification-a26476dd0146">here</a> to understand the basic evaluation metrics.</p><p>By evaluating our models, we assess their performance using key parameters and functions. Model evaluation is an integral step in the machine learning pipeline and we evaluate our models for a number of reasons. Most importantly, we evaluate models to ascertain that they are able to generalize on unseen data and therefore produce accurate predictions. As models are trained using past data, how they perform on future data to predict target outcomes can only be gauged through the process of model evaluation.</p><p>Model evaluation is also carried out to ensure that the model does not overfit the training data. Overfitting occurs when a model has memorized the target values for our data set and performs excellently on training data but perform poorly when fitted to new data.</p><p>We also evaluate models to determine the model that gives the highest accuracy for a dataset. It is common practice to fit various models to a dataset in order to determine which model makes the most accurate predictions.</p><p>It is advisable to evaluate model performance on data different from the training data.</p><p>Evaluation techniques include:</p><ul><li><strong>Holdout: </strong>In this technique, the dataset is randomly divided into the<strong> Training, Validation and Test set</strong>. The training set is used to fit the model. During training, the model <em>learns</em> the relationships between the input features and target output. The Validation set is used to assess model learning ability and adjust model parameters if need be. <strong>Weak learners</strong> are models that do not accurately define the relationship between the input and output variables while <strong>strong learners</strong> are capable of identifying the relationship between the input features and target output. The test or holdout set is then used to assess the model’s performance after training and validation have been carried out.</li><li><strong>Cross validation</strong>: In this technique, model training and testing is carried out on two separate datasets. There are different cross validation methods such as the train_test_split and the k-folds validation. The methods of Cross validation are not within our scope but you can read about them <a href="https://www.analyticsvidhya.com/blog/2018/05/improve-model-performance-cross-validation-in-python-r/">here</a>.</li></ul><p>In this post, we will discuss two curves commonly used to evaluate the performance of Classification models: the ROC curve and Precision-Recall curve.</p><h3><strong>Receiver Operating Characteristic Curve(ROC)</strong></h3><p>The ROC Curve is a plot of the True Positive rate(recall) vs the false positive rate. <strong>Recall</strong> as we learnt in our previous post, is the ratio of positive cases that the model accurately classifies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*4qfrT76JfK5JHClH6HdIHQ.png" /><figcaption>Recall</figcaption></figure><p>The <strong>False Positive Rate</strong> is the proportion of negative classes that are classified as positive classes by the model. Let us continue with our Cancer Classification problem, if we assign a negative instance to benign cancers (0) and a positive instance to the malignant cancers(1), with the goal of identifying cases of malignant cancers, the <strong>False Positive Rates</strong> are the cases of benign cancer that are misclassified as malignant cancer. We can therefore call these <em>False Alerts</em>.</p><p>FPR, also known as Fall-out is defined by the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*jOoltcAkIyNYNh9HrgSsWQ.png" /><figcaption>False Positive Rate</figcaption></figure><p><strong>Specificity</strong> is the True Negative Rate which is the proportion of negative classes which the model classifies as negative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*RqwzgfDriEi0AR3ZZ-HbrA.png" /><figcaption>Specificity</figcaption></figure><p>The ROC curve can therefore be defined as the plot of <strong>recall</strong> versus <strong>(1 — specificity)</strong>. The ROC curve is a probability curve and the goal is to identify the false negatives.</p><p>The ideal ROC curve is close to the top left corner of the plot, a classifier with high recall and low false positive rate. The ROC curve is a good method to compare performance of different Classification models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*4ejMy9RXc_5f9-ojfzkfxg.png" /></figure><p>The diagonal line from the origin to the point (1,1) represents a random model.</p><p>Model with high True Positive Values and Low False Positive values are more accurate. From our ROC curve above, we can see that the green classifier is the most accurate followed by the purple, blue and red classifiers in that order.</p><p>The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html">Sklearn</a> roc_curve function is used to draw an ROC curve. The example below was pulled from the sklearn roc_curve documentation.</p><pre><strong>import</strong> <strong>numpy</strong> <strong>as</strong> <strong>np</strong><br><strong>from</strong> <strong>sklearn</strong> <strong>import</strong> metrics<br>fpr, tpr, thresholds = metrics.roc_curve(y, scores, pos_label=2)</pre><p>The threshold values range from 0 to 1. The threshold determines the True positive or False positive rate. This is because values below and above the thresholds fall into different classes.</p><p>In our Cancer example, if we set a threshold of 0.5, then values above 0.5 indicate a malignant cancer while values below indicate benign cancers. If we adjust our threshold value to 0.7, then the range of values for malignant cancers in reduced. Model recall is reduced and specificity increases.</p><p>Likewise if we reduce the threshold, there are more positive values and recall increases while specificity reduces.</p><p>The ROC can be plotted for varying threshold values to determine the optimum threshold value or plotted for different classifiers to determine the best model. The ROC is best suited for binary classification problems but can be extended for multiclass classification problems.</p><p><strong>Area Under Curve (AUC)- ROC</strong></p><p>The Area Under Curve is a summary value of the ROC curve. As the name suggests, it is the value of the area that lies beneath the ROC curve. The AUC ranges from 0 for a poor classifier to 1 which is the maximum value of the area under the ROC curve. Therefore an AUC value closer to 1 indicates an accurate model which is able to differentiate between the classes in a classification problem. The AUC can also be used to compare the performance of various classifiers.</p><p>An AUC value of 0.5 represents a random classifier.</p><pre><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> roc_auc_score<br>roc_auc_score(y_true, y_scores)</pre><p>Here is a <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html">link</a> to the sklearn roc_auc_score.</p><h3><strong>Precision-Recall Curve</strong></h3><p>The precision-recall curve is a plot of the recall on the x-axis and precision on the y-axis. <strong>Precision</strong> measures the number of positive values predicted by the model that are actually positive and <strong>Recall</strong> determines the proportion of the positives values that were accurately predicted. The precision-recall curve allows us to view the precision-recall relationship at a glance and is especially useful in <strong>imbalanced class classification</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*5MofYEOpCPhWyTzMjjjLMg.png" /></figure><p>The <a href="https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_recall_curve.html">Precision-Recall</a> curve of a good classifier is closer to the top right corner of the plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*bsStKDBf6NjKakzf96b1rA.png" /></figure><pre><strong>from</strong> <strong>sklearn.metrics</strong> <strong>import</strong> precision_recall_curve<br>precision, recall, thresholds = precision_recall_curve(y_true, y_scores)</pre><p>While the ROC curve compares the True Positive Rate and False Positive Rates, the Precision-Recall curve compares the Precision and Recall of models.</p><p>The Area Under Curve of the <a href="https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html#:~:text=The%20precision%2Drecall%20curve%20shows,a%20low%20false%20negative%20rate.">Precision-Recall Curve</a> (AUCPRC) can also be determined using Trapezoidal rule. A high AUCPRC value — one — indicates that the model has high precision and recall.</p><p>A horizontal line in the Precision-Recall plot indicates a poor classifier and AUCPRC of zero</p><h3>Conclusion</h3><p>When working with a problem, you should outline your target output and its interpretation. Knowing this will help you determine what evaluation model to use.</p><p>In a breast cancer classification problem, we are concerned with high Recall — low False Negative — value so as to capture all cases of malignant cancer even if some benign cancers are classified as malignant. In an attrition model, Sensitivity is our main focus and Accuracy is best used in balanced classification problems. Need I go on?</p><p>Here, we have learnt that Precision-Recall curves are better suited to imbalanced classification than ROC. We have also looked at the importance of Evaluating models and briefly outlined the model evaluation techniques.</p><p>Thanks to libraries such as scikit-learn, a deep understanding of these metrics may not be required but it is always good to know when to apply each metric to obtain required results.</p><h4>REFERENCES</h4><ul><li><strong>Hands-on Machine Learning with Scikit-Learn, Keras, and TensorFlow</strong> by Aurélien Géron</li><li>Udacity Microsoft Azure Foundation Course Lesson 3.25: <strong>Evaluation Metrics for Classification</strong></li><li>11 Important Model Evaluation Error Metrics, <a href="https://www.analyticsvidhya.com/blog/2019/08/11-important-model-evaluation-error-metrics/">Analyticsvidhya</a></li><li>Scikit-learn dicumentations</li><li>Training Sets, Validation Sets, and Holdout Sets; <a href="https://www.datarobot.com/wiki/training-validation-holdout/">DataRobot</a></li><li>Understanding AUC-ROC Curve; Towards Data Science <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">Publication</a></li></ul><p>Written by <a href="https://www.linkedin.com/in/anita-igbine-0a4282150">Anita Igbine</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5988e02543f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>